language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
1,535
2.640625
3
[ "MIT" ]
permissive
import {config, a} from './config.js' /** Manages the lose place sprite and related sounds */ export default class LosePlace { constructor(width, height, scene) { this.width = width; this.height = height; this.scene = scene; const lp = config.losePlace; scene.load.image('losePlace', a(lp.image)); scene.load.audio('losePlace', a(lp.ambientSound)); scene.load.audio('lose', a(lp.loseSound)); } create() { this.losePlaceSprite = this.scene.add.sprite(this.scene.xPos(0), 0, 'losePlace'); this.losePlaceSprite.setScale(0.6); this.losePlaceSprite.setY(this.height - this.losePlaceSprite.displayHeight / 2); this.losePlaceSound = this.scene.sound.add('losePlace', {loop: true}); this.setAmbientVolume(0); this.losePlaceSound.play(); this.loseSound = this.scene.sound.add('lose'); this.loseSound.setVolume(0.7); } setAmbientVolume(volume) { this.losePlaceSound.setVolume(volume); } lose() { this.loseSound.play(); } /** Makes the lose place grow to cover the background, while reducing opacity so the score will still show */ consumeTheWorld() { if (!this.consuming) { this.consuming = true; this.scene.tweens.add({targets: [this.losePlaceSprite], scaleX: 3, scaleY: 3, alpha: 0.5, x: this.width / 2, y: this.height / 2, duration: 1000}); } } }
Java
UTF-8
939
3.109375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Semana01.Trabajos; import java.util.Scanner; /** * * @author Ario1 */ public class Ejercicio35 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Ingres n alumanos a evaluar:"); int nAlu= sc.nextInt(); double nota=0,porcentaje=0,suma=0; int reprobados=0,i=1; do { System.out.println("Alumno: "+i); nota=sc.nextDouble(); if (nota<70) { reprobados++; } nAlu--; i++; suma++; } while (nAlu!=0); porcentaje=(reprobados*100)/suma; System.out.println("Porcentaje de reprobados : "+porcentaje+" %"); } }
C
UTF-8
1,256
2.75
3
[]
no_license
#include "stdh.h" #include "smart_buf.h" #include "profile.h" #include "connection.h" #include "buffer_list.h" #include "macros.h" #include "util.h" BUFFER_LIST *buffer_list_free_list = 0; long buffer_list_count = 0; BUFFER_LIST *buffer_list_create() { BUFFER_LIST *buffer_list; NewObject(buffer_list_free_list, buffer_list, BUFFER_LIST) buffer_list_count++; buffer_list->state = BUFFER_LIST_CREATED; buffer_list->buf = smart_buf_create(1024); return buffer_list; } // only call this during a cleanup phase void buffer_list_free(CONNECTION *connection, BUFFER_LIST *obj) { RemoveFromList(connection->buffer_list, obj) obj->state = BUFFER_LIST_REMOVED; smart_buf_free(obj->buf); AddToList(buffer_list_free_list, obj) buffer_list_count--; } // goes through each buffer list object and sees if it is a certain // state, and then removes it from the list. this isn't "exactly" // thread safe, but is the best compromise I came up with before // getting into locks void buffer_list_cleanup(CONNECTION *connection) { BUFFER_LIST *obj, *obj_next; for(obj = connection->buffer_list; obj; obj = obj_next) { obj_next = obj->next; if(obj->state == BUFFER_LIST_READ_FINISHED) { buffer_list_free(connection, obj); continue; } } }
Markdown
UTF-8
2,425
2.671875
3
[ "MIT" ]
permissive
# backend baseUrl: https://water-my-plants-ptct.herokuapp.com Auth Endpoints | Required Fields | Description POST REQUESTS: /api/auth/login | username, password | login user and set token [test user]: username= test, password= test /api/auth/register | username, phone, password | register user and save credentials to server, username/phone must be unique (non-duplicates in system), username must be a string that is min 3 chars long and phone # must be 10 digits long /api/auth/logout | user must be logged in | Allows user to logout and remove token and session id PUT REQUESTS: /api/auth/users/:id | phone OR password | User can update their phone number or password. Phone number must be unique (non-duplicates in system) Plant Endpoints | Required Fields / Token | Description GET REQUESTS: /api/plants | Token Required | Get's a list of all plants in database /api/plants/:id | Token Required | Get's a specific plant based on the plant_id /api/plants/user/:id | Token Required | Gets a list of plant data from a specific user id POST REQUESTS: /api/plants | Token Required, Required Fields: | Creates a new plant and returns an object. Optional: User can insert an image url to be saved to nickname, species, h2oFrequency, database. Ex: https://thumbs.dreamstime.com/z/cambria-orchid-plant-blooming-white-38131910.jpg user_id, photo(optional, user can insert an image url) PUT REQUESTS: /api/plants/:id | Token Required, Required Fields: | Allows user to update information about a specific plant based on the plant_id user can update any of the plant fields (nickname, species, h20frequency, etc) DELETE_REQUESTS: /api/plants/:id | Token Required | Allows user to delete a specific plant based on the plant_id
Markdown
UTF-8
1,419
2.71875
3
[]
no_license
# Flex(Flexbox) 1. ## [#01 Flex](flex01/README.md) - Flexbox 등장 배경 및 설명 2. ## [#02 Flex](flex02/README.md) - Flex 사용법(Flex-container, Flex-item) 3. ## [#03 Flex](flex03/README.md) - Flex를 사용한 레이아웃 <br><br> > **참고** > > - MDN Web Docs > > <https://developer.mozilla.org/ko/docs/Web/CSS/CSS_Flexible_Box_Layout/Flexbox%EC%9D%98_%EA%B8%B0%EB%B3%B8_%EA%B0%9C%EB%85%90> > > <https://developer.mozilla.org/en-US/docs/Web/CSS/flex_value> > > - w3schools > > <https://www.w3schools.com/cssref/css3_pr_flex.asp> > > - 생활코딩 > > <https://www.opentutorials.org/course/2418/13526> > > - Understanding Flexbox > > <https://www.vobour.com/1-flexbox-%EC%9D%B4%ED%95%B4-%EB%8B%B9%EC%8B%A0%EC%9D%B4-%EC%95%8C%EC%95%84%EC%95%BC-%ED%95%A0-%EB%AA%A8%EB%93%A0-%EA%B2%83-understa> > > - Flexbox Froggy(Game) > > <https://flexboxfroggy.com/#ko](https://flexboxfroggy.com/#ko> > > - caniuse > > <https://caniuse.com/#search=flex](https://caniuse.com/#search=flex> > > - Microsoft Docs > > <https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dev-guides/hh673531(v=vs.85)> > > <https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/dn265027(v=vs.85)> > > - blog > > <https://heropy.blog/2018/11/24/css-flexible-box/> > > <https://webdir.tistory.com/349>
C#
UTF-8
6,119
3.40625
3
[ "MIT" ]
permissive
using System; namespace TwistedLogik.Ultraviolet.Graphics.Graphics2D.Text { /// <summary> /// Represents a layout command to print a string of text. /// </summary> public struct TextLayoutTextCommand { /// <summary> /// Initializes a new instance of the <see cref="TextLayoutTextCommand"/> structure. /// </summary> /// <param name="textOffset">The offset from the beginning of the source string to the beginning of the /// substring which will be rendered by this command.</param> /// <param name="textLength">The number of characters that will be rendered by this command.</param> /// <param name="textX">The x-coordinate of the top-left corner of the text relative to its layout area.</param> /// <param name="textY">The y-coordinate of the top-left corner of the text relative to its layout area.</param> /// <param name="textWidth">The width of the text in pixels.</param> /// <param name="textHeight">The height of the text in pixels.</param> public TextLayoutTextCommand(Int32 textOffset, Int32 textLength, Int32 textX, Int32 textY, Int16 textWidth, Int16 textHeight) { this.commandType = TextLayoutCommandType.Text; this.textOffset = textOffset; this.textLength = textLength; this.textX = textX; this.textY = textY; this.textWidth = textWidth; this.textHeight = textHeight; } /// <summary> /// Gets the absolute position of the text when rendered. /// </summary> /// <param name="x">The x-coordinate of the top-left corner of the line of text that is being rendered.</param> /// <param name="y">The y-coordinate of the top-left corner of the line of text that is being rendered.</param> /// <param name="lineHeight">The height of the line of text that is being rendered.</param> /// <returns>A <see cref="Point2"/> that describes the absolute position of the text.</returns> public Point2 GetAbsolutePosition(Int32 x, Int32 y, Int32 lineHeight) { return new Point2(x + textX, y + textY + ((lineHeight - textHeight) / 2)); } /// <summary> /// Gets the absolute position of the text when rendered. /// </summary> /// <param name="x">The x-coordinate of the top-left corner of the line of text that is being rendered.</param> /// <param name="y">The y-coordinate of the top-left corner of the line of text that is being rendered.</param> /// <param name="lineHeight">The height of the line of text that is being rendered.</param> /// <returns>A <see cref="Vector2"/> that describes the absolute position of the text.</returns> public Vector2 GetAbsolutePositionVector(Single x, Single y, Int32 lineHeight) { return new Vector2(x + textX, y + textY + ((lineHeight - textHeight) / 2)); } /// <summary> /// Gets the absolute bounds of the text when rendered. /// </summary> /// <param name="x">The x-coordinate of the top-left corner of the line of text that is being rendered.</param> /// <param name="y">The y-coordinate of the top-left corner of the line of text that is being rendered.</param> /// <param name="lineHeight">The height of the line of text that is being rendered.</param> /// <returns>A <see cref="Rectangle"/> that describes the absolute bounds of the text.</returns> public Rectangle GetAbsoluteBounds(Int32 x, Int32 y, Int32 lineHeight) { return new Rectangle(x + textX, y + textY + ((lineHeight - textHeight) / 2), textWidth, textHeight); } /// <summary> /// Gets the command type. /// </summary> public TextLayoutCommandType CommandType { get { return commandType; } } /// <summary> /// Gets the offset from the beginning of the source string to the beginning of the substring /// which will be rendered by this command. /// </summary> public Int32 TextOffset { get { return textOffset; } internal set { textOffset = value; } } /// <summary> /// Gets the number of characters that will be rendered by this command. /// </summary> public Int32 TextLength { get { return textLength; } internal set { textLength = value; } } /// <summary> /// Gets the x-coordinate of the top-left corner of the text relative to its layout area. /// </summary> public Int32 TextX { get { return textX; } internal set { textX = value; } } /// <summary> /// Gets the y-coordinate of the top-left corner of the text relative to its layout area. /// </summary> public Int32 TextY { get { return textY; } internal set { textY = value; } } /// <summary> /// Gets the width of the text in pixels. /// </summary> public Int16 TextWidth { get { return textWidth; } internal set { textWidth = value; } } /// <summary> /// Gets the height of the text in pixels. /// </summary> public Int16 TextHeight { get { return textHeight; } internal set { textHeight = value; } } /// <summary> /// Gets the bounds of the text drawn by this command relative to the layout area. /// </summary> public Rectangle Bounds { get { return new Rectangle(textX, textY, textWidth, textHeight); } } // Property values. private readonly TextLayoutCommandType commandType; private Int32 textOffset; private Int32 textLength; private Int32 textX; private Int32 textY; private Int16 textWidth; private Int16 textHeight; } }
TypeScript
UTF-8
2,144
4.1875
4
[]
no_license
// 泛型 // 除了泛型接口,我们还可以创建泛型类,无法创建泛型枚举和泛型命名空间。 // 泛型类指的是实例部分的类型,静态属性不能使用泛型类型。 function identity1(arg: number): number { return arg; } function identity2(arg: any): any { return arg; } // 泛型函数 function identity<T>(arg: T): T { return arg; } function loggingIdentity<T>(arg: T[]): T[] { console.log(arg.length); return arg; } function loggingIdentity1<T>(arg: Array<T>): Array<T> { console.log(arg.length); return arg; } let output = identity<string>('myString'); // 泛型函数类型 let myIdentity: <T>(arg: T) => T = identity; let myIdentity1: <U>(arg: U) => U = identity; let myIdentity2: { <T>(arg: T): T } = identity; // 泛型接口 interface GenericIdentityFn { <T>(arg: T): T; } let myIdentity3: GenericIdentityFn = identity; interface GenericIdentityFn1<T> { (arg: T): T } let myIdentity4: GenericIdentityFn1<number> = identity; // 泛型类 class GenericNumber<T> { zeroValue: T; add: (x: T, y: T) => T; } let myGenericNumber = new GenericNumber<number>(); myGenericNumber.zeroValue = 0; myGenericNumber.add = function (x, y) { return x + y; }; let stringNumeric = new GenericNumber<string>(); stringNumeric.zeroValue = ''; stringNumeric.add = function (x, y) { return x + y; }; console.log(stringNumeric.add(stringNumeric.zeroValue, 'test')); // 泛型约束 interface Lengthwise { length: number; } function loggingIdentity2<T extends Lengthwise>(arg: T): T { console.log(arg.length); return arg; } loggingIdentity2({ length: 1, value: 3 }); // 在泛型约束中使用类型参数 // 在泛型里使用类类型 function create<T>(c: { new(): T }): T { return new c(); } class BeeKeeper { hasMask: boolean; } class ZooKeeper { nametag: string; } class Animal { numLegs: number; } class Bee extends Animal { keeper: BeeKeeper; } class Lion extends Animal { keeper: ZooKeeper; } function createInstance<A extends Animal>(c: new () => A): A { return new c(); } createInstance(Lion).keeper.nametag; createInstance(Bee).keeper.hasMask;
Markdown
UTF-8
2,659
2.65625
3
[]
no_license
## Backing up a raspberrypi or emoncms.org account ### Backing up your emoncms.org account (or other remote server account) **(Optional) To view your data on the backup computer install emoncms on your backup computer following the guide here:** [http://emoncms.org/site/docs/installlinux](http://emoncms.org/site/docs/installlinux) Create an account and note down your mysql credentials. 1) Download the usefulscripts repository: [https://github.com/emoncms/usefulscripts](https://github.com/emoncms/usefulscripts) 2) Open Backup/backup.php in a text editor. - Set $remote_server and $remote_apikey to correspond to the remote emoncms account you wish to download from. - Set $link\_to\_local\_emoncms to true if you wish to access your data within a local installation of emoncms. Set $local\_emoncms\_location and $local\_emoncms\_userid to link to your local emoncms installation. - Set $link\_to\_local\_emoncms to false if you just want to download the data without linking to a local emoncms install (non-mysql data only). Set $dir to the directory on your computer you wish to download the data. Manually create the folders: phpfina, phpfiwa, phptimeseries, phptimestore within this folder. 3) Run the backup script from terminal with: php backup.php Tested with emoncms.org (v8.0.9: 4 July 2014), and local emoncms v8.2.8 That's it, it should now work through all your feeds. When you first run this script it can take a long time. When you run this script again it will only download the most recent data and so will complete much faster. ### Backing up a full emoncms installation (raspberrypi install or your own server) Start by making a backup of your emoncms data and emoncms application folder. To export a backup of your emoncms mysql data: mysqldump -u root -p emoncms > emoncms_backup.sql Or if you have a lot of feed data stored in mysql, you can export the meta data only with: mysqldump -u root -p emoncms users input feeds dashboard multigraph > emoncms_backup.sql You can make a direct directory copy of the /var/lib/mysql/emoncms folder if the mysql dump is too large. Make a backup copy of the feed data folders on your system, the default locations on linux are: /var/lib/phpfiwa /var/lib/phpfina /var/lib/phptimeseries /var/lib/timestore **Important** Make sure you disable oem\_gateway/emonhub or raspberrypi\_run and any posting to the http api's (stop apache) before copying the data files so that when you make the copy the data is in a state where its not being written to. Make a copy of the emoncms application folder usually found under /var/www/emoncms
C++
UTF-8
904
3.125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> int knapSack(int W, int wt[], int val[], int n) { int i, w; std::vector<int> row(W+1, 0); std::vector<std::vector<int>> K(n+1, row); //K.reserve(n + 1); //for (std::vector<int> row : K) // row.reserve(W + 1); // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = std::max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } return K[n][W]; } int main() { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = sizeof(val) / sizeof(val[0]); printf("%d", knapSack(W, wt, val, n)); return 0; }
Java
UTF-8
515
2.546875
3
[]
no_license
package unsw.dungeon; import javafx.beans.property.BooleanProperty; /** * An abstract class for an ItemEntity */ public abstract class ItemEntity extends Entity { /** * Constructor for item entity * * @param x coordinate position of entity * @param y coordinate position of entity * @param dungeon entity belongs to */ public ItemEntity(int x, int y, Dungeon dungeon) { super(x, y, dungeon); } public abstract BooleanProperty isPickedUp(); }
C#
UTF-8
12,012
2.765625
3
[ "BSD-3-Clause" ]
permissive
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Abot.Poco; using Spider.Infrastructure; using Spider.Interface; using Spider.Models; using HtmlAgilityPack; using Spider.Models.Domain; using Spider.Models.Result; using Spider.Repository; namespace Spider.Engine { public class PageAnalyzer { private readonly IEnumerable<CrawledPage> _pages; private readonly String _category; private readonly Dictionary<string, ISheetRow> _urlDictionary; public PageAnalyzer(IEnumerable<CrawledPage> pages, string category, Dictionary<string, ISheetRow> urlDict) { _pages = pages; _category = category; _urlDictionary = urlDict; } /// <summary> /// Kickoff method to analyze pages asyncronously /// </summary> /// <returns></returns> public async Task<IList<ISheetRow>> AnalyzeAsync() { if (_pages == null || !_pages.Any()) { throw new InvalidOperationException("Cannot begin analyzing null pages. Set pages in constructor."); } return await Task.Run(() => AnalyzePages()); } /// <summary> /// Magic page analyzing goes in here /// </summary> /// <returns></returns> private IList<ISheetRow> AnalyzePages() { Trace.WriteLine($"begin analyzing {_pages.Count()} pages in new thread"); var results = new List<ISheetRow>(); switch (_category) { case Constants.FileCategory.Roster: results = AnalyzeRosterUrls(); break; } Trace.WriteLine("returning from analyzer thread"); return results; } private List<ISheetRow> AnalyzeRosterUrls() { foreach (var page in _pages) { var html = page.HtmlDocument; // assume the roster will be in a table. grab all tables var tables = html.DocumentNode.SelectNodes("//table"); if (tables == null) { continue; // move to next page } var playerList = new List<Player>(); foreach (var table in tables) { // look for table header. if not found, use first row var tHead = table.SelectSingleNode("//thead"); var firstRow = tHead != null ? tHead.SelectSingleNode("./tr") : table.SelectSingleNode(".//tr"); // Couldn't get a first row; just discard this table if (firstRow == null) { continue; } // get cells of first row. determine column names from this row var headerCells = firstRow.SelectNodes("./th | ./td"); // look for player number column var playerNumberCell = headerCells.FirstOrDefault(cell => RegexRepository.NumberColumnRegex.IsMatch(cell.InnerText)); // get index of this column var playerNumberCellIndex = headerCells.IndexOf(playerNumberCell); // Look for a full name column; if not found, check next table if (!headerCells.Skip(playerNumberCellIndex + 1).Any(n => RegexRepository.NameColumnRegex.IsMatch(n.InnerText))) { continue; } // Get column indices for data that we want var playerNameIndex = headerCells.IndexOf(headerCells.FirstOrDefault(n => RegexRepository.NameColumnRegex.IsMatch(n.InnerText))); var classColumnIndex = headerCells.IndexOf( headerCells.FirstOrDefault(n => RegexRepository.ClassColumnRegex.IsMatch(n.InnerText))); var positionColumnIndex = headerCells.IndexOf( headerCells.FirstOrDefault(n => RegexRepository.PositionColumnRegex.IsMatch(n.InnerText))); var majorColumnIndex = headerCells.IndexOf( headerCells.FirstOrDefault(n => RegexRepository.MajorColumnRegex.IsMatch(n.InnerText))); var numColsInTable = headerCells.Count; // If there was a <thead> hopefully there's a <tbody> // If so, capture all the rows in <tbody>. Otherwise, // get all rows in this table except the first one HtmlNodeCollection dataRows; var tableBody = table.SelectSingleNode("//tbody"); if (tableBody != null) { dataRows = tableBody.SelectNodes(".//tr"); } else { dataRows = table.SelectNodes(".//tr[position()>=1]"); } // iterate over each row, skipping rows with different numbers // of columns than in the header row. For each matching row, // get the player name and player URL from the appropriate // columns. if (dataRows != null) { foreach (var row in dataRows) { // keep cell index counts for each loop iteration -- will change if headshot column exists //var tempPlayerNumberCellIndex = playerNumberCellIndex; var tempPlayerNameIndex = playerNameIndex; var tempClassColumnIndex = classColumnIndex; var tempPositionColumnIndex = positionColumnIndex; var tempMajorColumnIndex = majorColumnIndex; var rowCells = row.SelectNodes("./td"); if (rowCells == null || rowCells.Count != numColsInTable) { /* Check if the first column of this row is a hidden column for headshots. This is fairly common, but throws off our counts. Need to increment our column counts if so. */ if (rowCells != null && rowCells.Any() && rowCells[0].Attributes["class"] != null && rowCells[0].Attributes["class"].Value == "headshot") { // Only increment these values if > 0; if they are < 0 it means they don't exist as a column tempPlayerNameIndex = tempPlayerNameIndex < 0 ? tempPlayerNameIndex : tempPlayerNameIndex + 1; tempClassColumnIndex = tempClassColumnIndex < 0 ? tempClassColumnIndex : tempClassColumnIndex + 1; tempPositionColumnIndex = tempPositionColumnIndex < 0 ? tempPositionColumnIndex : tempPositionColumnIndex + 1; tempMajorColumnIndex = tempMajorColumnIndex < 0 ? tempMajorColumnIndex : tempMajorColumnIndex + 1; } else { continue; } //continue; } var playerCell = rowCells[tempPlayerNameIndex]; var playerUrlTag = playerCell.SelectSingleNode("a") ?? playerCell.SelectSingleNode(".//a"); if (playerUrlTag == null) { continue; } var playerName = playerUrlTag.InnerText.Trim(); // check if name is listed LAST, FIRST and if so, reverse it if (playerName.Contains(",")) { var nameArray = playerName.Split(','); if (nameArray.Length == 2) // if length isn't two, just leave the name alone { playerName = String.Empty; playerName += nameArray[1] + " "; playerName += nameArray[0]; } } // find out more info about player here (position? height/weight? class?) // get player year/class (freshman, sophomore, etc) var playerClass = String.Empty; if (tempClassColumnIndex > 0) { var classCell = rowCells[tempClassColumnIndex]; playerClass = classCell.InnerText.Trim(); } // get player position var playerPosition = String.Empty; if (tempPositionColumnIndex > 0) { var positionCell = rowCells[tempPositionColumnIndex]; playerPosition = positionCell.InnerText.Trim(); } var playerMajor = String.Empty; if (tempMajorColumnIndex > 0) { var majorCell = rowCells[tempMajorColumnIndex]; playerMajor = majorCell.InnerText.Trim(); } var newPlayer = new Player() { FirstLast = playerName, Class = playerClass, Position = playerPosition, Major = playerMajor }; // Check we don't already have this player. Some pages have massive duplicates that must be accounted for if (!playerList.Exists(p => Player.Equals(p, newPlayer))) { playerList.Add(newPlayer); } } } } // find this Url in the dictionary and add the list of player results if (_urlDictionary.ContainsKey(page.Uri.ToString())) { var pageRosterSheet = _urlDictionary[page.Uri.ToString()]; pageRosterSheet.Results = new RosterResult() { Players = playerList }; } else { //throw new InvalidOperationException("On page we aren't supposed to be on. " + page.Uri.ToString()); // We are on a URL not in the dictionary. skip continue; } } // figure out a way to return this stuff return _urlDictionary.Values.ToList(); } } }
C#
UTF-8
1,032
2.828125
3
[ "MIT" ]
permissive
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System { // // This simple class enables one to throw a NotImplementedException using the following // idiom: // // throw NotImplemented.ByDesign; // // Used by methods whose intended implementation is to throw a NotImplementedException (typically // virtual methods in public abstract classes that intended to be subclassed by third parties.) // // This makes it distinguishable both from human eyes and CCI from NYI's that truly represent undone work. // internal static class NotImplemented { internal static Exception ByDesign { get { return new NotImplementedException(); } } internal static Exception ByDesignWithMessage(String message) { return new NotImplementedException(message); } } }
Java
UTF-8
3,691
3.90625
4
[]
no_license
package com.algorithm.all; import org.junit.Test; public class Sum { /** * 给定两个数n,m,从1,2,3..,n中找出所有值等于m的数(所有个数) * @param n * @param m */ public void printAllSum(int n, int m) { } @Test public void testJump1() { System.out.println(jump1(1)); System.out.println(jump1(2)); System.out.println(jump1(3)); System.out.println(jump1(4)); System.out.println(jump1(5)); } /** * 跳台阶问题,每次只能跳1,2 * f(n),当1时,剩下的f(n-1)种,当2时,剩下的(n-2)种,一共f(n)=f(n-1) + f(n-2) * @param n * @return */ public int jump1(int n) { if (n == 0) { return 1; } if (n == 1) { return 1; } return jump1(n-1) + jump1(n-2); } @Test public void testJump() { System.out.println(Jump(2)); System.out.println(Jump(3)); System.out.println(Jump(4)); System.out.println(Jump(5)); } /** * 跳台阶问题 * 当n = 1 时, 只有一种跳法,即1阶跳:Fib(1) = 1; 当n = 2 时, 有两种跳的方式,一阶跳和二阶跳:Fib(2) = Fib(1) + Fib(0) = 2; 当n = 3 时,有三种跳的方式,第一次跳出一阶后,后面还有Fib(3-1)中跳法; 第一次跳出二阶后,后面还有Fib(3-2)中跳法;第一次跳出三阶后,后面还有Fib(3-3)中跳法 Fib(3) = Fib(2) + Fib(1)+Fib(0)=4; * @param n * @return */ public int Jump(int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } return Jump(n-1) + Jump(n-1); } @Test public void testBinarySum() { System.out.println(Integer.toBinaryString(1)); System.out.println(binarySum(1)); System.out.println(Integer.toBinaryString(2)); System.out.println(binarySum(2)); System.out.println(Integer.toBinaryString(3)); System.out.println(binarySum(3)); System.out.println(Integer.toBinaryString(33)); System.out.println(binarySum(33)); System.out.println(Integer.toBinaryString(333)); System.out.println(binarySum(333)); } /*int 数种binary字符1的个数 * */ public int binarySum(int n) { int sum = 0; while(n>0) { if ((n & 1) == 1) { sum = sum +1; } n = n >>1; } return sum; } @Test public void testDecimalSum() { System.out.println(decimalSum(1)); System.out.println(decimalSum(5)); System.out.println(decimalSum(12)); } /** * :输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。 例如输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。 * @param n * @return */ public int decimalSum(int n) { StringBuilder s = new StringBuilder(); for (int i = 1; i <=n; i++) { s.append(i); } String ss = s.toString(); System.out.println(ss); int sum = 0; for (int i = 0; i < ss.length(); i++) { int ii= Integer.valueOf(ss.charAt(i) - 48); if ( ii== 1) { sum = sum +1; } } return sum; } @Test public void testContinueSum() { continueSum(15); } /** * 输入一个正数n,输出所有和为n连续正数序列。 例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。 设起始数为x,共i个数相加,序列x + (x+1) + (x+2) + ...+ (x + i -1) = N 解为:x*i = N - ((i*(i-1))/2; * @param n * @return */ public void continueSum(int n) { for (int i = 2; i < n; i++) { int x = (2*n - i*i +i)/(2*i); int x2 = (2*n - i*i +i)%(2*i); if (x >0 && x2 ==0) { for (int j = 0; j < i; j++) { System.out.print(x+j + " "); } System.out.println(""); } } } }
JavaScript
UTF-8
4,893
2.609375
3
[]
no_license
import TiledInterpreter from './TiledInterpreter'; import { collect, consume, knockDoor, knockGate } from './interactions'; /** * Extend this instead of Phaser.State to handle a Tiled level * @type {Object} */ class TiledLevelState extends Phaser.State { init({ mapPath }) { this.tiledLevel = { mapPath, mapName: mapPath }; Phaser.Canvas.setImageRenderingCrisp(this.game.canvas); } preload() { const { mapName, mapPath } = this.tiledLevel; this.preloadTilemap(mapName, mapPath, null, Phaser.Tilemap.TILED_JSON); this.load.spritesheet('player', '/assets/sprites/dog.gif', 24, 16); } create() { const { mapName } = this.tiledLevel; this.game.stage.backgroundColor = '#000'; this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; // have the game centered on screen this.scale.pageAlignHorizontally = true; this.scale.pageAlignVertically = true; this.map = this.createTilemap(mapName); this.tiledLevel.mapLayers = []; this.tiledLevel.collideLayers = []; this.map.layers.forEach(layer => { const createdLayer = this.map.createLayer(layer.name); createdLayer.resizeWorld(); this.tiledLevel.mapLayers.push(createdLayer); if (layer.properties.impassable) { this.tiledLevel.collideLayers.push(createdLayer); this.map.setCollisionByExclusion([], true, createdLayer); } }); const objectsByType = this.getTilemapObjectsByType(this.tilemap); if (objectsByType.Consumable) { this.tiledLevel.consumables = this.game.add.group(); this.tiledLevel.consumables.enableBody = true; const consumables = objectsByType.Consumable; consumables.forEach(item => this.createSpriteFromTiledObject(item, this.tiledLevel.consumables) ); } if (objectsByType.Key) { this.tiledLevel.keys = this.game.add.group(); this.tiledLevel.keys.enableBody = true; const keys = objectsByType.Key; keys.forEach(item => this.createSpriteFromTiledObject(item, this.tiledLevel.keys) ); } if (objectsByType.Door) { this.tiledLevel.doors = this.game.add.group(); this.tiledLevel.doors.enableBody = true; const doors = objectsByType.Door; doors.forEach(item => { const sprite = this.createSpriteFromTiledObject(item, this.tiledLevel.doors); sprite.body.moves = false; }); } if (objectsByType.Gate) { this.tiledLevel.gates = this.game.add.group(); this.tiledLevel.gates.enableBody = true; const gates = objectsByType.Gate; gates.forEach(item => { const sprite = this.createSpriteFromTiledObject(item, this.tiledLevel.gates); sprite.body.moves = false; }); } this.physics.startSystem(Phaser.Physics.ARCADE); // add player const playerStart = objectsByType.PlayerStart[0]; this.player = this.add.sprite(playerStart.x, playerStart.y - playerStart.height, 'player'); this.physics.arcade.enable(this.player); this.player.animations.add('walk', [ 0, 2 ], 8, true); this.player.animations.add('sit', [ 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6 ], 8, true); this.player.scale.x = -1; this.player.anchor.setTo(0.5, 1); this.player.body.setSize(10, 8, 3, 8); this.game.camera.follow(this.player); this.cursors = this.game.input.keyboard.createCursorKeys(); } update() { this.tiledLevel.collideLayers.forEach(layer => { this.game.physics.arcade.collide(this.player, layer); }); this.game.physics.arcade.overlap(this.player, this.tiledLevel.consumables, consume, null, this); this.game.physics.arcade.overlap(this.player, this.tiledLevel.keys, collect, null, this); this.game.physics.arcade.collide(this.player, this.tiledLevel.doors, knockDoor, null, this); this.game.physics.arcade.collide(this.player, this.tiledLevel.gates, knockGate, null, this); // Reset the this.players velocity (movement) this.player.body.velocity.x = 0; this.player.body.velocity.y = 0; let direction = ''; switch (true) { case this.cursors.left.isDown: direction += 'left'; this.player.body.velocity.x = -50; this.player.scale.x = 1; break; case this.cursors.right.isDown: direction += 'right'; this.player.body.velocity.x = 50; this.player.scale.x = -1; break; } switch (true) { case this.cursors.up.isDown: direction += 'up'; this.player.body.velocity.y = -50; break; case this.cursors.down.isDown: direction += 'down'; this.player.body.velocity.y = 50; break; } if (direction) { this.player.animations.play('walk'); } else { this.player.animations.play('sit'); } } } Object.assign(TiledLevelState.prototype, TiledInterpreter); export default TiledLevelState;
Java
UTF-8
1,108
2.5
2
[ "Apache-2.0" ]
permissive
package code.landgrey.copagent.utils; import java.io.File; import java.sql.Timestamp; import java.text.SimpleDateFormat; public class LogUtils { public static File log_file = null; public static File result_file = null; public static File getLogFile() { File log_directory = new File(PathUtils.getCurrentDirectory(), "logs"); if(!log_directory.exists()){ log_directory.mkdirs(); } return new File(log_directory, "copagent.log"); } public static void logit(String content){ if(log_file == null){ log_file = getLogFile(); } Timestamp createTime = new Timestamp(System.currentTimeMillis()); String eventTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(createTime); PathUtils.appendTextToFile(log_file, eventTime + " "+ content); } public static void result(String content){ if(result_file == null){ result_file = new File(PathUtils.getCurrentDirectory(), "result.txt"); } PathUtils.writeTextToFile(result_file, content); } }
Java
UTF-8
222
1.546875
2
[]
no_license
package ixcode.platform.http.server.resource; import ixcode.platform.http.protocol.request.Request; public interface DataConsumer { void consumeRequest(Request request, RedirectionParameters redirectionParameters); }
TypeScript
UTF-8
7,470
2.96875
3
[ "MIT" ]
permissive
/** * Abstract robot capability. */ /* * AetheBot - A Discord Chatbot * * Created by Tyrone Trevorrow on 03/02/17. * Copyright (c) 2017 Tyrone Trevorrow. All rights reserved. * * This source code is licensed under the permissive MIT license. */ import { Stream } from "stream" import assert from "assert" import * as Discord from "discord.js" import randomNumber from "random-number-csprng" import { Bot } from "../bot" const NEGATIVES = [ "yeah, nah", "no", "nah that's fucked as", "can't do it mate", "nope, ya fucked it", "what even is that m8", "do it properly cunt", "nah fuck ya", ] interface FileAttachment { data: Buffer | Stream | string name?: string } export class MessageContext<F extends FeatureBase> { private myMessage: Discord.Message private myFeature: F private myIsDM = false public constructor(message: Discord.Message, feature: F) { this.myFeature = feature this.myMessage = message this.myIsDM = message.channel.type === Discord.ChannelType.DM } public get message(): Discord.Message { return this.myMessage } public get feature(): F { return this.myFeature } public get isDM(): boolean { return this.myIsDM } /** * Sends a message to the channel without any reply or mention. * @param str message to send * @returns The `Discord.Message` that was sent */ public async sendPlain(str: string, embeds?: Discord.JSONEncodable<Discord.APIEmbed>[]): Promise<Discord.Message> { const channel = this.myMessage.channel // Shouldn't be possible assert(channel.type !== Discord.ChannelType.GuildStageVoice) return channel.send({content: str, embeds}) } /** * Replies to the message using Discord's reply system if not in a DM. * @param str message to send * @param embeds Discord embed objects * @returns The `Discord.Message` that was sent */ public async sendReply(str: string, embeds?: Discord.JSONEncodable<Discord.APIEmbed>[]): Promise<Discord.Message> { const channel = this.myMessage.channel if (channel.type === Discord.ChannelType.DM) { if (embeds && embeds.length > 0) { return channel.send({content: str, embeds}) } else { return channel.send(str) } } else { if (embeds && embeds.length > 0) { return this.myMessage.reply({content: str, embeds}) } else { return this.myMessage.reply(str) } } } /** * Sends a reply like `sendReply` but with file attachments. * @param content message to send * @param filesData Files to send * @returns The `Discord.Message` that was sent */ public async sendReplyFiles(content: string | undefined, filesData: FileAttachment[]): Promise<Discord.Message> { const channel = this.myMessage.channel const files = filesData.map(data => new Discord.AttachmentBuilder(data.data, {name: data.name})) if (channel.type === Discord.ChannelType.DM) { return channel.send({content, files}) } else { return this.myMessage.reply({content, files}) } } /** * Send a random rejection message, intended as a result of a (usually) intentional misuse or bad parameter, * like sending a large or negative number. */ public async sendNegativeReply(hint?: string): Promise<Discord.Message | Discord.Message[]> { const idx = await randomNumber(0, NEGATIVES.length - 1) const msg = NEGATIVES[idx] if (hint) { return this.sendReply(`${msg} (${hint})`) } else { return this.sendReply(msg) } } } export type DiscordReaction = Discord.MessageReaction | Discord.PartialMessageReaction export type DiscordUser = Discord.User | Discord.PartialUser export interface FeatureBase { onMessageReactionAdd?(reaction: DiscordReaction, user: DiscordUser): boolean onMessageReactionRemove?(reaction: DiscordReaction, user: DiscordUser): boolean } export interface SlashCommand { name: string toJSON(): Discord.RESTPostAPIChatInputApplicationCommandsJSONBody } export abstract class FeatureBase { public get bot(): Bot { return this.internalBot } public static slashCommands?: SlashCommand[] public name: string private internalBot: Bot public constructor(bot: Bot, name: string) { this.internalBot = bot this.name = name } public voiceChannelStateChanged?(channel: Discord.VoiceBasedChannel): void public handlesMessage(context: MessageContext<this>): boolean { const message = context.message if (!this.bot.user) { return false } // Ignore messages sent by the bot itself if (message.author.equals(this.bot.user)) { return false } // Handle all DMs by default if (message.channel.type === Discord.ChannelType.DM) { return true } // Handle messages where the bot is specifically mentioned if (message.mentions.has(this.bot.user, { ignoreEveryone: true, ignoreRoles: true, })) { return true } return false } public commandTokens(context: MessageContext<this>): string[] { const message = context.message const matches = message.content.trim().match(/\\?.|\n|^$/g) if (!matches) { return [] } const tokens = matches.reduce((state, c) => { if (c === '"') { state.quote = !state.quote } else if (!state.quote && c === " ") { state.a.push("") } else if (!state.quote && c === "\n") { state.a.push(c) state.a.push("") } else { state.a[state.a.length-1] += c.replace(/\\(.)/,"$1") } return state }, { a: [""], quote: false, }) .a .filter(token => token !== "") const user = this.bot.user // Remove the mention if (user && message.mentions.has(user)) { tokens.splice(tokens.findIndex(s => { if (s === `<@${user.id}>`) { return true } if (s === `<@!${user.id}>`) { return true } return false }), 1) } return tokens } public async handleInteraction?(interaction: Discord.Interaction<Discord.CacheType>): Promise<void> public abstract handleMessage(context: MessageContext<this>): boolean } /** * GlobalFeature is a feature which is intantiated once per-bot, and will be * present in every server the bot is joined to. */ export abstract class GlobalFeature extends FeatureBase { } /** * ServerFeature is a feature which is instantiated per-server, and must be * added to a server to work. */ export abstract class ServerFeature extends FeatureBase { private internalServer: Discord.Guild public constructor(bot: Bot, name: string, server: Discord.Guild) { super(bot, name) this.internalServer = server } public get server(): Discord.Guild { return this.internalServer } }
C++
WINDOWS-1250
884
3.140625
3
[]
no_license
/********************************************************************************************************************************************* Print_Numbers_without_semicolon.cpp Created on: 03-Mar-2021 Author: Malkeet Mehra How to print numbers from 1 to N without using any semicolon in C. #include<stdio.h> #define N 100 // Add your code here to print numbers from 1 // to N without using any semicolon What code to add in above snippet such that it doesnt contain semicolon and prints numbers from 1 to N? **********************************************************************************************************************************************/ #include<bits/stdc++.h> using namespace std; #define n 10 /* void print(int n) { int i = 1; while(printf("%d",i) && (++i) <= n) { } }*/ int main(int i) { while(printf("%d", i) && (++i <= n)) { } }
Swift
UTF-8
1,530
2.6875
3
[]
no_license
// // GXFavouritesRepository.swift // GX-App // // Created by M. Barış ÇİÇEK on 19.03.2020. // Copyright © 2020 M. Barış ÇİÇEK. All rights reserved. // import Foundation protocol GXFavouritesRepositoryType { func checkIsFavourited(id: Int, completion: @escaping (Bool) -> Void) func fetchFavouriteList(completion: @escaping (Result<GXGameListEntity?, Error>) -> Void) func addFavourite(game: GXGameEntity, completion: @escaping () -> Void) func removeFavourite(game: GXGameEntity, completion: @escaping () -> Void) } final class GXFavouritesRepository: GXFavouritesRepositoryType { // MARK: INITIALIZERS private let localRepository: GXFavouritesLocalRepository init(storageContext: GXStorageContext) { localRepository = GXFavouritesLocalRepository(storageContext: storageContext) } // MARK: REPOSITORY func checkIsFavourited(id: Int, completion: @escaping (Bool) -> Void) { localRepository.checkIsFavourited(id: id, completion: completion) } func fetchFavouriteList(completion: @escaping (Result<GXGameListEntity?, Error>) -> Void) { localRepository.fetchFavouriteList(completion: completion) } func addFavourite(game: GXGameEntity, completion: @escaping () -> Void) { localRepository.addFavourite(game: game, completion: completion) } func removeFavourite(game: GXGameEntity, completion: @escaping () -> Void) { localRepository.removeFavourite(game: game, completion: completion) } }
Java
UTF-8
762
2.5
2
[ "MIT" ]
permissive
package no.nav.fo.veilarbregistrering.bruker; public class Ident { private String ident; private boolean historisk; private Gruppe gruppe; public Ident(String ident, boolean historisk, Gruppe gruppe) { this.ident = ident; this.historisk = historisk; this.gruppe = gruppe; } public String getIdent() { return ident; } public void setIdent(String ident) { this.ident = ident; } public boolean isHistorisk() { return historisk; } public void setHistorisk(boolean historisk) { this.historisk = historisk; } public Gruppe getGruppe() { return gruppe; } public void setGruppe(Gruppe gruppe) { this.gruppe = gruppe; } }
Java
UTF-8
566
2.53125
3
[ "Apache-2.0" ]
permissive
package com.iobeam.api.resource; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * A base type for collections of resource objects. */ public abstract class ResourceList<T> implements Serializable { private final ArrayList<T> list = new ArrayList<T>(); public void add(final T r) { list.add(r); } protected List<T> getList() { return list; } public int size() { return list.size(); } @Override public String toString() { return list.toString(); } }
Java
UTF-8
15,462
2.46875
2
[]
no_license
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import edu.tsinghua.lumaqq.models.Group; import edu.tsinghua.lumaqq.models.ModelRegistry; import edu.tsinghua.lumaqq.qq.QQ; import edu.tsinghua.lumaqq.qq.packets.BasicInPacket; import edu.tsinghua.lumaqq.qq.packets.InPacket; import edu.tsinghua.lumaqq.qq.packets.in.ReceiveIMPacket; /** * 消息队列实现类 * * * @author luma */ public class MessageQueue { // 总队列 private Queue<InPacket> queue; // 系统消息队列 private Queue<InPacket> sysQueue; // 延迟处理队列 private Queue<InPacket> postponeQueue; // 用户消息队列映射哈希表 private Map<Integer, Queue<InPacket>> userQueueMap; // 用户临时会话消息映射哈希表 private Map<Integer, Queue<InPacket>> tempSessionQueueMap; // 短消息队列 private Queue<InPacket> smsQueue; // true表示收到的消息应该延迟处理 private boolean postpone; /** * 私有构造函数,singleton模式 */ public MessageQueue() { queue = new LinkedList<InPacket>(); sysQueue = new LinkedList<InPacket>(); postponeQueue = new LinkedList<InPacket>(); userQueueMap = new HashMap<Integer, Queue<InPacket>>(); tempSessionQueueMap = new HashMap<Integer, Queue<InPacket>>(); smsQueue = new LinkedList<InPacket>(); postpone = false; } /** * 情况所有数据 */ public void clear() { queue.clear(); sysQueue.clear(); postponeQueue.clear(); userQueueMap.clear(); } /** * 添加一个短消息到队列末尾 * * @param in * 要添加的消息包对象 */ public void putSMS(InPacket in) { if(in != null) { smsQueue.offer(in); queue.offer(in); } } /** * 得到队列中第一条短消息,并且把它从队列中删除 * * @return * InPacket,如果队列为空,返回null */ public InPacket getSMS() { InPacket ret = smsQueue.poll(); queue.remove(ret); return ret; } /** * 得到下一条手机短信 * * @param qq * @return */ public InPacket getSMS(int qq) { int size = smsQueue.size(); while(size-- > 0) { ReceiveIMPacket packet = (ReceiveIMPacket)smsQueue.poll(); if(packet.sms.sender == qq) { queue.remove(packet); return packet; } else smsQueue.offer(packet); } return null; } /** * 得到下一条手机短信 * * @param mobile * @return */ public InPacket getSMS(String mobile) { int size = smsQueue.size(); while(size-- > 0) { ReceiveIMPacket packet = (ReceiveIMPacket)smsQueue.poll(); if(packet.sms.sender == 0 && packet.sms.senderName.equals(mobile)) { queue.remove(packet); return packet; } else smsQueue.offer(packet); } return null; } /** * 把一个普通消息包推入消息队列 * @param packet * 消息包对象 */ public void putMessage(BasicInPacket packet) { putMessage(packet, true); } /** * @param packet * 消息包对象 * @param global * true表示添加这个消息到总队列中。推到总队列中的效果是这条消息会在tray中 * 闪烁。有时候消息是不需要在tray中闪烁的,比如把群消息设为只显示计数,不显示 * 提示时。 */ public void putMessage(InPacket packet, boolean global) { ReceiveIMPacket im = (ReceiveIMPacket)packet; if(im.header.type == QQ.QQ_RECV_IM_TEMP_SESSION) { putTempSessionMessage(im); return; } // 得到QQ号,判断是否已经存在该用户的消息队列,如果这个是群消息,这个其实就是群的内部ID int qq; if(im.header.type == QQ.QQ_RECV_IM_TEMP_CLUSTER) qq = im.clusterIM.clusterId; else qq = im.header.sender; Queue<InPacket> userQueue = null; if(!userQueueMap.containsKey(qq)) { userQueue = new LinkedList<InPacket>(); userQueueMap.put(qq, userQueue); } else { userQueue = userQueueMap.get(qq); } // 消息推入用户队列组队列和总队列 userQueue.offer(packet); if(global) queue.offer(packet); } /** * 把临时会话消息推入队列 * * @param packet */ protected void putTempSessionMessage(ReceiveIMPacket packet) { int qq = packet.tempSessionIM.sender; Queue<InPacket> tempQueue = null; if(tempSessionQueueMap.containsKey(qq)) tempQueue = tempSessionQueueMap.get(qq); else { tempQueue = new LinkedList<InPacket>(); tempSessionQueueMap.put(qq, tempQueue); } tempQueue.offer(packet); queue.offer(packet); } /** * 把一个系统消息推入队列 * @param packet */ public void putSystemMessage(BasicInPacket packet) { sysQueue.offer(packet); queue.offer(packet); } /** * 得到一条普通消息,并把他从队列中删除 * * @param qq * 发送消息的好友QQ号 * @return * 如果有消息在返回消息,否则返回null */ public InPacket getMessage(int qq) { // 检查是否有这个队列,有则取第一个消息,如果取后队列为空,删除这个队列 if(userQueueMap.containsKey(qq)) { Queue<InPacket> userQueue = userQueueMap.get(qq); InPacket p = userQueue.poll(); if(p == null) return null; // 从总队列中删除 queue.remove(p); // 如果用户消息队列为空,删除这个队列 if(userQueue.isEmpty()) userQueueMap.remove(qq); return p; } else return null; } /** * 得到一条普通消息,不把他从队列中删除 * * @param qq * 发送消息的好友QQ号 * @return * 如果有消息在返回消息,否则返回null */ public InPacket peekMessage(int qq) { // 检查是否有这个队列,有则取第一个消息,如果取后队列为空,删除这个队列 if(userQueueMap.containsKey(qq)) { Queue<InPacket> userQueue = userQueueMap.get(qq); return userQueue.peek(); } else return null; } /** * 把qq号指定的好友或者群的所有消息删除 * * @param qq * 可能是好友的QQ号,也可能是群的内部ID */ public void removeMessage(int qq) { // 检查是否有这个队列 if(userQueueMap.containsKey(qq)) { Queue<InPacket> userQueue = userQueueMap.remove(qq); for(InPacket p : userQueue) queue.remove(p); } } /** * 得到一条普通消息,这条消息是该组内队列的第一条 * * @param g * Group * @return * 如果有则返回消息,否则返回null */ public InPacket getGroupMessage(Group g) { int nextSender = nextGroupSender(g); if(nextSender == -1) return null; else { Queue<InPacket> userQueue = userQueueMap.get(nextSender); InPacket ret = userQueue.poll(); queue.remove(ret); return ret; } } /** * 得到系统消息队列的第一个包,但是不删除它 * * @return * 系统消息包对象 */ public InPacket peekSystemMessage() { InPacket ret = sysQueue.peek(); return ret; } /** * 得到一条系统消息,并把他从队列删除 * * @return * 如果有消息,返回消息,否则返回null */ public InPacket getSystemMessage() { InPacket ret = sysQueue.poll(); queue.remove(ret); return ret; } /** * 检查是否某个好友还有消息未读 * * @param qqNum * 好友QQ号 * @return * true如果有消息未读 */ public boolean hasMessage(int qqNum) { return userQueueMap.containsKey(qqNum); } /** * 检查是否有某个用户的临时会话消息 * * @param qqNum * QQ号 * @return * true表示有临时会话消息未读 */ public boolean hasTempSessionMessage(int qqNum) { return tempSessionQueueMap.containsKey(qqNum); } /** * 得到下一条临时会话消息 * * @param qqNum * @return */ public InPacket getTempSessionMessage(int qqNum) { if(hasTempSessionMessage(qqNum)) { Queue<InPacket> tempQueue = tempSessionQueueMap.get(qqNum); InPacket p = tempQueue.poll(); if(p == null) return null; // 从总队列中删除 queue.remove(p); // 如果用户消息队列为空,删除这个队列 if(tempQueue.isEmpty()) tempSessionQueueMap.remove(qqNum); return p; } else return null; } /** * 得到下一条临时会话消息,不从队列中删除 * * @param qqNum * @return */ public InPacket peekTempSessionMessage(int qqNum) { if(hasTempSessionMessage(qqNum)) { Queue<InPacket> tempQueue = tempSessionQueueMap.get(qqNum); return tempQueue.peek(); } else return null; } /** * 检查是否某个群下面有讨论组的消息,如果父群id是0,则检查 * 是否有多人对话消息 * * @param parentClusterId * 父群id,0表示多人对话容器 * @return * 子群id,如果为-1表示没有子群有消息 */ public int hasSubClusterIM(int parentClusterId) { for(InPacket p : queue) { if(p instanceof ReceiveIMPacket) { ReceiveIMPacket packet = (ReceiveIMPacket)p; switch(packet.header.type) { case QQ.QQ_RECV_IM_TEMP_CLUSTER: if(packet.clusterIM.externalId == parentClusterId) return packet.clusterIM.clusterId; default: break; } } } return -1; } /** * 检查某个组是否有消息未读 * * @param g * Group * @return * true如果有消息未读 */ public boolean hasGroupMessage(Group g) { return nextGroupSender(g) != -1; } /** * @return * true如果还有任何消息未读 */ public boolean hasNext() { return !queue.isEmpty(); } /** * @return * true如果还有系统消息未读 */ public boolean hasSystemMessage() { return !sysQueue.isEmpty(); } /** * @return * true如果还有短消息 */ public boolean hasSMS() { return !smsQueue.isEmpty(); } /** * 好友的下一条消息是不是临时会话消息 * * @param qq * @return */ public boolean isNextTempSessionMessage(int qq) { InPacket normal = peekMessage(qq); InPacket temp = peekTempSessionMessage(qq); if(temp == null && normal == null) return false; if(temp == null) return false; for(InPacket in : queue) { if(in == normal) return false; if(temp == in) return true; } return false; } /** * @return * 下一条消息的发送者的QQ号,如果是0,表示是系统消息,-1表示 * 无消息如果是群消息,返回的将是群的内部ID */ public int nextSender() { InPacket packet = queue.peek(); if(packet == null) return -1; if(packet instanceof ReceiveIMPacket) { ReceiveIMPacket im = (ReceiveIMPacket)packet; if(im.header.type == QQ.QQ_RECV_IM_SYS_MESSAGE) return 0; else if(im.header.type == QQ.QQ_RECV_IM_TEMP_CLUSTER) return im.clusterIM.clusterId; else return im.header.sender; } else return 0; } /** * 返回下一个消息的来源,对于普通消息,返回QQ_IM_FROM_FRIEND,对于 * 系统消息,返回QQ_IM_FROM_SYS,对于群消息,有两种情况,因为群消息 * 包含了普通消息和通知消息,对于普通消息,我们返回QQ_IM_FROM_CLUSTER, * 对于通知消息,我们返回QQ_IM_FROM_SYS * * @return * 消息来源标识常量 */ public int nextMessageSource() { InPacket packet = queue.peek(); if(packet == null) return -1; if(packet instanceof ReceiveIMPacket) { ReceiveIMPacket im = (ReceiveIMPacket)packet; return im.getMessageCategory(); } else return QQ.QQ_IM_FROM_SYS; } /** * 返回该组内下一条消息发送者的QQ号 * * @param g * Group * @return * QQ号,如果没有消息,返回-1 */ public int nextGroupSender(Group g) { for(InPacket p : queue) { if(p instanceof ReceiveIMPacket) { ReceiveIMPacket packet = (ReceiveIMPacket)p; if(packet.header.type == QQ.QQ_RECV_IM_BIND_USER || packet.header.type == QQ.QQ_RECV_IM_MOBILE_QQ) continue; // 得到下一个包的发送者QQ号 int sender = packet.header.sender; if(packet.header.type == QQ.QQ_RECV_IM_TEMP_CLUSTER) sender = packet.clusterIM.clusterId; // 在g指定的组中查找是否有这个好友 if(ModelRegistry.hasUser(sender)) { if(ModelRegistry.getUser(sender).group == g) return sender; } else if(ModelRegistry.hasCluster(sender)) { if(ModelRegistry.getCluster(sender).group == g) return sender; } } } return -1; } /** * @return * 下一个应该闪烁的消息的发送者 */ public int nextBlinkableIMSender() { for(InPacket p : queue) { if(p instanceof ReceiveIMPacket) { ReceiveIMPacket packet = (ReceiveIMPacket)p; switch(packet.header.type) { case QQ.QQ_RECV_IM_FRIEND: case QQ.QQ_RECV_IM_STRANGER: case QQ.QQ_RECV_IM_TEMP_SESSION: return packet.header.sender; default: break; } } } return -1; } /** * @return * 下一条群消息的群号,-1表示没有 */ public int nextClusterIMSender() { for(InPacket p : queue) { if(p instanceof ReceiveIMPacket) { ReceiveIMPacket packet = (ReceiveIMPacket)p; switch(packet.header.type) { case QQ.QQ_RECV_IM_CLUSTER: return packet.header.sender; case QQ.QQ_RECV_IM_TEMP_CLUSTER: return packet.clusterIM.clusterId; default: break; } } } return -1; } /** * 一个消息在好友列表还没得到之前到达了,延迟处理这个消息 * * @param packet * 消息包 */ public void postponeMessage(InPacket packet) { postponeQueue.offer(packet); } /** * 返回下一个延迟处理的消息 * * @return * 如果有则返回消息,没有返回null */ public InPacket getPostponedMessage() { return postponeQueue.poll(); } /** * @return Returns the postpone. */ public synchronized boolean isPostpone() { return postpone; } /** * @param postpone The postpone to set. */ public synchronized void setPostpone(boolean postpone) { this.postpone = postpone; } }
C#
UTF-8
2,195
2.578125
3
[ "MIT" ]
permissive
using NUnit.Framework; using Rebilly.Core; using Rebilly.Entities; namespace Tests.Unit.Entities { [TestFixture] public class NoteUnitTests { [Test] public void TestConstructIsInstanceOfEntity() { var Note = new Note(); Assert.IsInstanceOf<Entity>(Note); } [Test] public void TestIdDefaultIsEqualTo() { var Note = new Note(); Assert.IsNull(Note.Id); } [Test] public void TestIdIsEqualTo() { var Note = new Note(); Note.Id = "test1"; Assert.AreEqual("test1", Note.Id); } [Test] public void TestContentDefaultIsEqualTo() { var Note = new Note(); Assert.IsNull(Note.Content); } [Test] public void TestContentIsEqualTo() { var Note = new Note(); Note.Content = "Content1"; Assert.AreEqual("Content1", Note.Content); } [Test] public void TestRelatedTypeDefaultIsEqualTo() { var Note = new Note(); Assert.IsNull(Note.RelatedType); } [Test] public void TestRelatedTypeIsEqualTo() { var Note = new Note(); Note.RelatedType = "RelatedType1"; Assert.AreEqual("RelatedType1", Note.RelatedType); } [Test] public void TestRelatedIdDefaultIsEqualTo() { var Note = new Note(); Assert.IsNull(Note.RelatedId); } [Test] public void TestRelatedIdIsEqualTo() { var Note = new Note(); Note.RelatedId = "RelatedId1"; Assert.AreEqual("RelatedId1", Note.RelatedId); } [Test] public void TestArchivedDefaultIsEqualTo() { var Note = new Note(); Assert.IsFalse(Note.Archived); } [Test] public void TestArchivedIsEqualTo() { var Note = new Note(); Note.Archived = true; Assert.IsTrue(Note.Archived); } } }
Java
UTF-8
317
1.976563
2
[]
no_license
package com.app.service; import java.util.List; import com.app.model.Vendor; public interface IVendorService { public Integer saveVendors(Vendor v); public void updateVendors(Vendor v); public void deleteVendors(Integer id); public Vendor getOneVendorById(Integer id); public List<Vendor> getAllVendors(); }
Java
UTF-8
2,818
3.125
3
[]
no_license
import java.awt.Color; import java.util.Set; public class Bullet implements Viewable { private Vector r; // Position of bullet private double velocity = 2e4; // constant velocity of bullet private Vector vel; // velocity of player private double radius = 0.02e10; // Constant radius of bullet private Color color; // Color of bullet private double distance; // Distance from player Bullet(Vector r, Vector v, Color c) { // Asign values for new bullet this.r = r; this.color = c; this.vel = v; } void updatePosition() { // Move bullet r = r.plus(vel.times(StellarCrush.GAME_DELAY_TIME)); } public Vector getBulletPos() { return this.r; } public double getD() { // Returns distance from player return this.distance; } // Sets distance between bullet and player public void setD(double d) { this.distance = d; } public Vector getR() { return this.r; } public double getRadius() { return this.radius; } // Check if bullet hit objects @SuppressWarnings( "deprecation" ) public int objectHit(Set<GameObject> set, Set<Bullet> bSet, Set<Bullet> temp, int score) { for (GameObject o : set) { //bullet hits if ((this.radius + o.getRadius()) > this.r.minus(o.getR()).magnitude()) { // hits player if (o instanceof PlayerObject) { score -= 1; // Minus 1 from player score StdDraw.filledSquare(0, 0, 5e10); // Flash red square StdDraw.show(5); /* Acquired from Youtube video: Link: https://www.youtube.com/watch?v=eYWmrObq6HU&t=61s Used Audacity to manipulate and cut file to get sound effect */ StdAudio.play("Sounds/hit1.wav"); } temp.add(this); // Add bullets to set to be removed } } return score; } // When bullet is not in scale anymore public void outOfSpace(Set<Bullet> bSet, Set<Bullet> temp) { if (this.r.cartesian(0) > StellarCrush.scale || this.r.cartesian(0) < -StellarCrush.scale || this.r.cartesian(1) > StellarCrush.scale || this.r.cartesian(1) < -StellarCrush.scale) { temp.add(this); } } // Check if bullet hits enemy public void enemyHit(Set<Enemy> set, Set<Bullet> bSet, Set<Enemy> temp) { for (Enemy e : set) { // Player bullet hits enemy if ((this.radius + e.getRadius() > this.r.minus(e.getR()).magnitude()) && this.color == StdDraw.GREEN) { temp.add(e); } } } // Draw bullet on canvas void bulletDraw() { StdDraw.setPenColor(this.color); StdDraw.filledCircle(r.cartesian(0), r.cartesian(1), radius); } }
PHP
UTF-8
5,720
2.8125
3
[]
no_license
<?php namespace Sengin\Extractor; use Sengin\Extractor; use Sengin\DataSource; use Sengin\Extraction\Result; use Sengin\Extraction\SearchResult; use Sengin\Extraction\SuggestedKeyword; class GoogleSearch implements Extractor { /** * @var \DOMDocument */ protected $_document; /** * @var \Sengin\DataSource */ protected $_dataSource; /** * Disable libxml errors and allow user to fetch error information as needed * @var bool */ protected $_disableLibXmlErrors = true; public function __construct(DataSource $dataSource) { $this->_dataSource = $dataSource; } /** * @return \DOMDocument */ public function getDocument() { if (null === $this->_document) { $this->_document = new \DOMDocument; } return $this->_document; } /** * @param boolean $disableLibXmlErrors */ public function setDisableLibXmlErrors($disableLibXmlErrors) { $this->_disableLibXmlErrors = (bool) $disableLibXmlErrors; } /** * @return boolean */ public function getDisableLibXmlErrors() { return $this->_disableLibXmlErrors; } /** * @return \Sengin\Extraction\Result * @throws Exception\Exception */ public function extract() { $data = $this->_dataSource->getData(); $document = $this->getDocument(); /* * If disable libxml errors is set to true then we see no more errors like that: * Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity */ $previos = libxml_use_internal_errors($this->getDisableLibXmlErrors()); $isLoaded = $document->loadHTML($data); libxml_use_internal_errors($previos); if (!$isLoaded) { $message = "Can't load html data from given source"; throw new Exception\Exception($message); } $result = new Result(); $this->extractSearchResults($result); $this->extractSponsoredResults($result); $this->extractSuggstions($result); return $result; } protected function extractSearchResults(\Sengin\Extraction $extraction) { $document = $this->getDocument(); $xpath = new \DOMXPath($document); $elements = $xpath->query( "//li[contains(normalize-space(@class), 'g')]". "//h3[contains(normalize-space(@class), 'r')]". "//a[starts-with(normalize-space(@href), '/url?q=')]" ); if (!count($elements)) { return false; } $results = new \ArrayObject(); $position = 0; foreach($elements as $key => /* @var $element \DOMElement */ $element) { $url = $element->getAttribute('href'); $query = parse_url($url, PHP_URL_QUERY); parse_str($query, $queryArray); $url = isset($queryArray['q']) ? $queryArray['q'] : $url; $title = $element->textContent; $title = $this->filterWhitespaces($title); $result = new SearchResult(); $result->setUrl($url); $result->setTitle($title); $result->setPosition(++$position); $results->append($result); } $extraction->setSearchResults($results); } protected function extractSponsoredResults(\Sengin\Extraction $extraction) { $document = $this->getDocument(); $xpath = new \DOMXPath($document); $elements = $xpath->query( "//li". "//h3". "//a[starts-with(normalize-space(@href), '/aclk?sa=')]" ); if (!count($elements)) { return false; } $results = new \ArrayObject(); $position = 0; foreach($elements as $key => /* @var $element \DOMElement */ $element) { $url = $element->getAttribute('href'); $query = parse_url($url, PHP_URL_QUERY); parse_str($query, $queryArray); $url = isset($queryArray['c']) ? $queryArray['c'] : $queryArray['adurl']; $title = $element->textContent; $title = $this->filterWhitespaces($title); $result = new SearchResult(); $result->setUrl($url); $result->setTitle($title); $result->setPosition(++$position); $results->append($result); } $extraction->setSponsoredResult($results); } protected function extractSuggstions(\Sengin\Extraction $extraction) { $document = $this->getDocument(); $xpath = new \DOMXPath($document); /** * ct = broad-revision: (? ct = click through) Where was the link? Depending on the search result can “ct = title” or as “ct = Resalte” occur. * http://www.googlesearchblog.com/seo-universal-search.html */ $elements = $xpath->query( "//p//a[contains(normalize-space(@href), 'ct=broad-revision')]" ); if (!count($elements)) { return false; } $results = new \ArrayObject(); foreach($elements as /* @var $element \DOMElement */ $element) { $keyword = $element->textContent; $keyword = $this->filterWhitespaces($keyword); $result = new SuggestedKeyword(); $result->setKeyword($keyword); $results->append($result); } $extraction->setSuggestedKeywords($results); } protected function filterWhitespaces($string) { return implode(' ', array_map('trim', array_filter(explode(' ', $string)))); } }
Markdown
UTF-8
1,207
2.875
3
[]
no_license
# ansible-module-mysql-migration Ansible module for mysql migration, Runs database migration on MySQL server. It reads a mysql SQL scripts from sources (folder) and applies them in correct order to a database. This is preety useful module as we need to use thrid party database migration tools. This module stores data in mysql table itslef to have what migration scripts already runned or on which stage our database migration is, it will then only apply new sql scripts. ## Funtions Supported Before discussing on feature support we can share some terminology of database migration. Lets say we have 5 different script (sql scripts on version) for our complete database. So `up` means we are going forward to database version; `down` means we are moving backward in database version 1. up: number of Version up 2. down: number of Version down 3. goto: Want to goto specific version 4. drop: Drop a database 5. all -> want to go to latest version (means apply all migration version) Detailed information can be found in code docs itself [library/mysql_database_migration.py](./library/mysql_database_migration.py) **Ansible version checked** 1. Ansible 2.7 ## Author Varun Palekar github: varunpalekar
PHP
UTF-8
1,934
2.703125
3
[ "MIT" ]
permissive
<?php class PostController extends \BaseController { /** * Display a listing of the resource. * GET /post * * @return Response */ public function index() { //$posts = Posts::all(); $posts = Posts::with('user')->get(); //$posts = Posts::where('title','like','%post%')->get(); //$posts = Posts::where('title','like','%post%')->take(1)->skip(1)->get(); return View::make('post.list',compact('posts')); } /** * Show the form for creating a new resource. * GET /post/create * * @return Response */ public function create() { // } /** * Store a newly created resource in storage. * POST /post * * @return Response */ public function store() { $post = new Post; //$post->title='test title'; //$post->body='test body'; $data = [ 'title'=>'title', 'body'=>'body', 'user_id'=>1 ];; Posts::create($data); $post->save(); } /** * Display the specified resource. * GET /post/{id} * * @param int $id * @return Response */ public function show($id,$date) { $post = Posts::find($id); //return View::make('post.detail')->with(['id'=>$id,'date'=>$date]); return View::make('post.detail',compact('post')); } /** * Show the form for editing the specified resource. * GET /post/{id}/edit * * @param int $id * @return Response */ public function edit($id) { // } /** * Update the specified resource in storage. * PUT /post/{id} * * @param int $id * @return Response */ public function update($id) { $post = Posts::find($id); $post->user_id = 1; $post->save(); } /** * Remove the specified resource from storage. * DELETE /post/{id} * * @param int $id * @return Response */ public function destroy($id) { Posts::where('id',$id)->delete(); } }
Java
UTF-8
100
1.703125
2
[]
no_license
public interface OptionHandler { public void setOptions( String[] options ) throws Exception; }
TypeScript
UTF-8
746
2.640625
3
[ "Apache-2.0" ]
permissive
import { fromJson } from "./utils"; import {fromArray} from "rxjs/internal/observable/fromArray"; import {toArray} from "rxjs/operators"; describe('Utils test suite', () => { test('fromJson test', async done => { const strings = fromArray(['[1, 2', ', 3]', '{"test1": "val1', '"}{"data":[0,1,2,{"nested', '": true}]}']); const objects = await (strings.pipe(fromJson(), toArray())).toPromise(); expect(objects.length).toEqual(3) expect(objects[0].constructor).toEqual(Array) expect(objects[0].length).toEqual(3) expect(objects[2].data.constructor).toEqual(Array) expect(objects[2].data.length).toEqual(4) expect(objects[2].data[3].nested).toEqual(true) done() }) })
Java
UTF-8
1,762
2.40625
2
[]
no_license
package com.example.cry.user; import lombok.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; public class UserDTO { @Getter @AllArgsConstructor @NoArgsConstructor static public class CreateAdmin { @NotBlank @Size(min = 1, max = 31) private String username; @NotBlank @Size(min = 6, max = 63) @Setter private String password; private UserRoles role = UserRoles.USER; } @Getter @AllArgsConstructor @NoArgsConstructor static public class UpdateAdmin { @Size(min = 1, max = 31) private String username; @Size(min = 6, max = 63) @Setter private String password; private UserRoles role = UserRoles.USER; } @Getter @AllArgsConstructor @NoArgsConstructor static public class UpdateUser { @Size(min = 1, max = 31) private String username; @Size(min = 6, max = 63) @Setter private String password; } @Getter @AllArgsConstructor static public class Signin { @NotBlank @Size(min = 1, max = 31) private String username; @NotBlank @Size(min = 6, max = 63) private String password; } @AllArgsConstructor @NoArgsConstructor @Data static public class SigninReponse { private String jwt; private String id; private String username; private UserRoles role; public SigninReponse(String jwt, UserPrincipal user) { this.jwt = jwt; this.id = user.getId(); this.username = user.getUsername(); this.role = user.getRole(); } } }
JavaScript
UTF-8
237
2.546875
3
[ "BSD-3-Clause" ]
permissive
$(function () { let html = $('#contents').html(); console.log(html); $('#contents').html('<p id="txt">p要素を追加</p>'); let html2 = $('#contents2').html(); console.log(html2); $('#contents2').html('<h2>h2</h2>'); });
C++
UTF-8
1,439
3.03125
3
[ "MIT", "Zlib", "Apache-2.0" ]
permissive
#pragma once #include <string> #include <variant> class ConfigurationManager { public: ConfigurationManager(int argc, char* commandLine[]); enum class Mode { HIDE, EXTRACT, TEST, HELP }; enum class Option { Mode, ImagePath, DataPath, Encryption, Password, DisableCompression }; using variant_value = std::variant<ConfigurationManager::Mode, std::string, bool>; std::variant<ConfigurationManager::Mode, std::string, bool> getOption(ConfigurationManager::Option option) { switch (option) { case ConfigurationManager::Option::Mode: return variant_value(mode); case ConfigurationManager::Option::ImagePath: return variant_value(imagePath); case ConfigurationManager::Option::DataPath: return variant_value(dataPath); case ConfigurationManager::Option::Encryption: return variant_value(encryption); case ConfigurationManager::Option::Password: return variant_value(password); case ConfigurationManager::Option::DisableCompression: return variant_value(disableCompression); default: return -1; } }; private: ConfigurationManager::Mode mode = ConfigurationManager::Mode::HELP; std::string imagePath = ""; std::string dataPath = ""; bool encryption = false; std::string password = ""; bool disableCompression = false; };
C++
UTF-8
5,156
2.625
3
[]
no_license
#pragma once #ifndef nofilter #define nofilter 0 #endif #include <time.h> #include <list> #include "CCheck.h" #include <map> #include <string> #include <algorithm> #include <vector> #include <set> #include <stdio.h> #include "CIntervalSeries.h" #include "CHistoryItem.h" #include "CSupplementMatrix.h" #include "CAssetsSummary.h" #include "CGroupsInfo.h" #include "CFilterAdvanced.h" #include "CStructureMap.h" #include "CPriceList.h" #include "CMatrix.h" using namespace std; typedef std::pair<int, time_t> unique_key; /// <summary>Является идентификатором типа функции, которую необходимо применять для расчетов</summary> enum class FunMode { Sum, AvgCheck }; class CPriceList; class CSalesHistory { public: CSalesHistory(); CSalesHistory(shared_ptr<list<CHistoryItem>> items); ~CSalesHistory(); void AddCheck(shared_ptr<CCheck> check); void AddLine(int checkId, time_t checkTime, int shopId, int assetId, double price, double volume, double discount); void AddLine(const CHistoryItem & item); void DeleteCheck(unique_key checkKey); double Income() const; double Volume() const; std::string ToString() const; int AmountOfAssets() const; /// <summary>Осуществляет поиск чека по паре уникальных параметров</summary> /// <param name="checkId">Идентификатор чека из системы пользователя (может быть не уникальным)</param> /// <param name="checkTime">Время продажи чека (time_t)</param> /// <returns>Умный указатель на объект CCheck</returns> shared_ptr<CCheck> FindCheck(int checkId, time_t checkTime) const; shared_ptr<CCheck> FindCheck(unique_key key) const; /// <summary>Возвращает множество assetId, которые принадлежат groupId</summary> /// <returns>Возвращает умный указатель на множество. Если ничего не найдено, возвращает указатель на nullptr</returns> shared_ptr<const set<int>> GetAssetsFromGroup(int groupId) const; /// <summary>Возвращает множество assetId, которые принадлежат хотя бы одной из groupIds</summary> /// <returns>Возвращает умный указатель на множество. Если ничего не найдено, возвращает указатель на nullptr</returns> shared_ptr<set<int>> GetAssetsFromGroup(const set<int> &groupIds) const; void SetGroupsInfo(shared_ptr<const CGroupsInfo> groupsInfo); /// <summary>Сопоставляет всякому assetId его группу groupId</summary> /// <returns>Возвращает groupId, либо -1, если ничего не найдено</returns> int GetGroupId(int assetId) const; set<int> GetGroupIds() const; shared_ptr<const CGroupsInfo> GetGroupsInfo() const; /// <summary>Осуществляет расчет показателя, задаваемого mode, с фильтром по торговым точкам, товарам и группам</summary> /// <param = "from">Время начала периода (если не задано, указывать nofilter)</param> /// <param = "to">Время конца периода (если не задано, указывать nofilter)</param> /// <param = "funMode">Определяет тип функции, которая будет вычисляться в ходе исполнения программы</param> /// <returns>Рассчитанное значение. Если фильтрация образовывает пустое множество, возвращается 0</returns> vector<double> CalculateDynamics(const CFilter & filter, FunMode funMode) const; void CalculateCheckStructure(const CFilter & filter, CStructureMap<int, double> & structureMap, int & amountOfChecks) const; void Clear(); shared_ptr<CSupplementMatrix> BuildSupplementMatrix(const CFilterAdvanced & filter) const; set<int> GetAllAssets() const; shared_ptr<CAssetsSummary> GetAssetsSummary(const CFilter & filter) const; shared_ptr<CPriceList> GenCurrentPriceList() const; void FillDaysStatistics(CMatrix &priceMatrix, CMatrix &volumeMatrix, CMatrix &incomeMatrix, const CFilterAdvanced & filter) const; const map<time_t, int> & CalcAmountOfChecks(); const map<time_t, int> & GetDaysAmountOfChecks() const; private: void AddInfoToCheck(shared_ptr<CCheck> check, int assetId, double price, double volume, double discount); void RemoveCheckFromInternalStructure(list<shared_ptr<CCheck>>::iterator checksIterator); shared_ptr<const CGroupsInfo> groupsInfoPtr; map<unique_key, shared_ptr<CCheck>> checks_map; // Определяет сопоставление (assetId, time) -> "указатель на чек" list<shared_ptr<CCheck>> checks; set<int> assetsAll; // множество всех активов, входящих в объект map<time_t, shared_ptr<CPriceList>> priceLists; map<time_t, int> amtOfChecks; };
Java
UTF-8
1,276
2.1875
2
[]
no_license
package com.white.servlet; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.white.model.Essay; import com.white.model.User; import com.white.service.EssayService; import com.white.service.UserService; public class AddEssayServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); HttpSession session=req.getSession(); User user=(User)session.getAttribute("user"); Essay essay=new Essay(); essay.setTitle(req.getParameter("title")); essay.setDescript(req.getParameter("descrption")); essay.setBlog(user.getBlog()); essay.setContent(req.getParameter("content")); essay.setDate(new Date()); essay.setPraiseNum(0); essay.setType("public"); EssayService.addEssay(essay); resp.sendRedirect("myIndex.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req,resp); } }
TypeScript
UTF-8
829
3.046875
3
[ "MIT" ]
permissive
export type MemoizeExpireConfig = { expirationInSeconds: number; }; export const memoizeExpire = <Params extends any[], Output>( config: MemoizeExpireConfig ) => (fn: (...params: Params) => Output) => { const previousResults: Map<Params, [Date, Output]> = new Map(); const addNew = (key: Params, value: Output) => { const currentDate = new Date(); const toExpire = new Date( currentDate.getTime() + 1000 * config.expirationInSeconds ); previousResults.set(key, [toExpire, value]); previousResults.forEach(([date], key) => { if (date < currentDate) { previousResults.delete(key); } }); return (...params: Params) => { if (!previousResults.has(params)) { addNew(params, fn(...params)); } return previousResults.get(params)[1]; }; }; };
Python
UTF-8
1,552
2.8125
3
[]
no_license
from datetime import datetime from dataclasses import dataclass from werkzeug.security import generate_password_hash, check_password_hash from sqlalchemy import Column, Integer, String, DateTime, Boolean from sqlalchemy.orm import validates from database import BaseModel @dataclass class User(BaseModel): id: int username: str date_joined: datetime last_login: datetime is_active: bool is_admin: bool __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(32), index=True, unique=True, nullable=False) password = Column(String(128), unique=True, nullable=False) date_joined = Column(DateTime, default=datetime.now(), nullable=False) last_login = Column(DateTime, nullable=True) is_admin = Column(Boolean, default=False) is_active = Column(Boolean, default=True) def __str__(self): return self.username @validates('username') def validate_username(self, key, username): assert username, 'No username provided' assert User.query.filter_by(username=username).first() is None, 'Username is already in use' assert len(username)>3 and len(username)<32, 'Username must be between 3 and 32 characters' return username def set_password(self, password): assert password, 'No password provided' self.password = generate_password_hash(password) def check_password(self, password): assert password, 'No password provided' return check_password_hash(self.password, password)
C
UTF-8
6,053
3.453125
3
[]
no_license
/******************** * Joseph Adams * jpadams * * cs341L * cache lab part A * due 11/11/20 * * This program simulates a cache by creating an array of doubly linked lists. * Each linked list is used to represent a set, with each node representing a * line in that set. ********************/ #include <stdio.h> #include <string.h> #include <getopt.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include "cachelab.h" int s; unsigned long S; //number of sets int E; int b; char* trace; //to accept from traceFile FILE* traceFile; //user specified traceFile pointer int hits = 0; int misses = 0; int evictions = 0; char inst; //I, M, L, S unsigned long address; //address from trace file int size; //size given by trace file. Does nothing. unsigned long tag; //tag of address unsigned long setIndex; //set index of address typedef struct node{ unsigned long tag; struct node* next; struct node* previous; } node; node** set; //used to point to array of node pointers, each pointing to the head of a doubly linked list unsigned long generateMask(int s){//helper function to return mask of 1's of length s unsigned long mask = 0; for(int i = 0; i < s; i++){ mask <<= 1; mask += 1; } return mask; } node* findTail(node* head){//returns tail of linked list if(head == NULL) return head; node* current = head; while(current -> next != NULL) current = current -> next; return current; } char search(node* head){ //looks for tag in list (set) //If found, changes order so our tag is head //returns 0 if not found if(head == NULL){ misses++; return 0; } node* current = head; while(current -> tag != tag){ if(current -> next == NULL){//tail reached misses++; return 0; } current = current -> next; } //only exits if tag has been found hits++; if(current == head) return 1; //tag already first else if(current == findTail(head)){//node is tail node* previous = current -> previous; previous -> next = NULL; head -> previous = current; current -> next = head; } else{ //node is not head or tail node* previous = current -> previous; node* next = current -> next; previous -> next = next; next -> previous = previous; current -> previous = NULL; current -> next = head; head -> previous = current; } set[setIndex] = current; //node is new head return 1; } int listLength(node* head){//returns length of a list if(head == NULL) return 0; int count = 1; node* current = head; while(current -> next != NULL){ count++; current = current -> next; } return count; } void createNode(node* head){//creates node and adds to front of list node* new = (node*) malloc(sizeof(node)); if(new == NULL){ printf("MALLOC FAILURE!\n"); exit(0); } new -> tag = tag; if(head != NULL){ new -> next = head; head -> previous = new; } set[setIndex] = new; //new node is now head } void evictNode(node* head){//will actually put tag in the tail and move to front of list node* tail = findTail(head); tail -> tag = tag; if(tail -> previous != NULL){ //tail is not head node* previous = tail -> previous; previous -> next = NULL; tail -> previous = NULL; tail -> next = head; head -> previous = tail; } set[setIndex] = tail; evictions++; } void updateCache(){//this is the function called by main(). It is called twice for 'M' node* head = set[setIndex]; if(!search(head)){//tag not found in cache if(listLength(head) < E) createNode(head); //set not full else evictNode(head); //set full, so evict } } void freeList(node* head){ //helper function for freeNodes(). frees a doubly linked list. if(head == NULL) return; node* current = head -> next; while(current != NULL){ node* next = current -> next; current = NULL; free(current); current = next; } free(head); } void freeNodes(){ for(int i = 0; i <= S; i++){ freeList(set[i]); } free(set); } int main(int argc, char** argv){ char opt; char hFlag = 0; //-h option char sMissing = 1; //flags used in case a parameter is missing char EMissing = 1; char bMissing = 1; char tMissing = 1; while((opt = getopt(argc, argv, "h:s:E:b:t:")) != -1){ switch(opt){ case 'h': hFlag = 1; case 's': s = atoi(optarg); sMissing = 0; break; case 'E': E = atoi(optarg); EMissing = 0; break; case 'b': b = atoi(optarg); bMissing = 0; break; case 't': trace = optarg; tMissing = 0; break; } } if(hFlag){ //printed if -h given printf("Options:\n"); printf(" -h Print this help message.\n"); printf(" -v Optional verbose flag.\n"); printf(" -s <num> Number of set index bits.\n"); printf(" -E <num> Number of lines per set.\n"); printf(" -b <num> Number of block offset bits.\n"); printf(" -t <file> Trace file.\n\n"); printf("Examples:\n"); printf(" linux> ./csim-ref -s 4 -E 1 -b 4 -t traces/yi.trace\n"); printf(" linux> ./csim-ref -v -s 8 -E 2 -b 4 -t traces/yi.trace\n"); return 0; } if(sMissing || EMissing || bMissing || tMissing){ //check for all the flags printf("A parameter is missing!\n"); return 0; } S = pow(2, s); //number of sets set = malloc(S*sizeof(node*)); //allocate array where each entry is a pointer to linked list. traceFile = fopen(trace, "r"); //open trace file if(traceFile == NULL){ printf("No trace file found!\n"); return 0; } while(fscanf(traceFile, " %c %lx, %d", &inst, &address, &size) > 0){//parse trace file if(inst == 'I') continue; tag = address >> (s + b); //get tag for address setIndex = (address >> b) & generateMask(s); //get set index for address if(inst == 'M') updateCache(); //update cache twice for 'M' updateCache(); } printSummary(hits, misses, evictions); freeNodes(); fclose(traceFile); return 0; }
TypeScript
UTF-8
1,142
2.859375
3
[ "MIT" ]
permissive
import ArrayPattern from '../nodes/ArrayPattern'; import AssignmentPattern from '../nodes/AssignmentPattern'; import Identifier from '../nodes/Identifier'; import ObjectPattern from '../nodes/ObjectPattern'; import RestElement from '../nodes/RestElement'; import { Node } from '../nodes/shared/Node'; export default function extractNames(param: Node) { const names: string[] = []; extractors[param.type](names, param); return names; } interface Extractors { [nodeType: string]: (names: string[], param: Node) => void; } const extractors: Extractors = { Identifier(names, param: Identifier) { names.push(param.name); }, ObjectPattern(names, param: ObjectPattern) { param.properties.forEach(prop => { extractors[prop.value.type](names, prop.value); }); }, ArrayPattern(names, param: ArrayPattern) { param.elements.forEach(element => { if (element) extractors[element.type](names, element); }); }, RestElement(names, param: RestElement) { extractors[param.argument.type](names, param.argument); }, AssignmentPattern(names, param: AssignmentPattern) { extractors[param.left.type](names, param.left); } };
Java
UTF-8
3,145
2.421875
2
[]
no_license
package com.yushilei.myapp.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * @auther by yushilei. * @time 2017/3/30-11:26 * @desc */ public class BezierSignatureView extends View { private Path mPath = new Path(); PointF cacheMidPointF = new PointF(); PointF lastPointF = new PointF(); PointF newPointF = new PointF(); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private Canvas mCanvas; private Bitmap bitmap; public BezierSignatureView(Context context) { super(context); } public BezierSignatureView(Context context, AttributeSet attrs) { super(context, attrs); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth(4); paint.setStrokeJoin(Paint.Join.ROUND); bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.RGB_565); mCanvas = new Canvas(bitmap); mCanvas.drawColor(Color.WHITE); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.WHITE); canvas.drawPath(mPath, paint); mCanvas.drawPath(mPath, paint); } boolean isFirstMoveP = false; @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: isFirstMoveP = true; break; case MotionEvent.ACTION_MOVE: newPointF.x = x; newPointF.y = y; comMidpointF(lastPointF, newPointF); if (isFirstMoveP) {//第一个Move点 isFirstMoveP = false; mPath.moveTo(cacheMidPointF.x, cacheMidPointF.y); } else { mPath.quadTo(lastPointF.x, lastPointF.y, cacheMidPointF.x, cacheMidPointF.y); } break; case MotionEvent.ACTION_UP: if (!isFirstMoveP) {//如果只是点击一下 就弹起 mPath.lineTo(x, y); } break; } lastPointF.x = x; lastPointF.y = y; invalidate(); return true; } private void comMidpointF(PointF a, PointF b) { cacheMidPointF.x = (a.x + b.x) / 2f; cacheMidPointF.y = (a.y + b.y) / 2f; } public void clear() { mPath.reset(); mCanvas.drawColor(Color.WHITE); invalidate(); } public Bitmap getSignBitmap() { return bitmap; } public Bitmap getDrawBitmap() { destroyDrawingCache(); buildDrawingCache(); Bitmap drawingCache = getDrawingCache(); return drawingCache; } }
Markdown
UTF-8
5,819
3.1875
3
[]
no_license
# 一面 这是人生第一次面试,开始之前很慌很慌。当打开视频时看到了一位女面试官,给我的感觉很和蔼可亲,内心的慌乱也减少了好多。 1. 首先做了自我介绍,当我说在ACM待过一年时间,那参加过很多比赛,她说不错呀看你这么爱编程,先出个编程题吧! 2. 编程题 * 第一道我记得是关于hashmap的,没太明白她说的啥意思(然后她就换了个题目) * 第二道是如何通过O(1)的时间复杂度,来查看一个数组最大值,这个题目我很熟悉,只需要借助一个辅助栈就好了。很快回答出来了,当时真应该好好想想再说也显得我思考了 3. TCP和UDP的区别 4. 三次握手四次挥手和原因 5. 线程和进程的区别 对设计模式是否了解 5. 如何使用Python设计一个单利模式 6. 观察者模式简单描述 7. 然后简单的介绍一下项目 8. 问关于是否在linux上部署的项目 9. memcached和redis(还读错了)的区别 10. 在项目部署前应该做一些什么操作 (我说的是让同学注册账号,然后体验一下项目是否有BUG),(面试官补充,注意项目的安全问题,还有高并发问题(因为360他们的用户很多,需要注意并发量)) 11. 是否在项目中注意过日志问题.(不懂,面试官补充:对于项目来说,当用户多的话有可能出现BUG,如果有日志的话,就可以很快的找到出现BUG的位置,可以节省好多的时间) 12. 项目那个地方用到了缓存 13. 项目中的个人中心主要包含什么属性 14. 项目中是否对账户的密码进行加密 ### 总结: 一面总体感觉还不错,虽然有地方没回答出来,面试官都给我说了说,自己也学到了不少。 通过一面我找到了自己的不足点:首先是设计模式的不太了解,还有就是Python的单例模式的实现不太了解, 还有进程线程部分理解的不够充分,还有Linux的使用不太熟悉,还有应该注意项目的安全问题,高并发问题。 # 二面 当去吃饭时,突然发信息说我通过了,请不要离开面试房间,急忙的跑回来。开始我以为凉了,想着就当一次练手吧。 等了好2个小时才等到二面,一打开是个男面试官(当时感觉不太好,后面也不好)。 1. 首先就是老一套自我介绍。 2. 编程题(一步步摧残我) * 第一道是对于10瓶水,其中一瓶有毒,毒发作时间是24小时,总时间是24小时,至少需要多少只兔子才能够验出那个瓶子是有毒的,当时稍微一想就说二分法,但是面试官好像不满意,又想想还是不太明白,他最后说四只兔子。下面是详细解答 十瓶水,我们用2进制表示 1 2 3 4 5 6 7 8 9 10 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 现在我们把10瓶水,然后取其中的某些瓶分成组 像这样 第4位为1 第3位为1 第2位为1 第1位为1 0001 0010 0100 1000 0011 0011 0110 1001 0101 0110 0111 1010 0111 0111 1001 1010 把每一纵列的水取出来一滴然后混合,现在我们有四瓶混合水 现在我们需要四只小兔兔,准备为了伟大的算法题而献身 她们喝水的时候我不敢看~ _ ~ 把第一位为1的给一号兔兔 把第二位为1的给二号兔兔 把第三位为1的给三号兔兔 把第四位为1的给四号兔兔 喝完 现在假设四号兔子,死了,另外3只没死 这意味着什么? 意味着第四位为1的瓶子中有一瓶有毒! 嫌疑人有 0001 0011 0101 0111 1001 然而我们知道,另外3只没死,意味着第一位为1,第二位为1,第三位为1的都没有毒 所以排除掉后面4个 真相只有一个! 0001是有毒! 如果我们对结果,用1代表死,0代表没死 那就是0001 对,兔子的存活编号就直接告诉看我们凶手是谁! 原因理解,其实很简单,这相当于是一个在与不在的二元判断 对于第一位为1的水,如果兔子死了,证明毒水里面第一位是1 依次类推,i号兔子的存亡状态决定了毒水编号二进制的i号是否为1 所以1000瓶水,是2^10次方,我们需要10位去表示,十只兔子去检验 * 第二道题是对于俩个数组,如何判断他俩的重复的元素。我当时想的是用for循环,对于每个元素判断是否在另一个列表中,这里我使用的是Python中的in方法,面试官问我 这个in 是怎么实现的 * 给一个ip地址,然后给出起点-终点还有对应的省份,然后找出ip对应的省份,ip相当于255进制的,转化成十进制后,然后进行查找。查找时用的是二分的方法,与以往的 二分不同的是,每个位置对应的是范围而不是确定的值。 3. session存在服务端,当有多个服务器怎么获取对应的session信息嘛。他们有一个存储地址,session服务器就是利用独立部署的session服务器(集群)统一管理session, 应用服务器每次读写session时候,都去访问session服务器。 ### 总结: 真的是菜呀!面试官这都是思维问题,唉,只怪脑子太少没答好! # HR面 HR基本都是唠家常,在这里也不记录了,只说一点就是多注意一些关于这个公司的信息,对自己的规划设计设计。
C#
UTF-8
2,342
2.703125
3
[]
no_license
using System.Text; using Extensions; using RingLAN; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace RingLANTests { /// <summary> ///This is a test class for MessageTest and is intended ///to contain all MessageTest Unit Tests ///</summary> [TestClass()] public class MessageTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion /// <summary> ///A test for Message Constructor ///</summary> [TestMethod()] public void MessageConstructorTest() { const string testPacket = "{TFD1234567890\0}"; byte[] data = Encoding.ASCII.GetBytes(testPacket); Message target = new Message(data); string laterData = Encoding.ASCII.GetString(target.ToByteArray(false)); if (laterData != testPacket) { Assert.Fail("Packets are different: {0} != {1}".With(laterData, testPacket)); } } } }
C#
UTF-8
1,698
2.6875
3
[]
no_license
using AutoMapper; using CleanArch.Application.DTOs; using CleanArch.Application.Interfaces; using CleanArch.Domain.Entities; using CleanArch.Domain.Interfaces; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace CleanArch.Application.Services { public class CategoryService : ICategoryService { private readonly ICategoryRepository _repository; private readonly IMapper _mapper; public CategoryService(ICategoryRepository repository, IMapper mapper) { _repository = repository; _mapper = mapper; } public async Task<IEnumerable<CategoryDTO>> GetAsync() { var categoriesEntity = await _repository.GetAsync(); return _mapper.Map<IEnumerable<CategoryDTO>>(categoriesEntity); } public async Task<CategoryDTO> GetByIdAsync(int? id) { var categoryEntity = await _repository.GetByIdAsync(id); return _mapper.Map<CategoryDTO>(categoryEntity); } public async Task AddAsync(CategoryDTO categoryDto) { var categoryEntity = _mapper.Map<Category>(categoryDto); await _repository.CreateAsync(categoryEntity); } public async Task UpdateAsync(CategoryDTO categoryDto) { var categoryEntity = _mapper.Map<Category>(categoryDto); await _repository.UpdateAsync(categoryEntity); } public async Task RemoveAsync(int? id) { var categoryEntity = _repository.GetByIdAsync(id).Result; await _repository.RemoveAsync(categoryEntity); } } }
TypeScript
UTF-8
612
2.75
3
[]
no_license
import { ActionTypes, ActionsCategories } from '../actions/categories'; import { WpCategory } from '../../interfaces/wp-category'; export interface CategoriesState { list: WpCategory[]; loading: Boolean; } const initialState: CategoriesState = { list: [], loading: false }; export function categoriesReducer(state = initialState, action: ActionsCategories) { switch (action.type) { case ActionTypes.LoadCategories: return { ...state, loading: true }; case ActionTypes.LoadedCategories: return { list: action.payload, loading: false }; } return state; }
Java
UTF-8
12,461
3.28125
3
[]
no_license
/* * AUTHOR: LUIS FELIPE CHAPARRO HURTADO * DATE: 21 NOVEMBER 2019 * DESCRIPTION: Program that allows to have salary information (random number between SMLV and SMLV * 4) of each of its N employees for each quarter of the year */ package proyecto.pkgfinal; import java.util.Scanner; import java.io.PrintWriter; public class PROYECTOFINAL { static int[][] Vector; static Scanner Keyboard = new Scanner(System.in); public static void main(String[] args) { try { int[] mostSalary = new int[2]; int[] lessSalary = new int[2]; int Opt = 6; while (Opt != 0) { Show_menu(); Opt = Keyboard.nextInt(); switch (Opt) { case 1: Vector = Generate_Salary(); Generate_Files(Vector); break; case 2: Show_result(Vector); case 3: System.out.println("The employees who earned more than $ 8,000,000 were " + Show_employees_won_most_of_8_millions(Vector)); break; case 4: System.out.println("The average salaries per quarter was " + Show_Average_1_Semester(Vector)); System.out.println("The average salaries per quarter was " + Show_Average_2_Semester(Vector)); System.out.println("The average salaries per quarter was " + Show_Average_3_Semester(Vector)); System.out.println("The average salaries per quarter was " + Show_Average_4_Semester(Vector)); break; case 5: mostSalary = Show_Employee_won_most(Vector); if (mostSalary != null) { System.out.println("The employee with the highest salary gain in the year was " + mostSalary[0] + " with " + mostSalary[1]); } break; case 6: lessSalary = Show_Employee_won_less(Vector); if (lessSalary != null) { System.out.println("The employee with the highest salary gain in the year was " + lessSalary[0] + " with " + lessSalary[1]); } break; } } } catch (Exception e) { System.err.println("Error. Aborted system by error: main(String[] args" + e.toString()); } } public static void Show_menu() { try { System.out.println("\n------SOFTWARE OF AYROLL FOR BOYACA ANCESTRAL FOOD------\n" + "CREATED BY: LUIS FELIPE CHAPARRO HURTADO\n"); System.out.println("MENU PRINCIPAL:\n" + "1. Generate Database\n" + "2. Display database\n" + "3. Employees who earned more than $ 8,000,000\n" + "4. Average salaries per quarter.\n" + "5. Employee with the highest salary gain in the year.\n" + "6. Employee with lower salary gain in the year\n" + "0. Exit the software\n"); System.out.println("Select an option"); } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_menu() " + e.toString()); } } public static int[][] Generate_Salary() { try { Scanner Keyboard = new Scanner(System.in); System.out.println("How many employees do you want to enter the program?"); int N = Keyboard.nextInt(); int[][] Vector = new int[N][4]; for (int i = 0; i < N; i++) { for (int j = 0; j < 4; j++) { Vector[i][j] = (int) (Math.random() * (3312464 - 828116) + 828116); } } return Vector; } catch (Exception e) { System.err.println("Error. Aborted system for error: int Generate_Salary () " + e.toString()); return null; } } public static void Show_result(int[][] Salary) { try { for (int i = 0; i < Salary.length; i++) { System.out.println("\nThe employee: " + (i + 1)); System.out.println("In the 1° semester won " + Salary[i][0] + " millions of pesos"); System.out.println("In the 2° semester won " + Salary[i][1] + " millions of pesos"); System.out.println("In the 3° semester won " + Salary[i][2] + " millions of pesos"); System.out.println("In the 4° semester won " + Salary[i][3] + " millions of pesos"); int Total = Salary[i][0] + Salary[i][1] + Salary[i][2] + Salary[i][3]; System.out.println("\nThe employee " + (i + 1) + " have a salary annual of " + Total); } System.out.println("\nThe employee with the highest salary gain in the year was " +Show_Employee_won_most(Salary)[0]); System.out.println("The employee with lower salary gain in the year was " + Show_Employee_won_less(Salary)[0]); System.out.println("The average salary for the first quarter was " + Show_Average_1_Semester(Salary)); System.out.println("The average salary for the second quarter was " + Show_Average_2_Semester(Salary)); System.out.println("The average salary for the third quarter was " + Show_Average_3_Semester(Salary)); System.out.println("The average salary for the fourth quarter was " + Show_Average_4_Semester(Salary)); } catch (Exception e) { } } public static int[] Show_Employee_won_most(int[][] Salary) { try { int[] Result = new int[2]; int Max = 0; int Person = 0; for (int i = 0; i < Salary.length; i++) { int Total = Salary[i][0] + Salary[i][1] + Salary[i][2] + Salary[i][3]; if (i == 0) { Max = Total; Person = i; } else if (Total > Max) { Max = Total; Person = i; } } Result[0] = Person + 1; Result[1] = Max; return Result; } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_Employee_won_most (int [][] Salary) " + e.toString()); return null; } } public static int [] Show_Employee_won_less(int[][] Salary) { try { int[] Result = new int[2]; int Min = 0; int Person = 0; for (int i = 0; i < Salary.length; i++) { int Total = Salary[i][0] + Salary[i][1] + Salary[i][2] + Salary[i][3]; if (i == 0) { Min = Total; Person = i; } else if (Total < Min) { Min = Total; Person = i; } } Result[0] = Person + 1; Result[1] = Min; return Result; } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_Employee_won_less (int [][] Salary) " + e.toString()); return null; } } public static double Show_Average_1_Semester(int[][] Salary) { try { int Sum = 0; for (int i = 0; i < Salary.length; i++) { Sum += Salary[i][0]; } double Average = Sum / Salary.length; return Average; } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_Average(int[][] Salary)" + e.toString()); return 0; } } public static double Show_Average_2_Semester(int[][] Salary) { try { int Sum = 0; for (int i = 0; i < Salary.length; i++) { Sum += Salary[i][1]; } double Average = Sum / Salary.length; return Average; } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_Average(int[][] Salary)" + e.toString()); return 0; } } public static double Show_Average_3_Semester(int[][] Salary) { try { int Sum = 0; for (int i = 0; i < Salary.length; i++) { Sum += Salary[i][2]; } double Average = Sum / Salary.length; return Average; } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_Average(int[][] Salary)" + e.toString()); return 0; } } public static double Show_Average_4_Semester(int[][] Salary) { try { int Sum = 0; for (int i = 0; i < Salary.length; i++) { Sum += Salary[i][3]; } double Average = Sum / Salary.length; return Average; } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_Average(int[][] Salary)" + e.toString()); return 0; } } public static int Show_employees_won_most_of_8_millions(int[][] Salary) { try { int Most_of_20 = 0; for (int i = 0; i < Salary.length; i++) { int Total = Salary[i][0] + Salary[i][1] + Salary[i][2] + Salary[i][3]; if (Total >= 8000000) { Most_of_20 += 1; } } return Most_of_20; } catch (Exception e) { System.err.println("Error. Aborted system for error: Show_employees_won_most_of_20_millions(int [][] Salary)" + e.toString()); return 0; } } public static void Generate_Files(int[][] Salary) { try { PrintWriter Archivo = new PrintWriter("d:/ SALARY_EMPLOYEES.txt", "UTF-8"); Archivo.println("-----------------SALARY EMPL0YEES------------------\n" + "CREATED BY:LUIS FELIPE CHAPARRO HURTADO\n" + "DATE: 21 NOVEMBER 2019"); for (int i = 0; i < Salary.length; i++) { Archivo.println("\nThe employee: " + (i + 1)); Archivo.println("In the 1° semester won " + Salary[i][0] + " millions of pesos"); Archivo.println("In the 2° semester won " + Salary[i][1] + "" + "1 millions of pesos"); Archivo.println("In the 3° semester won " + Salary[i][2] + " millions of pesos"); Archivo.println("In the 4° semester won " + Salary[i][3] + " millions of pesos"); int Total = Salary[i][0] + Salary[i][1] + Salary[i][2] + Salary[i][3]; Archivo.println("\nThe employee " + (i + 1) + " have a salary annual of " + Total); } Archivo.println("\nThe employee with the highest salary gain in the year was " +Show_Employee_won_most(Salary)[0]); Archivo.println("The employee with lower salary gain in the year was " + Show_Employee_won_less(Salary)[0]); Archivo.println("The average salary for the first quarter was " + Show_Average_1_Semester(Salary)); Archivo.println("The average salary for the second quarter was " + Show_Average_2_Semester(Salary)); Archivo.println("The average salaries per third was " + Show_Average_3_Semester(Salary)); Archivo.println("The average salaries per fourth was " + Show_Average_4_Semester(Salary)); Archivo.println("\nThe employees who earned more than $ 8,000,000 were " + Show_employees_won_most_of_8_millions(Salary)); Archivo.close(); System.out.println("Correct and finished process. The txt \"SALARY_EMPLOYEES\" was created and was located in the unit d"); } catch (Exception e) { System.err.println("Error. Aborted system for error: Generate_Files (int [][] Salary)" + e.toString()); } } }
Markdown
UTF-8
3,982
2.546875
3
[ "CC-BY-4.0", "MIT" ]
permissive
# Översikt ## [Vad är Event Hubs?](event-hubs-what-is-event-hubs.md) ## [Event Hubs-funktioner](event-hubs-features.md) ## [Vanliga frågor och svar](event-hubs-faq.md) # Kom igång ## [Skapa en Event Hub](event-hubs-create.md) ## Skicka händelser ### [.NET-standard](event-hubs-dotnet-standard-getstarted-send.md) ### [.NET Framework](event-hubs-dotnet-framework-getstarted-send.md) ### [Java](event-hubs-java-get-started-send.md) ### [C](event-hubs-c-getstarted-send.md) ## Ta emot händelser ### [.NET-standard](event-hubs-dotnet-standard-getstarted-receive-eph.md) ### [.NET Framework](event-hubs-dotnet-framework-getstarted-receive-eph.md) ### [Java](event-hubs-java-get-started-receive-eph.md) ### [Apache Storm](event-hubs-storm-getstarted-receive.md) ## Samla in händelser ### [Använd Azure Portal för att aktivera Event Hubs Capture](event-hubs-capture-enable-through-portal.md) ### [Använd en Resource Manager-mall för att aktivera Event Hubs Capture](event-hubs-resource-manager-namespace-event-hub-enable-capture.md) ## [Programmeringsguide](event-hubs-programming-guide.md) # Gör så här för att ## Planera och designa ### [Geo-haveriberedskap och geo-replikering](event-hubs-geo-dr.md) ### [Event Hubs Dedicated](event-hubs-dedicated-overview.md) ### [Översikt över autentisering och säkerhetsmodell](event-hubs-authentication-and-security-model-overview.md) ### [Tillgänglighet och konsekvens](event-hubs-availability-and-consistency.md) ### [Skala dataflödesenheter automatiskt](event-hubs-auto-inflate.md) ## Utveckla ### [Tillgängliga API:er](event-hubs-api-overview.md) #### [.NET-standard](event-hubs-dotnet-standard-api-overview.md) #### [.NET Framework](event-hubs-dotnet-framework-api-overview.md) #### [Diagnostikloggar](event-hubs-diagnostic-logs.md) ### [AMQP 1.0-protokollguide](../service-bus-messaging/service-bus-amqp-protocol-guide.md) ## Hantera ### [Övervaka Event Hubs med Azure-övervakning](event-hubs-metrics-azure-monitor.md) ### [Event Hubs-hanteringsbibliotek](event-hubs-management-libraries.md) ### Capture #### [Event Hubs Capture](event-hubs-capture-overview.md) #### [Samla in Event Hubs-data med hjälp av Python](event-hubs-capture-python.md) ### [Etablera entiteter med PowerShell](event-hubs-manage-with-ps.md) ### [Strömma Azure Diagnostics-data med Event Hubs](event-hubs-streaming-azure-diags-data.md) ### [Skapa och distribuera en Event Hub med en Resource Manager-mall](event-hubs-resource-manager-namespace-event-hub.md) # Referens ## [Kodexempel](https://azure.microsoft.com/en-us/resources/samples/?service=event-hubs) ## Java ### [com.microsoft.azure.eventhubs](/java/api/com.microsoft.azure.eventhubs) ### [com.microsoft.azure.eventprocessorhost](/java/api/com.microsoft.azure.eventprocessorhost) ## .NET ### [Microsoft.Azure.EventHubs](/dotnet/api/microsoft.azure.eventhubs) ### [Microsoft.Azure.EventHubs.Processor](/dotnet/api/microsoft.azure.eventhubs.processor) ### [Microsoft.ServiceBus.Messaging](/dotnet/api/microsoft.servicebus.messaging) ### [Microsoft.ServiceBus.Messaging.EventProcessorHost](/dotnet/api/microsoft.servicebus.messaging.eventprocessorhost) ### [Microsoft.Azure.Management.EventHub](/dotnet/api/microsoft.azure.management.eventhub) ## [REST](/rest/api/eventhub) ## [Undantag](event-hubs-messaging-exceptions.md) ## [Kvoter](event-hubs-quotas.md) # Resurser ## [Azure-översikt](https://azure.microsoft.com/roadmap/?category=internet-of-things) ## [Kodexempel](event-hubs-samples.md) ## [Utbildningsväg](https://azure.microsoft.com/documentation/learning-paths/event-hubs/) ## [Prissättning](https://azure.microsoft.com/pricing/details/event-hubs/) ## [Priskalkylator](https://azure.microsoft.com/pricing/calculator/) ## [Tjänstuppdateringar](https://azure.microsoft.com/updates/?product=event-hubs) ## [Stack Overflow](http://stackoverflow.com/questions/tagged/azure-eventhub) ## [Videoklipp](https://azure.microsoft.com/documentation/videos/index/?services=event-hubs)
Java
UTF-8
1,009
1.96875
2
[]
no_license
package com.sale.myweb; import com.sale.myweb.entity.Users; import com.sale.myweb.DAO.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class ApplicationTests { @Autowired private UserRepository userRepository; @Test public void test() throws Exception { // 创建10条记录 // userRepository.save(new Users("AAA", 10)); // userRepository.save(new Users("BBB", 20)); // userRepository.save(new Users("CCC", 30)); // userRepository.save(new Users("DDD", 40)); } // @Autowired // private JdbcTemplate jdbcTemplate; // @Test // public void test() throws Exception { // jdbcTemplate.update("INSERT INTO dbo.abina VALUES (?,?)",1,2); // // } }
PHP
UTF-8
1,842
2.65625
3
[]
no_license
<html xmlns="http://www.w3.org/1999/html"> <head> <title>Test PHP Connection Script</title> </head> <body> <h3>RESULTS</h3> <table> <tr> <td> <?php $dbname = 'cs332t26'; $dbuser = 'cs332t26'; $dbpass = 'cho4Iich'; $dbhost = 'localhost'; $connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to '$dbhost'"); $CRS = $_POST["COURSE"]; mysql_select_db($dbname) or die("Could not open the database '$dbname'"); $result = mysql_query(" SELECT unique_number, course_title, section_number, class_room, meeting_days, beginning_time, ending_time, (seats-COUNT(student_id)) as 'Seats' FROM course, record, sections WHERE enroll_sec = section_number AND unique_number = course_num AND enroll_course = $CRS GROUP BY section_number"); printf("</tr><td>" . "Course Title" . "</td><td>" . "Classroom" . "</td><td>" . "Meeting Days" . "</td><td>" . "Start Time" . "</td><td>" . "End Time" . "</td><td>" . "Seats". "</td></tr>"); while ($row = mysql_fetch_array($result)) { printf("</tr><td>" .$row ['course_title'] . "</td><td>" . $row['class_room'] . "</td><td>" .$row['meeting_days'] . "</td><td>" .$row ['beginning_time'] . "</td><td>" . $row['ending_time'] . "</td><td>" . $row['Seats']. "</td></tr>"); } ?> <button onclick="goBack()">Go Back</button> <script> function goBack(){ window.history.back(); } </script> </td> </tr> </table> </body> </html>
Java
UTF-8
262
1.6875
2
[]
no_license
package com.terrence.iread.view.activity; import com.terrence.iread.model.BookBean; import com.terrence.iread.view.base.IBaseLoadView; public interface IBookDetail extends IBaseLoadView { void addBookCallback(); void getBookInfo(BookBean bookBean); }
Java
UTF-8
5,478
2.546875
3
[]
no_license
package net.tudelft.hi.e.computation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.tudelft.hi.e.data.Column; import net.tudelft.hi.e.data.DateColumn; import net.tudelft.hi.e.data.DateValue; import net.tudelft.hi.e.data.NumberColumn; import net.tudelft.hi.e.data.NumberValue; import net.tudelft.hi.e.data.Record; import net.tudelft.hi.e.data.StringValue; import net.tudelft.hi.e.data.Table; import net.tudelft.hi.e.data.Value; import net.tudelft.hi.e.input.Settings; import org.junit.Before; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; /** * Test for BetweenOperation. */ public class BetweenOperationTest { Table dataTable; Settings settings; BetweenOperation lo; ArrayList<Column> cols; /** * Creates dummy table and creates the operation. * * @throws ParseException if the date is incorrect */ @Before public void setUp() throws ParseException { cols = new ArrayList<Column>(); cols.add(new NumberColumn("eventtype")); cols.add(new DateColumn("date")); // Table with test data dataTable = new Table(); dataTable.add(new Record(cols, new Value[] {new StringValue("A"), new DateValue(new SimpleDateFormat("ddMMyy").parse("120599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("A"), new DateValue(new SimpleDateFormat("ddMMyy").parse("130599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("C"), new DateValue(new SimpleDateFormat("ddMMyy").parse("140599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("B"), new DateValue(new SimpleDateFormat("ddMMyy").parse("150599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("B"), new DateValue(new SimpleDateFormat("ddMMyy").parse("160599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("B"), new DateValue(new SimpleDateFormat("ddMMyy").parse("170599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("A"), new DateValue(new SimpleDateFormat("ddMMyy").parse("180599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("B"), new DateValue(new SimpleDateFormat("ddMMyy").parse("190599"))})); dataTable.add(new Record(cols, new Value[] {new StringValue("A"), new DateValue(new SimpleDateFormat("ddMMyy").parse("200599"))})); settings = new Settings(); settings.getColumns().addAll(cols); lo = new BetweenOperation(dataTable, "eventtype", "date", new StringValue("A"), new StringValue( "B")); } @Test public void test() { lo.execute(); final Table res = lo.getResult(); assertEquals(9, res.size()); assertEquals(new NumberValue(86400 * 2 / (60 * 60)), res.get(1).get("time_between")); assertEquals(new NumberValue(86400 * 1 / (60 * 60)), res.get(6).get("time_between")); for (int index : Arrays.asList(new Integer[] {0, 2, 3, 4, 5, 7, 8})) { assertNull(res.get(index).get("time_between")); } } @Test public void equalityTest() { BetweenOperation t1 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); BetweenOperation t2 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); assertTrue(t1.equals(t2)); } @Test public void equalInstanceTest() { BetweenOperation t1 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); assertTrue(t1.equals(t1)); } @Test public void equalityNullTest() { BetweenOperation t1 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); assertFalse(t1.equals(null)); } @Test public void equalityStringTest() { BetweenOperation t1 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); assertFalse(t1.equals("foobar")); } @Test public void equalityWrongPropertyTest() { BetweenOperation t1 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); BetweenOperation t2 = new BetweenOperation(dataTable, "a", "b", "X", new StringValue("d"), new StringValue("e")); assertFalse(t1.equals(t2)); } @Test public void hashEqualTest() { BetweenOperation t1 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); BetweenOperation t2 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); assertEquals(t1.hashCode(), t2.hashCode()); } @Test(expected = InputMismatchException.class) public void testWrongColumnException() { new BetweenOperation(dataTable, "eventtype", "eventtype", new StringValue("A"), new StringValue("C")).execute(); } @Test public void testToStringSingleCount() { BetweenOperation t1 = new BetweenOperation(dataTable, "a", "b", "c", new StringValue("d"), new StringValue("e")); String expected = "BetweenOperation [datecol=b, datecol2=c, eventcol=a, ev1val=d, ev2val=e]"; assertEquals(expected, t1.toString()); } }
Java
UTF-8
1,402
3.671875
4
[]
no_license
package org.ventry.commons.algorithm.sort; public class InsertionSort { public static int[] order(int[] source) { for (int i = 1; i < source.length; i++) { int key = source[i]; int j = i - 1; while (j > -1 && source[j] > key) { source[j + 1] = source[j]; j--; } source[j + 1] = key; } return source; } public static int[] orderDescending(int[] source) { for (int i = 1; i < source.length; i++) { int key = source[i]; int j = i - 1; while (j > -1 && source[j] < key) { source[j + 1] = source[j]; j--; } source[j + 1] = key; } return source; } /** * array.size位于[10000, *)区间内,二分查找插入排序优于原始插入排序 * @param source * @return */ public static int[] orderBybinarySearch(int[] source) { for (int i = 1; i < source.length; i++) { int key = source[i]; int index = binarySearchIndex(source, i, key); if(i != index) { int j = i - 1; while (j >= index) { source[j + 1] = source[j]; j--; } source[j + 1] = key; } } return source; } private static int binarySearchIndex(int[] array, int end, int key) { int low = 0; int high = end; while (low <= high) { int mid = (low + high) / 2; if (key < array[mid]) { high = mid - 1; } else if (key > array[mid]) { low = mid + 1; } else { return mid; } } return low; } }
Markdown
UTF-8
5,681
2.921875
3
[]
no_license
# lang-ko_KO ### READ THIS WHEN YOU WANT TO MAKE TRANSLATIONS TO ANOTHER LANGUAGE There are sixteen text files included in this repository, each with their own section of translations: - translations.txt -- these are general translations and loaded each time - helptext.txt -- these are all help text sections and loaded each time - dashboard.txt -- these are translations for the dashboard section - main.txt -- these are translations for the main section - shares.txt -- these are translations for the shares section - users.txt -- these are translations for the users section - settings.txt -- these are translations for the settings section - plugins.txt -- these are translations for the plugins section - docker.txt -- these are translations for the docker section - vms.txt -- these are translations for the vms section - tools.txt -- these are translations for the tools section - javascript.txt -- these are translations for javascript scripts - scripts.txt -- these are translations for local scripts - apps.txt -- these are translations for the CA section - ca_settings -- these are translations for the CA settings - javascript.ca.txt-- these are translations for the CA javascript All file names are in lowercase and should be included in the repository to make the translations complete. Removing a particular file, means no translations will be available for that section and the GUI will display text in original English. ### TRANSLATIONS Each text file contains regular text strings stored in UTF-8 format with linux line-endings. Use a text editor which supports UTF-8 and linux format, like [notepad++](https://notepad-plus-plus.org/downloads) The content of each text file is separated into two parts ### PART 1 These are single line entries which are in the format: `original English text=translated Foreign text` Only modify the text after the equal sign(=) and leave the original English text at the left untouched. Removing a line or omitting a translation after the equal sign, results in the GUI displaying this line with the original English text. The translated text may have 'special characters', such as slashes, parenthesis or brackets which are not included in the key text, but which are used to display text accordingly. E.g. `Options see Help=Options (see Help)` The characters \* and \*\* are used to display text in italics and bold respectively. E.g. `Array must be Stopped to change=Array must be **Stopped** to change` It is recommended to make translations per section, that is one file at the time, and verify the correctness of the translations in the GUI before proceeding with the next section. Keep in mind the length of the translations and try to make them similar length as the original text and avoid space issues in the GUI. ### PART 2 These are multi line entries used to translate multiple lines at once. Multi line translations have a unique opening and closing tag: **:unique_tag_name_plug:** - unique opening tag used for any multi line text section **:end** - closing tag Do not remove or alter these tags and only translate the text between the opening and closing tags! ### HELP TEXT All help text of the GUI is stored in a single file *helptext.txt*. This file has multiple help text sections. Each section is enclosed by a unique opening tag and corresponding closing tag. **:unique_tag_name_help:** - unique opening tag used for a help text section **:end** - corresponding closing tag Do not remove or alter these tags and only translate the text between the opening and closing tags! Be aware that Markdown styling syntax is used, this must be preserved. ### LOCAL TESTING Once the translations are complete and you want to test locally the (intermediate) results, the text files need to be zipped into a single ZIP file. Give the ZIP file the name of your language, e.g. French.zip. In the GUI go to: Tools -> webGUI -> Language (switch to Developer view) - By default only the English language is installed (built-in) - Choose the ZIP file you have created earlier as the source file - If the language name is recognized, it will be automatically selected, otherwise chose the name of the language from the dropdown menu to install. - Click on "Upload" will add your translations to the GUI under the selected language name NOTE: If your language is not available from the dropdown menu, please make a request on the [Unraid forum](https://forums.unraid.net/forum/75-multi-language-section/) Now your language is available for local testing! In the GUI go to: Settings -> Display Settings -> Language - Select the preferred language from the dropdown menu. Note that only the available language choices are displayed here. ### GITHUB A language repository will be made available at [Github](https://github.com/unraid), where translators can create Pull Requests (PR) and submit their work. Once you are satisfied with your results, use Github (an account is required) to fork the respective language repository and create a PR with your modifications. Limetech will review this and merge your work when approved. ### UPDATES When updated source text files in English become available in the future, these updates will be made available through Github. Translators can use the Github system to see which changes are made and update their translations accordingly. ### CREDITS Your efforts are much welcomed and to show our appreciation, your name and language are credited on the Credits page under Tools in the GUI. Please let us know which credentials to use. Thank you very much!
PHP
UTF-8
1,140
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Trainee extends Model { // Connection protected $connection = 'sys_training'; // Primary key protected $primaryKey = 'trainee_code'; // Table protected $table = 'trainees_masterfile'; // Fillable fields protected $fillable = ['trainee_code','first_name', 'middle_name', 'last_name', 'nickname', 'dealer_id', 'street_address', 'telephone_no', 'email', 'job_position_id', 'employment_status_id', 'date_hired', 'date_of_birth', 'gender', 'picture', 'create_user', 'date_created', 'update_user', 'date_updated']; public $timestamps = false; // Relationship public function user() { return $this->hasOne('App\Models\User'); } public function dealer() { return $this->belongsTo('App\Models\Dealer', 'dealer_id'); } public function position() { return $this->belongsTo('App\Models\Position', 'job_position_id'); } public function status() { return $this->belongsTo('App\Models\Status', 'employment_status_id'); } // Name format public function getFullname() { return ucwords($this->first_name . ' ' . $this->last_name); } }
Java
UTF-8
293
1.53125
2
[]
no_license
package com.kino.kino.model.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class UserPostAuthDto { String username; String password; String lang; }
JavaScript
UTF-8
801
3.84375
4
[]
no_license
//Define a variable here called currentTurn and make it equal to the STRING "X" var TTT = { changeElement: function(piece) { if (currentTurn == "X") { $("#" + piece).html("X"); //Call the function checkWin //Make currentTurn equal to "O" } else { $("#" + piece).html("O"); //Call the function checkWin //Make currentTurn equal to "X" } }, checkWin: function() { //Write the logic for checking for a win } }; //Bind a click event to the DOM td element with the class .game-board if ($(this).html() !== "") { //Write an alert here that says "This spot has been taken...Sorry!" //Return false here } else { var gamePiece = $(this).attr("id"); //Call the function TTT.changeElement passing in the above variable (gamePiece) as a parameter } });
Java
UTF-8
618
2.21875
2
[]
no_license
package com.winwin.android.UI.Entity; import java.util.List; public class BaseHttpResult<T> { private StatusBean status; private int totalRows; private List<T> data; public StatusBean getStatus() { return status; } public void setStatus(StatusBean status) { this.status = status; } public int getTotalRows() { return totalRows; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } }
C++
UTF-8
1,084
2.796875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void printing(vector< vector<int> > arr) { cout<<'\n'; int n = arr.size(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<arr[i][j]<<' '; } cout<<'\n'; } } int optimalSearchTree(int keys[],int freq[],int n) { int i,j,k,l; vector< vector<int> > v(n,vector<int>(n)); vector< vector<int> > f(n,vector<int>(n)); for(i=0;i<n;i++) { v[i][i] = freq[i]; } for(i=0;i<n;i++) { int sum = 0; for(j=i;j<n;j++) { sum += freq[j]; f[i][j] = sum; } } //printing(f); for(k=1;k<n;k++) { for(i=0;i<n-k;i++) { j = i+k; v[i][j] = f[i][j]; int min = INT_MAX; for(l=i;l<=j;l++) { int a,b; if(l-1<0) a = 0; else a = v[i][l-1]; if(l+1>=n) b = 0; else b = v[l+1][j]; if(min>a+b) min = a+b; } v[i][j]+=min; } } printing(v); return v[0][n-1]; } int main() { int i,j,k,l; int keys[] = {10, 12, 20}; int freq[] = {34, 8, 50}; int n = sizeof(keys)/sizeof(keys[0]); printf("Cost of Optimal BST is %d ", optimalSearchTree(keys, freq, n)); return 0; }
Python
UTF-8
311
2.828125
3
[]
no_license
i = 0 with open('damaged.jpg', 'rb') as jpg: with open('recover.jpg', 'wb') as new_jpg: while True: chunk = jpg.read(1024) i += 1 if not chunk: break if i % 3 == 0: chunk = chunk[::-1] new_jpg.write(chunk)
Markdown
UTF-8
2,153
3.578125
4
[]
no_license
# 为云主机分配浮动 IP ## 分配浮动 IP * 前提: * 云主机的状态为 "Active"; * 租户已经创建了路由,且路由连接了外网; * 外网使用了 DHCP,DHCP 池中还有可用 IP。 * 操作: 1. 登录 OpenStack 管理界面; 1. 点击 【Project】 选项卡,点击 【Compute】 子选项卡,点击其中的 【Instances】 选项; 1. 选择要分配浮动 IP 的云主机,点击 【Actions】 中的 【Associate Floating IP】; 1. 在弹出的 【Manage Floating IP Associations】 对话框中,为云主机选择一个 IP 地址; 1. 如果 IP Address 列表中为空,则点击 【+】 按钮,在弹出的 【Allocate Floating IP】 对话框中,选择从哪一个池中分配 IP,点击对话框右下角的 【Allocate IP】 按钮; 1. 返回 【Manage Floating IP Associations】 对话框,在 "Port to be associated" 下拉列表中找到要分配的云主机名以及对应的端口,选择后点击对话框右下角的 【Associate】 按钮。 * 预期结果: * 为云主机分配浮动 IP 成功; * 界面有成功提示; * 在云主机列表的 "IP Address" 一栏中,看到增加了外网的 IP 地址; * 可以从外网通过浮动 IP 访问云主机。 ## 释放浮动 IP * 前提: * 用户从外网的 DHCP 地址池中分配了 IP; * IP 地址已被云主机使用。 * 操作: 1. 登录 OpenStack 管理界面; 1. 点击 【Project】 选项卡,点击 【Compute】 子选项卡,点击其中的 【Access & Security】 选项; 1. 在右侧点击 【Floating IPs】 标签,在 【Floating IPs】 列表中,选择要释放的 IP 地址,点击 【Actions】 中的 【Disassociate】; 1. 在弹出的 【Confirm Disassociate】 对话框中点击右下角的 【Disassociate】 按钮。 * 预期结果: * IP 地址成功被释放,界面上有成功提示; * 云主机列表中的 "IP Address" 没有浮动 IP 的显示; * 云主机不再拥有外网浮动 IP 地址,无法从外网访问云主机; * 被释放的 IP 地址可以重新被分配给其他云主机使用。
Java
UTF-8
304
2.625
3
[]
no_license
package Instrument; public abstract class Instrument { // declare fields protected String name; protected boolean hasStrings; public Instrument(String name, boolean hasStrings) { this.name = name; this.hasStrings = hasStrings; } // declare non-abstract methods }
Java
UTF-8
2,620
2.5
2
[]
no_license
package com.example.medina.freeaudiobooks.Services; import android.app.Service; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.IBinder; import android.support.annotation.RestrictTo; import android.util.Log; import java.io.IOException; public class PlayerService extends Service implements MediaPlayer.OnCompletionListener { /** * This field is used for testing purposes. * It can be used by the tests only */ @RestrictTo(RestrictTo.Scope.TESTS) private static boolean isServiceStarted; final String LOG_TAG = "myLogs"; private MediaPlayer mediaPlayer; /** * creating new MediaPlayer instance */ public void onCreate() { isServiceStarted = true; mediaPlayer = new MediaPlayer(); mediaPlayer.setOnCompletionListener(this); } /** * this method get the intent sent by BookActivity * extracts extras from it, check if the media is * already playing, and starts playback * @param intent * @param flags * @param startId * @return */ public int onStartCommand(Intent intent, int flags, int startId) { String link = intent.getStringExtra("link"); try { Uri myUri = Uri.parse(link); if (!mediaPlayer.isPlaying()) { try { mediaPlayer.setDataSource(this, myUri); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); Log.d(LOG_TAG, "ERROR!"); } } } catch (NullPointerException e) { e.printStackTrace(); } return START_STICKY; } /** * release mediaplayer when the secvice is * stopped */ public void onDestroy(){ try { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } mediaPlayer.release(); } catch (NullPointerException e) { e.printStackTrace(); } isServiceStarted = false; } public IBinder onBind(Intent intent) { return null; } public void onCompletion(MediaPlayer mediaPlayer) { stopSelf(); } public static boolean isServiceStarted() { return isServiceStarted; } }
Java
UTF-8
2,397
3.390625
3
[]
no_license
package step; import java.util.Scanner; public class Task_6 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i = (int) (1 + Math.random()*31); int j = (int) (1 + Math.random()*12); if (j == 1) { if (i != 7) System.out.println("Сегодня : " + i + " января."); else System.err.println("Сегодня РОЖДЕСТВО : " + i + " января."); } else if (j == 2) { if (i == 31 || i == 30) System.out.println("Дата: " + i + " февраля" + " не является валидной!"); else System.out.println("Сегодня :" + i + " февраля."); } else if (j == 3) System.out.println("Сегодня : " + i + " марта."); else if (j == 4) { if (i == 31 ) System.out.println("Дата: " + i + "апреля" + " не является валидной!"); else System.out.println("Сегодня :" + i + " апреля."); } else if (j == 5) System.out.println("Сегодня : " + i + " мая."); else if (j == 6) { if (i == 31 ) System.out.println("Дата: " + i + "июня" + " не является валидной!"); else System.out.println("Сегодня :" + i + " июня."); } else if (j == 7) System.out.println("Сегодня : " + i + " июля."); else if (j == 8) System.out.println("Сегодня : " + i + " августа."); else if (j == 9) { if (i == 31 ) System.out.println("Дата: " + i + " сентября" + " не является валидной!"); else System.out.println("Сегодня :" + i + " сентября."); } else if (j == 10) System.out.println("Сегодня : " + i + " октября."); else if (j == 11) { if (i == 31 ) System.out.println("Дата: " + i + " ноября" + " не является валидной!"); else System.out.println("Сегодня :" + i + " ноября."); } else if (j == 12) { if (i < 31) System.out.println("Сегодня : " + i + " декабря."); else System.err.println("Сегодня НОВЫЙ ГОД : " + i + " декабря."); } sc.close(); } }
C#
UTF-8
16,935
3.015625
3
[]
no_license
using System; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; namespace YuanTu.YuHangArea.ISO8583 { public class Cryptography { public Cryptography() { IV = new byte[8]; Key = new byte[8]; CipherMode = CipherMode.CBC; PaddingMode = PaddingMode.None; } /// <summary> /// DES加密所采用的算法 /// </summary> public CipherMode CipherMode { get; set; } /// <summary> /// 指定在消息数据块比加密操作所需的全部字节数短时应用的填充类型 /// </summary> public PaddingMode PaddingMode { get; set; } /// <summary> /// 密钥 /// </summary> public byte[] Key { get; set; } /// <summary> /// 初始化向量 /// </summary> public byte[] IV { get; set; } /// <summary> /// DES加密 /// </summary> /// <param name="bySource">要加密的源数据</param> /// </param> public byte[] DESEncrypt(byte[] bySource) { try { var MyServiceProvider = new DESCryptoServiceProvider(); //计算des加密所采用的算法 MyServiceProvider.Mode = CipherMode; //计算填充类型 MyServiceProvider.Padding = PaddingMode; var MyTransform = MyServiceProvider.CreateEncryptor(Key, IV); //CryptoStream对象的作用是将数据流连接到加密转换的流 var ms = new MemoryStream(); var MyCryptoStream = new CryptoStream(ms, MyTransform, CryptoStreamMode.Write); //将字节数组中的数据写入到加密流中 MyCryptoStream.Write(bySource, 0, bySource.Length); MyCryptoStream.FlushFinalBlock(); MyCryptoStream.Close(); var byEncRet = ms.ToArray(); ms.Close(); return byEncRet; } catch (Exception ex) { Console.WriteLine("Exception caught: {0}", ex.Message); return new byte[8]; } } /// <summary> /// DES解密 /// </summary> /// <param name="bySource">要解密的数据</param> public byte[] DESDecrypt(byte[] bySource) { try { var MyServiceProvider = new DESCryptoServiceProvider(); //计算des加密所采用的算法 MyServiceProvider.Mode = CipherMode; //计算填充类型 MyServiceProvider.Padding = PaddingMode; var MyTransform = MyServiceProvider.CreateDecryptor(Key, IV); //CryptoStream对象的作用是将数据流连接到加密转换的流 var ms = new MemoryStream(); var MyCryptoStream = new CryptoStream(ms, MyTransform, CryptoStreamMode.Write); //将字节数组中的数据写入到加密流中 MyCryptoStream.Write(bySource, 0, bySource.Length); MyCryptoStream.FlushFinalBlock(); MyCryptoStream.Close(); var byEncRet = ms.ToArray(); ms.Close(); return byEncRet; } catch (Exception ex) { Console.WriteLine("Exception caught: {0}", ex.Message); return new byte[8]; } } /// <summary> /// MAC计算所要采用的CBC DES算法实现 /// </summary> public byte[] HCDES(byte[] Key, byte[] Data) { try { //创建一个DES算法的加密类 var MyServiceProvider = new DESCryptoServiceProvider(); MyServiceProvider.Mode = CipherMode.CBC; MyServiceProvider.Padding = PaddingMode.None; //从DES算法的加密类对象的CreateEncryptor方法,创建一个加密转换接口对象 //第一个参数的含义是:对称算法的机密密钥(长度为64位,也就是8个字节) // 可以人工输入,也可以随机生成方法是:MyServiceProvider.GenerateKey(); //第二个参数的含义是:对称算法的初始化向量(长度为64位,也就是8个字节) // 可以人工输入,也可以随机生成方法是:MyServiceProvider.GenerateIV() // var MyTransform = MyServiceProvider.CreateEncryptor(Key, new byte[8]); //CryptoStream对象的作用是将数据流连接到加密转换的流 var ms = new MemoryStream(); var MyCryptoStream = new CryptoStream(ms, MyTransform, CryptoStreamMode.Write); //将字节数组中的数据写入到加密流中 MyCryptoStream.Write(Data, 0, Data.Length); //关闭加密流对象 var bEncRet = new byte[8]; // Array.Copy(ms.GetBuffer(), bEncRet, ms.Length); bEncRet = ms.ToArray(); // MyCryptoStream关闭之前ms.Length 为8, 关闭之后为16 MyCryptoStream.FlushFinalBlock(); MyCryptoStream.Close(); var bTmp = ms.ToArray(); ms.Close(); // return bEncRet; return bTmp; // } catch (Exception ex) { Console.WriteLine("HCDES Exception Caught, Exception = {0}", ex.Message); return new byte[8]; } } /// <summary> /// MAC计算 CBC /// </summary> public byte[] MAC_CBC(byte[] MacData) { try { var iGroup = 0; var bKey = Key; var bIV = IV; var bTmpBuf1 = new byte[8]; var bTmpBuf2 = new byte[8]; // init Array.Copy(bIV, bTmpBuf1, 8); if (MacData.Length%8 == 0) iGroup = MacData.Length/8; else iGroup = MacData.Length/8 + 1; var i = 0; var j = 0; for (i = 0; i < iGroup; i++) { Array.Copy(MacData, 8*i, bTmpBuf2, 0, 8); for (j = 0; j < 8; j++) bTmpBuf1[j] = (byte) (bTmpBuf1[j] ^ bTmpBuf2[j]); bTmpBuf2 = HCDES(bKey, bTmpBuf1); Array.Copy(bTmpBuf2, bTmpBuf1, 8); } return bTmpBuf2; } catch (Exception ex) { Console.WriteLine("MAC_CBC() Exception caught, exception = {0}", ex.Message); return new byte[8]; } } /// <summary> /// MAC计算 ECB /// </summary> public byte[] MAC_ECB(byte[] data) { try { // 8 字节对齐 var g = data.Length/8; if (data.Length%8 != 0) { g++; var newData = new byte[g*8]; Array.Copy(data, newData, data.Length); data = newData; } // 求异或 var buffer = new byte[8]; Array.Copy(data, 0, buffer, 0, 8); for (var i = 1; i < g; i++) for (var j = 0; j < 8; j++) buffer[j] = (byte) (buffer[j] ^ data[i*8 + j]); // 转Hex后分高低部分 var hex = buffer.Bytes2Hex(); var array = Array.ConvertAll(hex.ToCharArray(), Convert.ToByte); var hBytes = new byte[8]; var lBytes = new byte[8]; Array.Copy(array, 0, hBytes, 0, 8); Array.Copy(array, 8, lBytes, 0, 8); // 高位加密 与低位异或 再加密 var des = TripleDESEncryptOk(hBytes); for (var i = 0; i < 8; i++) { lBytes[i] = (byte) (lBytes[i] ^ des[i]); } des = TripleDESEncryptOk(lBytes); // 取Hex前8字符 var desHex = des.Bytes2Hex(); return Encoding.Default.GetBytes(desHex.Substring(0, 8)); //var desArray = Array.ConvertAll(desHex.ToCharArray(0, 8), Convert.ToByte); //return desArray.Bytes2Hex(); } catch (Exception ex) { Console.WriteLine("MAC_ECB() Exception caught, exception = {0}", ex.Message); return new byte[8]; } } public byte[] MAC_ECB_DES(byte[] data) { try { // 8 字节对齐 var g = data.Length / 8; if (data.Length % 8 != 0) { g++; var newData = new byte[g * 8]; Array.Copy(data, newData, data.Length); data = newData; } // 求异或 var buffer = new byte[8]; Array.Copy(data, 0, buffer, 0, 8); for (var i = 1; i < g; i++) for (var j = 0; j < 8; j++) buffer[j] = (byte)(buffer[j] ^ data[i * 8 + j]); return DESEncrypt(buffer); } catch (Exception ex) { Console.WriteLine("MAC_ECB() Exception caught, exception = {0}", ex.Message); return new byte[8]; } } /// <summary> /// 3DES加密 /// </summary> public byte[] TripleDESEncrypt(byte[] bySource) { try { var MyServiceProvider = new TripleDESCryptoServiceProvider(); //计算des加密所采用的算法 MyServiceProvider.Mode = CipherMode; //计算填充类型 MyServiceProvider.Padding = PaddingMode; /* MyServiceProvider.GenerateKey(); MyServiceProvider.GenerateIV(); byte[] key = MyServiceProvider.Key; byte[] iv = MyServiceProvider.IV; MyServiceProvider.IV = this.mbyIV; MyServiceProvider.Key = this.mbyKey; ICryptoTransform MyTransform = MyServiceProvider.CreateEncryptor();*/ //TripleDESCryptoServiceProvider //支持从 128 位到 192 位(以 64 位递增)的密钥长度 //IV需要8个字节 //设置KEY时要注意的是可能引发CryptographicException异常,主要是因为所设置的KEY为WeakKey var MyTransform = MyServiceProvider.CreateEncryptor(Key, IV); //CryptoStream对象的作用是将数据流连接到加密转换的流 var ms = new MemoryStream(); var MyCryptoStream = new CryptoStream(ms, MyTransform, CryptoStreamMode.Write); //将字节数组中的数据写入到加密流中 MyCryptoStream.Write(bySource, 0, bySource.Length); MyCryptoStream.FlushFinalBlock(); MyCryptoStream.Close(); var byEncRet = ms.ToArray(); ms.Close(); return byEncRet; } catch (Exception ex) { Console.WriteLine("Exception caught: {0}", ex.Message); return new byte[8]; } } /// <summary> /// 3DES解密 /// </summary> public byte[] TripleDESDecrypt(byte[] bySource) { try { //var MyServiceProvider = new TripleDESCryptoServiceProvider(); ////计算des加密所采用的算法 //MyServiceProvider.Mode = mCipherMode; ////计算填充类型 //MyServiceProvider.Padding = mPaddingMode; //支持从 128 位到 192 位(以 64 位递增)的密钥长度 //IV需要8个字节 //设置KEY时要注意的是可能引发CryptographicException异常,主要是因为所设置的KEY为WeakKey var MyTransform = ReflectorCreate(Key, CipherMode, IV); //MyServiceProvider.CreateDecryptor(mbyKey, mbyIV); //CryptoStream对象的作用是将数据流连接到加密转换的流 var ms = new MemoryStream(); var MyCryptoStream = new CryptoStream(ms, MyTransform, CryptoStreamMode.Write); //将字节数组中的数据写入到加密流中 MyCryptoStream.Write(bySource, 0, bySource.Length); MyCryptoStream.FlushFinalBlock(); MyCryptoStream.Close(); var byEncRet = ms.ToArray(); ms.Close(); return byEncRet; } catch (Exception ex) { Console.WriteLine("Exception caught: {0}", ex.Message); return new byte[8]; } } private ICryptoTransform ReflectorCreate(byte[] rgbKey, CipherMode mode, byte[] rgbIV, int feedbackSize = 8) { var type = typeof (TripleDESCryptoServiceProvider); var myServiceProvider = new TripleDESCryptoServiceProvider(); var methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); var med = methods.FirstOrDefault(p => p.Name == "_NewEncryptor"); return (ICryptoTransform) med?.Invoke(myServiceProvider, new object[] {rgbKey, CipherMode, IV, feedbackSize, 1}); } public byte[] CalcDesMac(byte[] data) { var des = new TripleDESCryptoServiceProvider(); //des.Key = Key; var fi = des.GetType().GetField("KeyValue", BindingFlags.Instance | BindingFlags.NonPublic); fi.SetValue(des, Key); fi = des.GetType().GetField("KeySizeValue", BindingFlags.Instance | BindingFlags.NonPublic); fi.SetValue(des, Key.Length*8); des.IV = new byte[8]; des.Padding = PaddingMode; des.Mode = CipherMode; var ms = new MemoryStream(); using (var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); } var encryption = ms.ToArray(); var mac = new byte[8]; Array.Copy(encryption, encryption.Length - 8, mac, 0, 8); //PrintByteArray(encryption); return mac; } public byte[] TripleDESDecryptOk(byte[] str) { var des = new TripleDESCryptoServiceProvider(); des.Padding = PaddingMode; des.Mode = CipherMode; var t = Type.GetType("System.Security.Cryptography.CryptoAPITransformMode"); var obj = t.GetField("Decrypt", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).GetValue(t); var mi = des.GetType().GetMethod("_NewEncryptor", BindingFlags.Instance | BindingFlags.NonPublic); var desCrypt = (ICryptoTransform) mi.Invoke(des, new[] {Key, CipherMode.ECB, null, 0, obj}); var result = desCrypt.TransformFinalBlock(str, 0, str.Length); return result; } public byte[] TripleDESEncryptOk(byte[] str) { var des = new TripleDESCryptoServiceProvider { Padding = PaddingMode, Mode = CipherMode }; var t = Type.GetType("System.Security.Cryptography.CryptoAPITransformMode"); var obj = t.GetField("Encrypt", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).GetValue(t); var mi = des.GetType().GetMethod("_NewEncryptor", BindingFlags.Instance | BindingFlags.NonPublic); var desCrypt = (ICryptoTransform) mi.Invoke(des, new[] {Key, CipherMode.ECB, IV, 0, obj }); // System.Security.Cryptography.CryptoAPITransformMode var result = desCrypt.TransformFinalBlock(str, 0, str.Length); return result; } } }
C
UTF-8
1,141
3.015625
3
[ "MIT" ]
permissive
#include<stdio.h> #include<stdlib.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<strings.h> #include<errno.h> #include<unistd.h> #include<arpa/inet.h> #define MAX 1024 void main(int argc, char **argv) { int soc; struct sockaddr_in remote_server; int len = sizeof(struct sockaddr_in); char output[MAX];; char input[MAX]; int data_len; if((soc = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("client socket:"); exit(-1); } remote_server.sin_family = AF_INET; remote_server.sin_port = htons(atoi(argv[2])); remote_server.sin_addr.s_addr = inet_addr(argv[1]); bzero(&remote_server.sin_zero,8); if((connect(soc,(struct sockaddr*)&remote_server,len)) < 0) { perror("client connect:"); exit(-1); } printf("connected to %s: %d \n", inet_ntoa(remote_server.sin_addr),ntohs(remote_server.sin_port)); while(1) { fgets(input, MAX, stdin); send(soc, input,strlen(input),0); printf("client message sent: %s\n", input); data_len = recv(soc, output,MAX, 0); output[data_len] = '\0'; printf("server message received: %s \n", output); } close(soc); }
C#
UTF-8
603
3.609375
4
[]
no_license
using System; class BonusScore { static void Main(string[] args) { Console.Write("Enter number [0...9] = "); int num = int.Parse(Console.ReadLine()); if (num>=1 && num<=3) { Console.WriteLine("result = {0}",num*10); } else if (num>=4 && num<=6) { Console.WriteLine("result = {0}",num*100); } else if (num >= 7 && num <= 9) { Console.WriteLine("result = {0}", num * 1000); } else { Console.WriteLine("invalid score!!!"); } } }
C++
UTF-8
701
3.015625
3
[]
no_license
/// /// @file namespace3.cc /// @author lemon(haohb13@gmail.com) /// @date 2016-10-17 11:50:42 /// #include <stdio.h> #include <stdlib.h> //#include <cstdio> //#include <cstdlib> #include <iostream> using std::cout; using std::endl; //之前C的标准头文件出现的实体都是在匿名的名称空间的 int num = 10; namespace A { int num = 100; } namespace B { int num = 1000; void display() { int num = 5; cout << "display::num = " << num << endl;//发生了屏蔽 cout << "B::num = " << B::num << endl; cout << "A::num = " << A::num << endl; cout << "全局名称空间中的num = " << ::num << endl;//匿名的名称空间 } } int main(void) { B::display(); return 0; }
Java
UTF-8
1,646
3.65625
4
[]
no_license
package com.javarush.test.level04.lesson16.home02; import java.io.*; /* Среднее такое среднее Ввести с клавиатуры три числа, вывести на экран среднее из них. Т.е. не самое большое и не самое маленькое. */ public class Solution { public static void main(String[] args) throws Exception { //напишите тут ваш код BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N1 = Integer.parseInt(br.readLine()); int N2 = Integer.parseInt(br.readLine()); int N3 = Integer.parseInt(br.readLine()); int MAX_N = max(N1, N2, N3); int MIN_N = min(N1, N2, N3); int[] N = new int[3]; N[0] = N1; N[1] = N2; N[2] = N3; for (int i = 0; i < 3 ; i++) { if (N[i]!=MAX_N&&N[i]!=MIN_N) System.out.println(N[i]); } } public static int max(int a, int b, int c) { int[] N = new int[3]; N[0] = a; N[1] = b; N[2] = c; int max_n = N[0]; for (int i = 0; i < 3; i++) if (N[i] > max_n) max_n = N[i]; // System.out.println("MAX_N = "+ max_n); return max_n; } public static int min(int a, int b, int c) { int[] N = new int[3]; N[0] = a; N[1] = b; N[2] = c; int min_n = N[0]; for (int i = 0; i < 3; i++) if (N[i] < min_n) min_n = N[i]; // System.out.println("MIN_N = " + min_n); return min_n; } }
Java
UTF-8
1,541
2.296875
2
[]
no_license
package com.miles.wechat.message.model; import javax.xml.bind.annotation.XmlElement; /** * 消息的基类 * * @author miles */ public abstract class AbstractMessage { /** * 消息接收人 */ private String toUserName; /** * 消息发送人 */ private String fromUserName; /** * 消息的发送时间 */ private long createTime; /** * 消息类型 */ private String messageType; /** * 消息ID */ private String messageId; @XmlElement(name = "ToUserName") public String getToUserName() { return toUserName; } public void setToUserName(String toUserName) { this.toUserName = toUserName; } @XmlElement(name = "FromUserName") public String getFromUserName() { return fromUserName; } public void setFromUserName(String fromUserName) { this.fromUserName = fromUserName; } @XmlElement(name = "CreateTime") public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } @XmlElement(name = "MsgType") public String getMessageType() { return messageType; } public void setMessageType(String messageType) { this.messageType = messageType; } @XmlElement(name = "MsgId") public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } }
Java
UTF-8
1,076
3.109375
3
[]
no_license
package com.onikiychuk.xmexersize; import java.util.stream.Stream; /** * Represents Knight figure. */ class KnightFigure { /** * Provide list of valid board positions that knight figure can move from current position. * * @param position current figure position. If there is no available moves - returns empty array. Never returns null. * @return list of valid ({@link BoardPosition#isValid()}) position that figure able to moves from current position. */ BoardPosition[] availableMoves(BoardPosition position) { return Stream.of( position.moveLeft(2).moveUp(1), position.moveLeft(2).moveDown(1), position.moveRight(2).moveUp(1), position.moveRight(2).moveDown(1), position.moveUp(2).moveLeft(1), position.moveUp(2).moveRight(1), position.moveDown(2).moveLeft(1), position.moveDown(2).moveRight(1)). filter(BoardPosition::isValid). toArray(BoardPosition[]::new); } }
Markdown
UTF-8
2,153
3.203125
3
[]
no_license
# Chapter 1 1. Pascal, BASIC, and C are p_____ languages, while C++ is an o_____ language. 2. A widget is to the blueprint for a widget as an object is to. - a member function - a class - an operator - data item 3. The two major components of an object are ____ and functions that ______ 4. In C++, a function contaioned within a class is called - a member function - an operator - a class function - a method 5. Protecting data from access by unauthorized functions is called _____ 6. which of the following are good reasons to use an object-oriented language? - You can define your own data typed - Program statements are simpler than in procedural languages - An OO program can be taught to correct its own error - It's easier to conceptualize an OO program 7. __ model entities in the real world more closely than do functions 8. True or False: A C++ program is similar to a C program except for the details of coding 9. Bundling data and functions together is called ____ 10. When a language has the capability to produce new data types, it is said to be - reprehensible - encapsulated - overloaded - extensible 11. True or false: You can easily tell, from any two lines of code, whether a program is written in C or C++ 12. The ability of a function or operator to act in different ways on different data is called ____ 13. A normal C++ operator that acts in special ways on newly defined data types is said to be - glorified - encapsulated - classified - overload 14. Memorizing the new terms used in C++ is - critically important - something you can return to later - the key to wealth and success - completely irrelvant 15. The Unified Modeling Language is - a program that builds physical models - a way to look at the organization of a program - the combination of C++ and FORTRAN - helpful in developing software systems ## Answer Key 1. Procedural, Obect-Oriented 2. b 3. data act on that data 4. a 5. data hiding 6. a, d 7. objects 8. false 9. encapsulation 10. d 11. false 12. polymorphism 13. d 14. b 15. b, d
JavaScript
UTF-8
7,670
3.046875
3
[]
no_license
//Given a ray described by an initial point P0 and a direction V both in world coordinates, check to see //if it intersects the polygon described by "vertices," an array of vec3 values describing the location of //the polygon vertices in its child frame. //mvMatrix is a matrix describing how to transform "vertices" into world coordinates which you will have to //do to get the correct intersection in world coordinates. //Be sure to compute the plane normal only after you have transformed the points, //and be sure to only compute intersections which are inside of the polygon //(you can assume that all polygons are convex and use the area method) function rayIntersectPolygon(P0, V, vertices, mvMatrix) { //TODO: Fill this in //Step 1: Make a new array of vec3s which holds "vertices" transformed to world //coordinates (hint: vec3 has a function "transformMat4" which is useful) //Step 2: Compute the plane normal of the plane spanned by the transformed vertices //Step 3: Perform ray intersect plane //Step 4: Check to see if the intersection point is inside of the transformed //polygon. You can assume that the polygon is convex. If you use the area test, //you can allow for some wiggle room in the two areas you're comparing (e.g. //absolute difference not exceeding 1e-4) //Step 5: Return the intersection point if it exists or null if it's outside //of the polygon or if the ray is perpendicular to the plane normal //(no intersection) return {t:1e9, P:vec3.fromValues(0, 0, 0)}; //These are dummy values //you should return both an intersection point and a parameter t. The parameter t will be used to sort //intersections in order of occurrence to figure out which one happened first } function addImageSourcesFunctions(scene) { //Setup all of the functions that operate directly on the scene //Purpose: A recursive function provided which helps to compute intersections of rays with all faces in //the scene, taking into consideration the scene graph structure //Inputs: P0 (vec3): Ray starting point; V (vec3): ray direction; node (object): node in scene tree to process; //mvMatrix (mat4): Matrix to put geometry in this node into world coordinates //excludeFace: Pointer to face object to be excluded (don't intersect with the face that this point lies on) //Returns: null if no intersection, {tmin:minimum t along ray, PMin(vec3): corresponding point, faceMin:Pointer to mesh face hit first} //NOTE: Calling this function with node = scene and an identity matrix for mvMatrix //will start the recursion at the top of the scene tree in world coordinates //**PROVIDED** scene.rayIntersectFaces = function(P0, V, node, mvMatrix, excludeFace) { var tmin = Infinity; //The parameter along the ray of the nearest intersection var PMin = null; //The point of intersection corresponding to the nearest interesection var faceMin = null;//The face object corresponding to the nearest intersection if (node === null) { return null; } if ('mesh' in node) { //Make sure it's not just a dummy transformation node var mesh = node.mesh; for (var f = 0; f < mesh.faces.length; f++) { if (mesh.faces[f] == excludeFace) { continue; //Don't re-intersect with the face this point lies on } //Intersect the ray with this polygon var res = rayIntersectPolygon(P0, V, mesh.faces[f].getVerticesPos(), mvMatrix); if (!(res === null) && (res.t < tmin)) { tmin = res.t; PMin = res.P; faceMin = mesh.faces[f]; } } } if ('children' in node) { //Recursively check the meshes of the children to make sure the ray doesn't intersect any of them first for (var i = 0; i < node.children.length; i++) { var nextmvMatrix = mat4.create(); //Multiply on the right by the next transformation of the childnode mat4.mul(nextmvMatrix, mvMatrix, node.children[i].transform); //Recursively intersect with the child node var cres = scene.rayIntersectFaces(P0, V, node.children[i], nextmvMatrix, excludeFace); if (!(cres === null) && (cres.tmin < tmin)) { tmin = cres.tmin; PMin = cres.PMin; faceMin = cres.faceMin; } } } if (PMin === null) { return null; } return {tmin:tmin, PMin:PMin, faceMin:faceMin}; } //Purpose: Fill in the array scene.imsources[] with a bunch of source objects //Inputs: order (int) : The maximum number of bounces to take //**IMAGE SOURCE GENERATION** scene.computeImageSources = function(order) { scene.source.order = 0; //Store an order field to figure out how many bounces a particular image represents scene.source.rcoeff = 1.0; //Keep track of the reflection coefficient of the node that gave rise to this source scene.source.parent = null; //Keep track of the image source's parent scene.source.genFace = null; //Keep track of the mesh face that generated this image scene.imsources = [scene.source]; //TODO: Fill the rest of this in //FOR DEBUGGING PURPOSES //Display all image sources to the console //# virtual images: N(N-1)^(r-1) where N = number of faces in a scene and r is the order for (var a = 0; a < scene.imsources.length; a++) { console.log(scene.imsources[a].pos); } } //Purpose: Based on the extracted image sources, trace back paths from the //receiver to the source, checking to make sure there are no occlusions //along the way. Remember, you're always starting by tracing a path from //the receiver to the image, and then from the intersection point with //that image's corresponding face to the image's parent, and so on //all the way until you get back to the original source. //Fill in the array scene.paths, where each element of the array is itself //an array of objects describing vertices along the path, starting //with the receiver and ending with the source. Each object in each path //array should contain a field "pos" which describes the position, as well //as an element "rcoeff" which stores the reflection coefficient at that //part of the path, which will be used to compute decays in "computeInpulseResponse()" //Don't forget the direct path from source to receiver! scene.extractPaths = function() { scene.paths = []; //TODO: Finish this. Extract the rest of the paths by backtracing from //the image sources you calculated. Return an array of arrays in //scene.paths. Recursion is highly recommended //Each path should start at the receiver and end at the source //(or vice versa), so scene.receiver should be the first element //and scene.source should be the last element of every array in //scene.paths } //Inputs: Fs: Sampling rate (samples per second) scene.computeImpulseResponse = function(Fs) { var SVel = 340; //Sound travels at 340 meters/second //TODO: Finish this. Be sure to scale each bounce by 1/(1+r^p), //where r is the length of the line segment of that bounce in meters //and p is some integer less than 1 (make it smaller if you want the //paths to attenuate less and to be more echo-y as they propagate) //Also be sure to scale by the reflection coefficient of each material //bounce (you should have stored this in extractPaths() if you followed //those directions). Use some form of interpolation to spread an impulse //which doesn't fall directly in a bin to nearby bins //Save the result into the array scene.impulseResp[] } }
PHP
UTF-8
907
3.484375
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Krt</title> </head> <body> <?php $prices = array('tires'=> 100, 'oil'=> 10, 'spark plugs'=> 4); echo "<p>using foreacho statement...</p>"; foreach($prices as $key => $value){ echo $key." - ".$value; echo "<br/>"; } echo"<hr> <p>using while statement...</p>"; #using while while (list($product, $price) = each($prices)){ echo $product." - ".$price."<br/>"; } echo"<hr> <p>after Asorting... asort(prices)</p>"; asort($prices); foreach($prices as $key => $value){ echo $key." - ".$value; echo "<br/>"; } echo"<hr> <p>after Ksorting... ksort(prices)</p>"; ksort($prices); foreach($prices as $key => $value){ echo $key." - ".$value; echo "<br/>"; } ?> </body> </html>
Python
UTF-8
556
4.0625
4
[]
no_license
user_dictionary = {} while 1: command = input("'a' to add word, 'l' to lookup a word, 'q' to quit ") if command == "a": word = input("Type the word: ") definition = input("Type the definition: ") user_dictionary[word] = definition print("Word added!") elif command == "l": word = input("Type the word: ") if word in user_dictionary.keys(): print(user_dictionary[word]) else: print("That word isn't in the dictionary yet.") elif command == 'q': break
Shell
UTF-8
7,102
3.578125
4
[]
no_license
#!/usr/bin/env bash set -e shopt -s extglob # makePlots.sh: make plots in a directory of scheme comparison stats output. OUTFILE="precision.tsv" truncate -s 0 ${OUTFILE} for FILE in `ls truth.*` do # Grab the scheme SCHEME=${FILE##*.} cat ${FILE} | cut -f 1 | while read LINE do # Tag each entry with its scheme printf "${SCHEME}\t${LINE}\n" >> ${OUTFILE} done done boxplot.py precision.tsv --x_label "Merging Scheme" --y_label "Precision" --title "Precision vs. Merging Scheme" --x_sideways --save precisionVsScheme.png OUTFILE="recall.tsv" truncate -s 0 ${OUTFILE} for FILE in `ls truth.*` do # Grab the scheme SCHEME=${FILE##*.} cat ${FILE} | cut -f 2 | while read LINE do # Tag each entry with its scheme printf "${SCHEME}\t${LINE}\n" >> ${OUTFILE} done done boxplot.py recall.tsv --x_label "Merging Scheme" --y_label "Recall" --title "Recall vs. Merging Scheme" --x_sideways --save recallVsScheme.png OUTFILE="coverages.tsv" truncate -s 0 ${OUTFILE} for FILE in `ls coverage.*` do # Grab the scheme SCHEME=${FILE##*.} cat ${FILE} | cut -f 2 | while read LINE do # Tag each entry with its scheme printf "${SCHEME}\t${LINE}\n" >> ${OUTFILE} done done boxplot.py coverages.tsv --x_label "Merging Scheme" --y_label "Portion Aligned to Reference" --title "Coverage vs. Merging Scheme" --x_sideways --save coverageVsScheme.png mkdir -p spectrums for SPECTRUM in spectrum.* do # Grab the extension. See <http://unix.stackexchange.com/a/1574/44348> SCHEME=${SPECTRUM##*.} # Work out the total tandem count TANDEM_COUNT=$(sum.sh < tandem.${SCHEME}) # Plot the histogram indication the tandem dupes histogram.py --min 0 --max 40 --bins 40 --logCounts ${SPECTRUM} --save spectrums/${SCHEME}.spectrum.png --x_label "Adjacency Component Size" --y_label "Occurrences" --title "${SCHEME} Component Spectrum" --label --redWeight 0 --redWeight 0 --redWeight 0 --redWeight 0 --redWeight ${TANDEM_COUNT} done OUTFILE="indelLengths.tsv" truncate -s 0 ${OUTFILE} for FILE in `ls indels.*` do # Grab the scheme SCHEME=${FILE##*.} cat ${FILE} | while read LINE do # Tag each entry with its scheme printf "${SCHEME}\t${LINE}\n" done >> ${OUTFILE} done barchart.py ${OUTFILE} --x_label "Merging Scheme" --y_label "Mean Indel Length" --title "Mean Length vs. Merging Scheme" --x_sideways --save meanIndels.png OUTFILE="tandemDupes.tsv" truncate -s 0 ${OUTFILE} for FILE in `ls tandem.*` do # Grab the scheme SCHEME=${FILE##*.} cat ${FILE} | while read LINE do # Tag each entry with its scheme printf "${SCHEME}\t${LINE}\n" >> ${OUTFILE} done done boxplot.py ${OUTFILE} --x_label "Merging Scheme" --y_label "Tandem Duplication Count" --title "Tandem Duplications vs. Merging Scheme" --x_sideways --save tandemsVsScheme.png OUTFILE="precisionRecall.tsv" truncate -s 0 ${OUTFILE} for FILE in `ls truth.*` do # Grab the scheme SCHEME=${FILE##*.} # Type is the scheme name without the numbers (with ps in them) SCHEME_TYPE=$(echo ${SCHEME} | sed 's/[0-9]\(p\)\?//g') # We want totals TOTAL_PRECISION=0 TOTAL_RECALL=0 LINE_COUNT=0 while read LINE || [[ -n $LINE ]] do # Split on spaces PARTS=(${LINE}) # Add in everything. Float math needs the bc tool. TOTAL_PRECISION=$(echo ${TOTAL_PRECISION} + ${PARTS[0]} | bc -l) TOTAL_RECALL=$(echo ${TOTAL_RECALL} + ${PARTS[1]} | bc -l) LINE_COUNT=$((${LINE_COUNT} + 1)) #echo "At line ${LINE_COUNT} totals ${TOTAL_PRECISION}, ${TOTAL_RECALL}" done < ${FILE} # Calculate averages. We seem to get integer division unless we pass -l? MEAN_PRECISION=$(echo ${TOTAL_PRECISION} / ${LINE_COUNT} | bc -l) MEAN_RECALL=$(echo ${TOTAL_RECALL} / ${LINE_COUNT} | bc -l) #echo "Means ${MEAN_PRECISION}, ${MEAN_RECALL}" # Write a mean precision/recall point for this type of scheme. We'll get one # per parameter value. printf "${SCHEME_TYPE}\t${MEAN_PRECISION}\t${MEAN_RECALL}\n" >> ${OUTFILE} done scatter.py ${OUTFILE} --x_label "Precision" --y_label "Recall" --title "Recall vs. Precision by Scheme" --save recallVsPrecision.png --max_x 1 --max_y 1 # Go get the size-4 adjacency components from the spectrums, and the tandem # dupe counts, and see what portion of size-4 adjacency components are tandem # dupes per scheme. OUTFILE="tandemPortion.tsv" truncate -s 0 ${OUTFILE} for FILE in `ls tandem.*` do # Grab the scheme SCHEME=${FILE##*.} # Make the spectrum filename SPECTRUM_FILE="spectrum.${SCHEME}" # Sum up the tandem duplications TOTAL_TANDEMS=0 while read LINE || [[ -n $LINE ]] do TOTAL_TANDEMS=$((${TOTAL_TANDEMS} + ${LINE})) done < ${FILE} # Sum up the 4-part rearrangements TOTAL_4PART=0 while read LINE || [[ -n $LINE ]] do # Split on spaces PARTS=(${LINE}) if [[ ${PARTS[0]} -eq 4 ]] then TOTAL_4PART=$((${TOTAL_4PART} + ${PARTS[1]})) fi done < ${SPECTRUM_FILE} # Work out the fraction of 4-part rearrangements (i.e. 2-break operations) # that are tandem duplications by our count. Will miss tandems with any # differences, or any other things aligned. FRACTION=$(echo ${TOTAL_TANDEMS} / ${TOTAL_4PART} | bc -l) printf "${SCHEME}\t${FRACTION}\n" >> ${OUTFILE} echo "Scheme ${SCHEME} is ${TOTAL_TANDEMS} / ${TOTAL_4PART} = ${FRACTION} tandems" done barchart.py ${OUTFILE} --x_label "Merging Scheme" --y_label "2-break tandem portion" --max 1 --title "Portion Tandem Dupes vs. Merging Scheme" --x_sideways --save tandemPortion.png # Make a boxplot of alignment mappings by scheme for each category, to display # the result of classifying mappings according to what they say about genes. # Still not sure exactly what the right way to display this is. rm -Rf checkgenes/ mkdir checkgenes/ for FILE in `ls checkgenes.*` do # Sort things out by category # Grab the scheme SCHEME=${FILE##*.} while read LINE || [[ -n $LINE ]] do # Split on spaces PARTS=(${LINE}) # Parse out the category and count for each line CATEGORY="${PARTS[0]}" COUNT="${PARTS[1]}" # Save the count and scheme name to the file for the category printf "${SCHEME}\t${COUNT}\n" >> checkgenes/${CATEGORY}.tsv done < ${FILE} done for FILE in `ls checkgenes/*.tsv` do # Now make the actual charts # Pull out the filename without directory FILENAME="${FILE##*/}" # And the category name from that CATEGORY="${FILENAME%.*}" boxplot.py ${FILE} --x_label "Scheme" --x_sideways --y_label "Count" --title "Occurrences of ${CATEGORY} mappings" --save checkgenes/${CATEGORY}.checkgenes.png done
Python
UTF-8
94
2.953125
3
[]
no_license
def main(): for i in range(0,5): print("Hello") if __name__=='__main__': main()
Python
UTF-8
1,203
3.109375
3
[]
no_license
#python2 operaciones.py import numpy as np from math import * import cv2 def negative(value): return 255-value def logarithmic(value): const=255/np.log2(1+255) return const*np.log2(1+value) def logarithmic_inverse(value): const=255*np.log2(256) return const*(1/np.log2(1+value)) def power(value,gamma=0.5): c=1 return c*pow(value,gamma)*255/(c*pow(255,gamma)) image=cv2.imread('woman.jpg',0) #rows,cols,channels=image.shape rows,cols=image.shape #new_image=np.zeros((rows,cols,channels),np.uint8) image_negative=np.zeros((rows,cols),np.uint8) image_log=np.zeros((rows,cols),np.uint8) image_power=np.zeros((rows,cols),np.uint8) image_inverse=np.zeros((rows,cols),np.uint8) for i in range(0,rows): for j in range(0,cols): image_negative[i][j]=negative(image[i][j]) image_log[i][j]=logarithmic(image[i][j]) image_power[i][j]=power(image[i][j]) image_inverse[i][j]=logarithmic_inverse(image[i][j]) cv2.imshow('Imagen original',image) cv2.imshow('Negative',image_negative) cv2.imshow('Logarithmic',image_log) cv2.imshow('Power',image_power) cv2.imshow('Log Inverse',image_inverse) cv2.waitKey(0) cv2.destroyAllWindows()
Python
UTF-8
4,067
3.046875
3
[]
no_license
import pandas as pd import nltk as nltk #from nltk import RegexpTokenizer #from nltk import TweetTokenizer from nltk import tokenize import os import numpy as np import re import string from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from nltk.stem import WordNetLemmatizer #from stanfordcorenlp import StanfordCoreNLP def count_all_caps_words(text): # Returns frequency of all caps words, not COUNT, as the function name says # Observation: technical ham emails can have a lot of acronyms. Also, some HTML makes things caps, but this can't detect it. return sum(token.isupper() for token in text) / len(text) def find_avg_word_length(text): # Assumes input text is tokenized, and a list # Sum is implemented in C, and fast return sum(len(token) for token in text) / len(text) def count_numbered_lists(text): # Runs on raw text count = 0 # Matches "1." and "1)" type numbering matches = re.findall(r'(?:\d+(?:\.|\))\s.*\n?)+', text) #returns a list of strings for match in matches: if match[0] == "1": count += 1 #print(match) return count <<<<<<< HEAD def extract_features(path): """ The main function which reads all training data, and extracts all features, then writes them (in matrix form) to an output file. To use, make sure to pass it the path of the directory containing the text files. Of course, the path is relative to the location of this file. It currently cannot navigate into subdirectories, so you may need to call several times for several folders. """ #nlp = StanfordCoreNLP(r'\stanford-english-corenlp-2017-06-09-models') #tknzr = TweetTokenizer(reduce_len=False) lmtzr = WordNetLemmatizer() stop_words = set(stopwords.words('english')) count = 0 for filename in os.listdir(path): file = open(path + "/" + filename, "r") email_content = "" email_subject = "" for line in file: m = re.search('^Subject:', line) if m: m_span = m.span() email_subject = line[m_span[1] + 1: -1] # We assume that a line break denotes where the email begins if line == "\n": email_content = file.read() break content_tknzd = tokenize.word_tokenize(email_content) subject_tknzd = tokenize.word_tokenize(email_subject) #content_depunct = list(filter(lambda token: token not in string.punctuation, content_tknzd)) print(content_tknzd) # De-punkt, stopwords removed, alphabetical words only content_cleaned = list(filter(lambda token: token not in stop_words, content_tknzd)) #content_cleaned = [token for token in content_cleaned if token.isalpha()] content_cleaned = [token for token in content_cleaned if token.isalpha() or token in string.punctuation] print(string.punctuation) content_cleaned_lower = [token.lower() for token in content_cleaned] content_cleaned_lemmatized = [lmtzr.lemmatize(token) for token in content_cleaned_lower] print(">>>>>>>>>>>>>>>>>>>>>", filename, ">>>>>>>>>>>>>>>>>>>>") #print(content_cleaned_lemmatized) write_string = " ".join(content_cleaned_lemmatized) # Call your helper functions here! Use the raw, depunct, or cleaned content/subject. # avg_word_len = find_avg_word_length(content_cleaned_lower) # freq_all_caps_words = count_all_caps_words(content_cleaned) # num_numbered_lists = count_numbered_lists(email_content) # print(avg_word_len) # print(freq_all_caps_words) # print(num_numbered_lists) file.close() write_file = open("easy_ham_" + str(count) + ".txt", "w") write_file.write(write_string) count += 1 # Do we need to consider case where email_content is empty? # TO DO: return features in matrix form, write this to a file return None def main(): # Make sure you fill in the correct path path = 'Data/test' features = extract_features(path) #count_all_caps_words("The following words are ALL CAPS FOREVER. The following word is in CAPS. 4DOT CATS 9 LIVE") if __name__ == '__main__': main() ======= >>>>>>> 10cabc49a91f630d1e0ee2c920faf7451c35d181
Swift
UTF-8
535
3.484375
3
[]
no_license
import SwiftUI enum PrimaryColor { case red case yellow case blue func color() -> Color { switch self { case .red: return Color.red case .yellow: return Color.yellow case .blue: return Color.blue } } func circle() -> some View { Circle() .foregroundColor(color()) } } Circle().foregroundColor(.red) let crayon = PrimaryColor.blue crayon.color() let paintBrush = PrimaryColor.red paintBrush.color()
Markdown
UTF-8
5,928
3.125
3
[]
no_license
--- title: "My favorite Yoga Studios in Berlin" description: "Looking for a great yoga studio in Berlin? These are my favorite yoga studios - great classes, awesome teacher, and relaxing atmosphere." date: "2018-02-09T13:50:46.234Z" categories: ["Fitness"] keywords: ["yoga studios Berlin"] hashtags: ["#fitness"] banner: "./images/chimosa_yoga.jpg" author: "" contribute: "" --- Yoga is booming in Berlin and there are opening up studios everywhere. Also, it feels like every second person I meet here either is a yoga teacher or is on the verge of becoming one. This is great but sometimes a wide choice makes it hard to find what you like most and to really stick to it. I have visited countless yoga classes in Berlin and have seen so many studios. In the end, I have fallen in love with three yoga studios that offer amazing classes, have a great atmosphere and super nice teachers. # Chimosa: For a powerful Practice ![yoga at Chimosa](./images/chimosa_yoga.jpg) [Chimosa](https://www.chimosa.de) is a fascinating studio to me, as they don’t only offer yoga classes, but also boxing classes. At first, it might sound a bit odd as martial art and yoga sound so far away from each other. Chimosa however, combines these opposites in the most perfect way. Calmness and movement, asian and western culture, tradition and modern age seem to merge into one here as you can see for example in their [Boxingyoga](https://www.21moves.com/boxing-yoga-the-new-yoga-trend/) classes. If you haven’t heard of that, it’s time to check it out. It is so much fun. The name Chimosa derives from the home countries of the studio’s founders: Chi for China and Mosa for Taiwan. Mental and physical well-being go hand in hand in these countries. Chimosa wants to take up on that and offers its own interpretation of the traditional lifestyle and translates it into a more modern way. When visiting Chimosa, I especially love their Power Yoga classes. They really make you sweat. The sequences are always challenging and never boring. The focus is never solely on the exercise. Mind and body form a unit here that’s why there is always great emphasis on the breathing and flowing as well. ![inside of Chimosa yoga studio](./images/chimosa_indoor.jpg) Apart from Power Yoga, Chimosa also offers Akro Yoga, Gentle Yoga, Yoga for beginners and Masterclass Yoga for very ambitious Yogis and teachers. Classes are either in German or in English. Depending on the class you take, they are either an hour or 1.5 hours long. I really like to go during lunch time. After that I feel fit to conquer the rest of my working day. The studio itself is conveniently located in Berlin Mitte. The yoga room is bright and friendly and equipped with everything you need for a strong practice. It is not very big but they never let it get over-crowded. The changing room comes with two open showers and rooms are seperated for boys and girls. # Yogatribe: For a strong Flow [Yogatribe](http://www.yogatribe.de) is Berlin’s Anusara studio. If you don’t know what anusara is: it is a modern-day Hatha Yoga practice, founded by John Friend. With more than 40 yoga classes each week, everybody can find time for their yoga practice here. The classes are aligned with the yogis level of knowledge. Thus, you can find constructive beginners classes, powerful morning classes, relaxing lunch classes and restorative evening classes. There are also great events and workshops with international guest teachers on a regular basis. ![yoga room with mat at yogatribe](./images/yogatribe_room.jpg) When I go to Yogatribe, I usually like to go to the morning classes. It’s really beautiful how they are sequenced: From a more calm and meditative beginning to a strong and playful practice with a very nice flow. Afterward, I always feel very refreshed and ready to take on the challenges of the day. ![decoration at yogatribe](./images/yogatribe_deco.jpg) The studio is in the perfect location in Berlin Mitte amongst nice coffee and food places. The two rooms to practice are bright and big with a very cozy atmosphere. Of course, you’ll also find all the yoga props that you need for your practice. The changing rooms come with one shower and racks to leave your stuff. Classes are mostly in German with just two classes in English. However, whenever someone doesn’t speak German, the teachers try to also explain things in English a bit. And besides, yoga is pretty universal after all. With drop in prices of 17 Euros, Yogatribe isn’t cheap, but it is definitely worth it. # Spirit Yoga: For a Practice that connects Body and Mind [Spirit Yoga](http://spirityoga.de/) likes the play with the opposite. Here you can practice to build up strength and to let go at the same time as well as to get energized while also relax your body. Breathing, body consciousness and mindfulness are the pillars of the practice. ![inside yoga studio spirit yoga](./images/spirityoga.jpg) Spirit Yoga has three studios in Berlin: one in Mitte, one in Charlottenburg and one in Zehlendorf. As the one in Mitte is the most convenient for me, that’s the only one I tried out. I went there during my lunch break and was really excited about the practice. It was very dynamic, powerful yet very mindful. The teacher put great emphasis on listening to your body while practicing. That way, you know how far you can go and what your body needs at this exact moment. After the practice, Spirit Yoga offered fruits and delicious tea to nourish your body. That was a really nice opportunity to talk to other yogis. ![yoga class room at Spirit Yoga](./images/spirityoga_room.jpg) The studio in Berlin Mitte is really beautiful with a big room to practice that is very cosy due to a lot of wooden elements. It is very bright and equipped with everything you need for your practice. The yoga classes are usually in German and cost 22 Euro for a drop in class.
Java
UTF-8
2,124
2.359375
2
[]
no_license
package com.dicoding.picodiploma.themoviedb.data.source.local; import android.app.Application; import androidx.lifecycle.LiveData; import androidx.paging.DataSource; import com.dicoding.picodiploma.themoviedb.data.source.local.entity.model.MovieEntity; import com.dicoding.picodiploma.themoviedb.data.source.local.entity.model.TvShowEntity; import com.dicoding.picodiploma.themoviedb.data.source.local.room.CatalogueDao; import com.dicoding.picodiploma.themoviedb.data.source.local.room.CatalogueDatabase; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; // Dipanggil ke sini public class LocalRepository { private CatalogueDao mCatalogueDao; private ExecutorService executorService; public LocalRepository(Application application) { executorService = Executors.newSingleThreadExecutor(); CatalogueDatabase database = CatalogueDatabase.getDatabase(application); mCatalogueDao = database.catalogueDao(); } public DataSource.Factory<Integer, MovieEntity> getAllBookmarkMovies() { return mCatalogueDao.getAllMovies(); } public LiveData<MovieEntity> getBookmarkMovieById(final String movieId) { return mCatalogueDao.getMovieById(movieId); } public void insertMovie(final MovieEntity movieEntity) { executorService.execute(() -> mCatalogueDao.insertMovie(movieEntity)); } public void deleteMovie(final MovieEntity movieEntity) { executorService.execute(() -> mCatalogueDao.deleteMovie(movieEntity)); } public DataSource.Factory<Integer, TvShowEntity> getAllBookmarkTvShows() { return mCatalogueDao.getAllTvShows(); } public LiveData<TvShowEntity> getBookmarkTvShowById(final String tvShowId) { return mCatalogueDao.getTvShowById(tvShowId); } public void insertTvShow(final TvShowEntity tvShowEntity) { executorService.execute(() -> mCatalogueDao.insertTvShow(tvShowEntity)); } public void deleteTvShow(final TvShowEntity tvShowEntity) { executorService.execute(() -> mCatalogueDao.deleteTvShow(tvShowEntity)); } }
JavaScript
UTF-8
20,359
2.671875
3
[]
no_license
var loadC = document.getElementsByClassName("load-container")[0]; var bodyCont = document.getElementsByClassName("bodyCont")[0]; //beginning //Note: Chrome supports ES6 syntax let show = () => { setTimeout(() => { loadC.style.display = "none"; },2000) } for (let yer = 0; yer < document.getElementsByClassName("year").length; yer++) { document.getElementsByClassName("year")[yer].innerHTML = new Date().getFullYear(); } var y = document.querySelectorAll(".sliderC"); for (var i = 0; i < y.length; i++) { if (y[i].className == "sliderC active") { y[i].style.backgroundColor = "blue"; y[i].style.border = "2px solid blue"; } else { y[i].style.backgroundColor = "#white"; y[i].style.border = "2px solid black"; } } try { let ar = (a, b) => a + b; console.log(`10 + 20 = ${ar(10, 20)}`); console.log("Your browser supports ES6 syntax"); } catch (error) { console.log("Your browser does not support ES6 syntax"); } function toggle(x) { x.classList.toggle("active"); if (x.className == "sliderC active") { x.style.backgroundColor = "blue"; x.style.border = "2px solid blue"; } else { x.style.backgroundColor = "white"; x.style.border = "2px solid black"; } } //Layer 2 function closeL2() { var l2 = document.querySelector('.layer2'); l2.style.top = "-100%"; document.body.classList.toggle("red"); } function openL2() { var l2 = document.querySelector('.layer2'); l2.style.top = "0"; document.body.classList.toggle("red"); } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function toggle4(x) { x.classList.toggle("active9"); } var tabcontent = document.querySelectorAll('.tabcontent'); tabcontent[0].style.display = "block"; function openTab(event, id) { var tabcontent = document.querySelectorAll('.tabcontent'); var tablinks = document.querySelectorAll('.tablinks'); for (var i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } for (var i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace("active", ""); } event.target.className += " active"; tabcontent[id].style.display = "block"; } //Slider type 2 var y = document.querySelectorAll(".sliderC2"); for (var i = 0; i < y.length; i++) { if (y[i].className == "sliderC2 active2") { y[i].style.backgroundColor = "green"; } else { y[i].style.backgroundColor = "#eee"; } } function toggle2(x) { x.classList.toggle("active2"); if (x.className == "sliderC2 active2") { x.style.backgroundColor = "green"; } else { x.style.backgroundColor = "#eee"; } } function snaToggle() { var snackbar = document.querySelector("#snackbar"); snackbar.style.bottom = "20px"; snackbar.style.opacity = "1"; setTimeout(function () { snackbar.style.bottom = "-50px"; snackbar.style.opacity = "0"; }, 3000); } function tgplayer(x) { x.classList.toggle("change"); } function run() { var pbar = document.querySelector(".pbar"); var width = 1; var wid = document.querySelector("#width"); var re = setInterval(frame, 1); function frame() { console.log(10); if (width >= 1000) { clearInterval(re); } else { width++; pbar.style.width = (width / 10) + "%"; wid.innerHTML = parseInt(width / 10) + "%"; } } } var modal = document.querySelector('.modal'); var modalcontent = document.getElementsByClassName("modal-content")[0]; var modalbody = document.querySelector('.modal-body'); function openModal() { modalcontent.style.webkitAnimationName = "slideIn"; modal.style.display = "block"; } function closeModal() { modalcontent.style.webkitAnimationName = "slideOut"; modal.style.display = "block"; setTimeout(function () { modal.style.display = "none"; }, 250); } window.onclick = function (event) { var overlay = document.querySelector(".modal"); if (event.target == overlay) { closeModal(); } }; function closeN() { var navig = document.querySelector('.navig'); navig.style.width = "0"; navig.style.left = "-15px" } function openN() { var navig = document.querySelector('.navig'); navig.style.width = "400px"; navig.style.left = "0px" } $(document).ready(function () { $("a").on('click', function (event) { if (this.hash !== "") { event.preventDefault(); var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 800, function () { window.location.hash = hash; }); } // End if }); }); var list = ["Sharan", "Cheetah", "Jahnvi", "Jaguar", "Anu", "Sajiv", "Tiger", "Lion", "Blue Whale", "Sperm Whale", "Orca", "Bottlenose Dolphin", "Humpback Whale", "Smilodon", "Spiderman", "Cougar", "Leopard", "Polar Bear", "Robin", "Albatross", "Elephant"]; for (var h = 0; h < list.length; h++) { var ul = document.querySelector("ul"); var li = document.createElement("li"); var t = document.createTextNode(list[h]); li.appendChild(t); ul.appendChild(li); } function filter() { var filter = document.querySelector("#filter"); var filt = filter.value.toUpperCase(); var ul = document.querySelector("#ul"); var li = ul.getElementsByTagName("li"); for (var i = 0; i < li.length; i++) { var value = li[i].innerHTML; if (value.toUpperCase().indexOf(filt) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } } var type = 0; function Tfilter(type) { var filter = document.querySelector("#tfilter"); var filt = filter.value.toUpperCase(); console.log(filt) var table = document.querySelector("#Table"); var tr = table.getElementsByTagName("tr"); for (var i = 0; i < tr.length; i++) { var value = tr[i].getElementsByTagName("td")[type]; if (value) { if (value.innerHTML.toUpperCase().indexOf(filt) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } var radios = document.querySelectorAll('.radioss'); for (var i = 0; i < radios.length; i++) { radios[i].addEventListener("click", function () { if (radios[0].checked == true) { type = 0; } if (radios[1].checked == true) { type = 1; } }) } document.querySelector('#tfilter').addEventListener("keyup", function () { Tfilter(type) }); class sharantg extends HTMLElement { // Monitor the 'name' attribute for changes. static get observedAttributes() { return ['name', 'equation']; } // Respond to attribute changes. attributeChangedCallback(attr, oldValue, newValue) { if (attr == 'name') { this.textContent += `Hello, ${newValue}. ` + ""; } if (attr = "equation") { this.textContent += "Equation answer: " + eval(newValue.toString()); } } } // Define the new element try { customElements.define('sharan-t', sharantg); } catch (e) { console.log("Your browser does not support custom elements"); } var codeDiv = document.getElementsByClassName('codeDiv'); for (var i = 0; i < codeDiv.length; i++) { CodeColor(codeDiv[i]); } function CodeColor(elmnt, mode) { var lang = (mode || "html"); var elmntObj = (document.getElementById(elmnt) || elmnt); var elmntTxt = elmntObj.innerHTML; var tagcolor = "#D64848"; var tagnamecolor = "#D64848"; var attributecolor = "#cc3333"; var attributevaluecolor = "green"; var commentcolor = "green"; var cssselectorcolor = "blue"; var csspropertycolor = "#ea4848"; var csspropertyvaluecolor = "mediumblue"; var cssdelimitercolor = "black"; var cssimportantcolor = "red"; var jscolor = "black"; var jskeywordcolor = "purple"; var jsstringcolor = "green"; var jsnumbercolor = "lightgreen"; var jspropertycolor = "blue"; elmntObj.style.fontFamily = "Consolas,'Courier New', monospace"; if (!lang) { lang = "html"; } if (lang == "html") { elmntTxt = htmlMode(elmntTxt); } if (lang == "css") { elmntTxt = cssMode(elmntTxt); } if (lang == "js") { elmntTxt = jsMode(elmntTxt); } elmntObj.innerHTML = elmntTxt; function extract(str, start, end, func, repl) { var s, e, d = "", a = []; while (str.search(start) > -1) { s = str.search(start); e = str.indexOf(end, s); if (e == -1) { e = str.length; } if (repl) { a.push(func(str.substring(s, e + (end.length)))); str = str.substring(0, s) + repl + str.substr(e + (end.length)); } else { d += str.substring(0, s); d += func(str.substring(s, e + (end.length))); str = str.substr(e + (end.length)); } } this.rest = d + str; this.arr = a; } function htmlMode(txt) { var rest = txt, done = "", php, comment, angular, startpos, endpos, note, i; comment = new extract(rest, "&lt;!--", "--&gt;", commentMode, "W3HTMLCOMMENTPOS"); rest = comment.rest; while (rest.indexOf("&lt;") > -1) { note = ""; startpos = rest.indexOf("&lt;"); if (rest.substr(startpos, 9).toUpperCase() == "&LT;STYLE") { note = "css"; } if (rest.substr(startpos, 10).toUpperCase() == "&LT;SCRIPT") { note = "javascript"; } endpos = rest.indexOf("&gt;", startpos); if (endpos == -1) { endpos = rest.length; } done += rest.substring(0, startpos); done += tagMode(rest.substring(startpos, endpos + 4)); rest = rest.substr(endpos + 4); if (note == "css") { endpos = rest.indexOf("&lt;/style&gt;"); if (endpos > -1) { done += cssMode(rest.substring(0, endpos)); rest = rest.substr(endpos); } } if (note == "javascript") { endpos = rest.indexOf("&lt;/script&gt;"); if (endpos > -1) { done += jsMode(rest.substring(0, endpos)); rest = rest.substr(endpos); } } } rest = done + rest; for (i = 0; i < comment.arr.length; i++) { rest = rest.replace("W3HTMLCOMMENTPOS", comment.arr[i]); } return rest; } function tagMode(txt) { var rest = txt, done = "", startpos, endpos, result; while (rest.search(/(\s|<br>)/) > -1) { startpos = rest.search(/(\s|<br>)/); endpos = rest.indexOf("&gt;"); if (endpos == -1) { endpos = rest.length; } done += rest.substring(0, startpos); done += attributeMode(rest.substring(startpos, endpos)); rest = rest.substr(endpos); } result = done + rest; result = "<span style=color:" + tagcolor + ">&lt;</span>" + result.substring(4); if (result.substr(result.length - 4, 4) == "&gt;") { result = result.substring(0, result.length - 4) + "<span style=color:" + tagcolor + ">&gt;</span>"; } return "<span style=color:" + tagnamecolor + ">" + result + "</span>"; } function attributeMode(txt) { var rest = txt, done = "", startpos, endpos, singlefnuttpos, doublefnuttpos, spacepos; while (rest.indexOf("=") > -1) { endpos = -1; startpos = rest.indexOf("="); singlefnuttpos = rest.indexOf("'", startpos); doublefnuttpos = rest.indexOf('"', startpos); spacepos = rest.indexOf(" ", startpos + 2); if (spacepos > -1 && (spacepos < singlefnuttpos || singlefnuttpos == -1) && (spacepos < doublefnuttpos || doublefnuttpos == -1)) { endpos = rest.indexOf(" ", startpos); } else if (doublefnuttpos > -1 && (doublefnuttpos < singlefnuttpos || singlefnuttpos == -1) && (doublefnuttpos < spacepos || spacepos == -1)) { endpos = rest.indexOf('"', rest.indexOf('"', startpos) + 1); } else if (singlefnuttpos > -1 && (singlefnuttpos < doublefnuttpos || doublefnuttpos == -1) && (singlefnuttpos < spacepos || spacepos == -1)) { endpos = rest.indexOf("'", rest.indexOf("'", startpos) + 1); } if (!endpos || endpos == -1 || endpos < startpos) { endpos = rest.length; } done += rest.substring(0, startpos); done += attributeValueMode(rest.substring(startpos, endpos + 1)); rest = rest.substr(endpos + 1); } return "<span style=color:" + attributecolor + ">" + done + rest + "</span>"; } function attributeValueMode(txt) { return "<span style=color:" + attributevaluecolor + ">" + txt + "</span>"; } function commentMode(txt) { return "<span style=color:" + commentcolor + ">" + txt + "</span>"; } function cssMode(txt) { var rest = txt, done = "", s, e, comment, i, midz, c, cc; comment = new extract(rest, /\/\*/, "*/", commentMode, "W3CSSCOMMENTPOS"); rest = comment.rest; while (rest.search("{") > -1) { s = rest.search("{"); midz = rest.substr(s + 1); cc = 1; c = 0; for (i = 0; i < midz.length; i++) { if (midz.substr(i, 1) == "{") { cc++; c++ } if (midz.substr(i, 1) == "}") { cc--; } if (cc == 0) { break; } } if (cc != 0) { c = 0; } e = s; for (i = 0; i <= c; i++) { e = rest.indexOf("}", e + 1); } if (e == -1) { e = rest.length; } done += rest.substring(0, s + 1); done += cssPropertyMode(rest.substring(s + 1, e)); rest = rest.substr(e); } rest = done + rest; rest = rest.replace(/{/g, "<span style=color:" + cssdelimitercolor + ">{</span>"); rest = rest.replace(/}/g, "<span style=color:" + cssdelimitercolor + ">}</span>"); for (i = 0; i < comment.arr.length; i++) { rest = rest.replace("W3CSSCOMMENTPOS", comment.arr[i]); } return "<span style=color:" + cssselectorcolor + ">" + rest + "</span>"; } function cssPropertyMode(txt) { var rest = txt, done = "", s, e, n, loop; if (rest.indexOf("{") > -1) { return cssMode(rest); } while (rest.search(":") > -1) { s = rest.search(":"); loop = true; n = s; while (loop == true) { loop = false; e = rest.indexOf(";", n); if (rest.substring(e - 5, e + 1) == "&nbsp;") { loop = true; n = e + 1; } } if (e == -1) { e = rest.length; } done += rest.substring(0, s); done += cssPropertyValueMode(rest.substring(s, e + 1)); rest = rest.substr(e + 1); } return "<span style=color:" + csspropertycolor + ">" + done + rest + "</span>"; } function cssPropertyValueMode(txt) { var rest = txt, done = "", s; rest = "<span style=color:" + cssdelimitercolor + ">:</span>" + rest.substring(1); while (rest.search(/!important/i) > -1) { s = rest.search(/!important/i); done += rest.substring(0, s); done += cssImportantMode(rest.substring(s, s + 10)); rest = rest.substr(s + 10); } result = done + rest; if (result.substr(result.length - 1, 1) == ";" && result.substr(result.length - 6, 6) != "&nbsp;" && result.substr(result.length - 4, 4) != "&lt;" && result.substr(result.length - 4, 4) != "&gt;" && result.substr(result.length - 5, 5) != "&amp;") { result = result.substring(0, result.length - 1) + "<span style=color:" + cssdelimitercolor + ">;</span>"; } return "<span style=color:" + csspropertyvaluecolor + ">" + result + "</span>"; } function cssImportantMode(txt) { return "<span style=color:" + cssimportantcolor + ";font-weight:bold;>" + txt + "</span>"; } function jsMode(txt) { var rest = txt, done = "", esc = [], i, cc, tt = "", sfnuttpos, dfnuttpos, compos, comlinepos, keywordpos, numpos, mypos, dotpos, y; for (i = 0; i < rest.length; i++) { cc = rest.substr(i, 1); if (cc == "\\") { esc.push(rest.substr(i, 2)); cc = "W3JSESCAPE"; i++; } tt += cc; } rest = tt; y = 1; while (y == 1) { sfnuttpos = getPos(rest, "'", "'", jsStringMode); dfnuttpos = getPos(rest, '"', '"', jsStringMode); compos = getPos(rest, /\/\*/, "*/", commentMode); comlinepos = getPos(rest, /\/\//, "<br>", commentMode); numpos = getNumPos(rest, jsNumberMode); keywordpos = getKeywordPos("js", rest, jsKeywordMode); dotpos = getDotPos(rest, jsPropertyMode); if (Math.max(numpos[0], sfnuttpos[0], dfnuttpos[0], compos[0], comlinepos[0], keywordpos[0], dotpos[0]) == -1) { break; } mypos = getMinPos(numpos, sfnuttpos, dfnuttpos, compos, comlinepos, keywordpos, dotpos); if (mypos[0] == -1) { break; } if (mypos[0] > -1) { done += rest.substring(0, mypos[0]); done += mypos[2](rest.substring(mypos[0], mypos[1])); rest = rest.substr(mypos[1]); } } rest = done + rest; for (i = 0; i < esc.length; i++) { rest = rest.replace("W3JSESCAPE", esc[i]); } return "<span style=color:" + jscolor + ">" + rest + "</span>"; } function jsStringMode(txt) { return "<span style=color:" + jsstringcolor + ">" + txt + "</span>"; } function jsKeywordMode(txt) { return "<span style=color:" + jskeywordcolor + ">" + txt + "</span>"; } function jsNumberMode(txt) { return "<span style=color:" + jsnumbercolor + ">" + txt + "</span>"; } function jsPropertyMode(txt) { return "<span style=color:" + jspropertycolor + ">" + txt + "</span>"; } function getDotPos(txt, func) { var x, i, j, s, e, arr = [".", "<", " ", ";", "(", "+", ")", "[", "]", ",", "&", ":", "{", "}", "/", "-", "*", "|", "%"]; s = txt.indexOf("."); if (s > -1) { x = txt.substr(s + 1); for (j = 0; j < x.length; j++) { cc = x[j]; for (i = 0; i < arr.length; i++) { if (cc.indexOf(arr[i]) > -1) { e = j; return [s + 1, e + s + 1, func]; } } } } return [-1, -1, func]; } function getMinPos() { var i, arr = []; for (i = 0; i < arguments.length; i++) { if (arguments[i][0] > -1) { if (arr.length == 0 || arguments[i][0] < arr[0]) { arr = arguments[i]; } } } if (arr.length == 0) { arr = arguments[i]; } return arr; } function getKeywordPos(typ, txt, func) { var words, i, pos, rpos = -1, rpos2 = -1, patt; if (typ == "js") { words = ["abstract", "arguments", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "eval", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "NaN", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"]; } for (i = 0; i < words.length; i++) { pos = txt.indexOf(words[i]); if (pos > -1) { patt = /\W/g; if (txt.substr(pos + words[i].length, 1).match(patt) && txt.substr(pos - 1, 1).match(patt)) { if (pos > -1 && (rpos == -1 || pos < rpos)) { rpos = pos; rpos2 = rpos + words[i].length; } } } } return [rpos, rpos2, func]; } function getPos(txt, start, end, func) { var s, e; s = txt.search(start); e = txt.indexOf(end, s + (end.length)); if (e == -1) { e = txt.length; } return [s, e + (end.length), func]; } function getNumPos(txt, func) { var arr = ["<br>", " ", ";", "(", "+", ")", "[", "]", ",", "&", ":", "{", "}", "/", "-", "*", "|", "%", "="], i, j, c, startpos = 0, endpos, word; for (i = 0; i < txt.length; i++) { for (j = 0; j < arr.length; j++) { c = txt.substr(i, arr[j].length); if (c == arr[j]) { if (c == "-" && (txt.substr(i - 1, 1) == "e" || txt.substr(i - 1, 1) == "E")) { continue; } endpos = i; if (startpos < endpos) { word = txt.substring(startpos, endpos); if (!isNaN(word)) { return [startpos, endpos, func]; } } i += arr[j].length; startpos = i; i -= 1; break; } } } return [-1, -1, func]; } } $("pre").html(function (index, html) { return html.replace(/^(.*)$/mg, "<span class=\"line\">$1</span>") });
Java
UTF-8
1,737
3.765625
4
[ "MIT" ]
permissive
import java.util.ArrayList; import java.util.List; public class Inorder { static class TreeNode { int val; TreeNode parent; TreeNode left; TreeNode right; TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; if (left != null) left.parent = this; if (right != null) right.parent = this; } @Override public String toString() { return "[" + val + "]"; } } private static void inorder(TreeNode root, List<Integer> values) { if (root == null) return; inorder(root.left, values); values.add(root.val); inorder(root.right, values); } private static void inorderConstant(TreeNode root, List<Integer> values) { TreeNode prev = null; TreeNode curr = root; while (curr != null) { if (curr.left != null && curr.parent == prev) { prev = curr; curr = curr.left; } else if (curr.right != null && curr.right != prev) { values.add(curr.val); prev = curr; curr = curr.right; } else { if (curr.right != prev) { values.add(curr.val); } prev = curr; curr = curr.parent; } } } public static void main(String[] args) { List<Integer> values = new ArrayList<Integer>(); TreeNode root = new TreeNode(5, new TreeNode(3, new TreeNode(2, null, null), new TreeNode(4, null, null) ), new TreeNode(7, new TreeNode(6, null, null), new TreeNode(8, null, null) ) ); inorder(root, values); System.out.println(values); values.clear(); inorderConstant(root, values); System.out.println(values); } }
Java
UTF-8
752
2.046875
2
[]
no_license
package com.epsi.mediatheque.config; import com.epsi.mediatheque.mapper.LoanMapper; import com.epsi.mediatheque.mapper.MediaMapper; import com.epsi.mediatheque.service.LoanService; import com.epsi.mediatheque.service.MediaService; import com.epsi.mediatheque.service.impl.JdbcLoanServiceImpl; import com.epsi.mediatheque.service.impl.JdbcMediaServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MediaConfig { @Bean public MediaService jdbcMediaService(MediaMapper mediaMapper) { return new JdbcMediaServiceImpl(mediaMapper); } @Bean public LoanService jdbcLoanService(LoanMapper loanMapper){return new JdbcLoanServiceImpl(loanMapper);} }
Python
UTF-8
1,541
2.71875
3
[ "MIT" ]
permissive
import pymunk from manimlib.scene.scene import Scene from manimlib.mobject.physics import PhysicMobject from manimlib.animation.physics import Simulate class PhysicScene(Scene): def __init__(self, **kwargs): self.space = pymunk.Space() self.physic_objs = [] super().__init__(**kwargs) def set_gravity(self, gravity): x = gravity[0] * 1000 y = gravity[1] * 1000 self.space.gravity = x, y def add_physic_obj(self, *mobjects): for i in mobjects: if isinstance(i, PhysicMobject): self.physic_objs.append(i) def add_static_obj(self, *mobjects): for obj in mobjects: self.space.add(obj.shape) self.add(obj.mobject) def bake(self, time=1.0): step = 1 / self.camera.frame_rate for obj in self.physic_objs: obj.show_alpha = obj.add_time / time for t in range(int(time / step)): for i, obj in enumerate(self.physic_objs): obj.append_act() if t * step >= obj.add_time: if obj.body.space != self.space: self.space.add(obj.body) self.space.add(obj.shape) self.space.step(step) def clear(self): for i in self.physic_objs: i.clear() def simulate(self, time=1.0): self.bake(time) self.play(*[Simulate(self, obj)\ for obj in self.physic_objs], run_time = time) self.clear()
Java
UTF-8
1,778
1.9375
2
[]
no_license
package com.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.bean.OldSickness; @Repository("oldSicknessMapper") public interface OldSicknessMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table old_sickness * * @mbggenerated */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table old_sickness * * @mbggenerated */ int insert(OldSickness record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table old_sickness * * @mbggenerated */ int insertSelective(OldSickness record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table old_sickness * * @mbggenerated */ OldSickness selectByPrimaryKey(Integer id); List<OldSickness> selectOldSicknessByoldDiseasedetailIid(Integer oldDiseasedetail_id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table old_sickness * * @mbggenerated */ int updateByPrimaryKeySelective(OldSickness record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table old_sickness * * @mbggenerated */ int updateByPrimaryKey(OldSickness record); void deleteOldSicknessByoldDiseasedetailId(Integer detailid); public List<OldSickness> selectDiseaseAndDiseaseDetailsByDetailid(Integer id); }
C#
UTF-8
7,286
3.265625
3
[ "Apache-2.0" ]
permissive
using System; using System.Drawing; using System.Numerics; using Veldrid; /* This class holds (and provides dubiously mutex guarded access to) OpenGl vertex and colour data */ namespace rgat { /// <summary> /// A colour format conversion class for dealing with colours /// in formats that Veldrid, ImGui and .NET require /// </summary> public struct WritableRgbaFloat { /// <summary> /// Create a colour from a .NET drawing Colour /// </summary> /// <param name="col">Colour</param> public WritableRgbaFloat(Color col) { R = col.R / 255f; G = col.G / 255f; B = col.B / 255f; A = col.A / 255f; } /// <summary> /// Create a colour from float colour values (0-1) /// Values higher than 1 can be specified for non-colour rendering usage /// </summary> /// <param name="Rf">red</param> /// <param name="Gf">green</param> /// <param name="Bf">blue</param> /// <param name="Af">alpha</param> public WritableRgbaFloat(float Rf, float Gf, float Bf, float Af) { R = (float)Rf; G = (float)Gf; B = (float)Bf; A = (float)Af; } /// <summary> /// Create a colour from uint colour values (0-255) /// </summary> /// <param name="Ru">red</param> /// <param name="Gu">green</param> /// <param name="Bu">blue</param> /// <param name="Au">alpha</param> public WritableRgbaFloat(uint Ru, uint Gu, uint Bu, uint Au) { System.Diagnostics.Debug.Assert(Ru <= 255 && Gu <= 255 && Bu <= 255 && Au <= 255); R = (float)(Ru / 255.0); G = (float)(Gu / 255.0); B = (float)(Bu / 255.0); A = (float)(Au / 255.0); } /// <summary> /// Create a colour from a Vector /// </summary> /// <param name="col">Vector4 of rgba</param> public WritableRgbaFloat(Vector4 col) { R = col.X; G = col.Y; B = col.Z; A = col.W; } /// <summary> /// Create a colour from an ImGui uint /// </summary> /// <param name="col">uint colour</param> public WritableRgbaFloat(uint col) { A = ((col & 0xff000000) >> 24) / 255f; B = ((col & 0xff0000) >> 16) / 255f; G = ((col & 0xff00) >> 8) / 255f; R = ((col & 0xff)) / 255f; } /// <summary> /// Get the uint value of this colour required by ImGui /// </summary> /// <param name="customAlpha">An optional alpha value</param> /// <returns>This colour as a uint</returns> public uint ToUint(uint? customAlpha = null) { if (customAlpha != null) { return (customAlpha.Value << 24) + ((uint)(B * 255) << 16) + ((uint)(G * 255) << 8) + ((uint)(R * 255)); } return ((uint)(A * 255) << 24) + ((uint)(B * 255) << 16) + ((uint)(G * 255) << 8) + ((uint)(R * 255)); } /// <summary> /// Change the alpha of a uint colour /// </summary> /// <param name="original">The colour to change the alpha of</param> /// <param name="customAlpha">An optional alpha value</param> /// <returns>This colour as a uint</returns> public static uint ToUint(uint original, uint customAlpha) { return (customAlpha << 24) + (original & 0xffffff); } /// <summary> /// This colour as a vector /// </summary> /// <returns>Vector4</returns> public Vector4 ToVec4() { return new Vector4(R, G, B, A); } /// <summary> /// Convert a .NET Colour to a Vector4 /// </summary> /// <param name="col">Input Colour</param> /// <returns>output Vector4</returns> public static Vector4 ToVec4(Color col) { float R = col.R / 255f; float G = col.G / 255f; float B = col.B / 255f; float A = col.A / 255f; return new Vector4(R, G, B, A); } /// <summary> /// Convert a .NET Colour to a Veldrid RgbaFloat /// </summary> /// <param name="col"></param> /// <returns>RgbaFloat</returns> public static RgbaFloat ToRgbaFloat(Color col) { float R = col.R / 255f; float G = col.G / 255f; float B = col.B / 255f; float A = col.A / 255f; return new RgbaFloat(R, G, B, A); } /// <summary> /// Convert a .NET Colour to a uint /// </summary> /// <param name="col">Input Colour</param> /// <returns>output uint</returns> public static uint ToUint(Color col) { float R = col.R / 255f; float G = col.G / 255f; float B = col.B / 255f; float A = col.A / 255f; return CreateUint(R, G, B, A); } /// <summary> /// Convert float colour components to an imgui uint /// </summary> /// <param name="R">Red component 0-1</param> /// <param name="G">Green component 0-1</param> /// <param name="B">Blue component 0-1</param> /// <param name="A">Alpha component 0-1</param> /// <returns>uint colour</returns> public static uint CreateUint(float R, float G, float B, float A) { R = Math.Min(R, 1); G = Math.Min(G, 1); B = Math.Min(B, 1); A = Math.Min(A, 1); return ((uint)(A * 255) << 24) + ((uint)(B * 255) << 16) + ((uint)(G * 255) << 8) + ((uint)(R * 255)); } /// <summary> /// Brighten a uint colour of a UI theme /// </summary> /// <param name="inputColour">uint colour</param> /// <param name="amount">How much to brighten it (0.0-2.0)</param> /// <returns></returns> public static uint Brighten(uint inputColour, float amount) { float A = ((inputColour & 0xff000000) >> 24) / 255f; float B = ((inputColour & 0xff0000) >> 16) / 255f; float G = ((inputColour & 0xff00) >> 8) / 255f; float R = ((inputColour & 0xff)) / 255f; return CreateUint(Math.Min(R * amount, 1), Math.Min(G * amount, 1), Math.Min(B * amount, 1), A); } /// <summary> /// Get this colour as a Veldrid RgbaFloat /// </summary> /// <returns>RgbaFloat</returns> public RgbaFloat ToRgbaFloat() { return new RgbaFloat(R, G, B, A); } /// <summary> /// The red value /// </summary> public float R { get; set; } /// <summary> /// The green value /// </summary> public float G { get; set; } /// <summary> /// The blue value /// </summary> public float B { get; set; } /// <summary> /// The alpha value /// </summary> public float A { get; set; } } }
Java
UTF-8
4,064
2.703125
3
[]
no_license
package entities; import java.util.Date; /** * * @author Adamenko Artem <adamenko.artem@gmail.com> * Класс хранящий данные об автобусах */ public class BusObject { /*идентификатор объекта*/ int obj_id_; /*идентификатор проекта*/ int proj_id_; /*название перевозчика*/ String projName; /*текущая скорость*/ int last_speed_; /*долгота*/ double last_lon_; /*широта*/ double last_lat_; /*номер*/ String name_; /*время последнего отклика*/ Date last_time_; /*последняя остановка*/ Date last_station_time_; /*название маршрута*/ String route_name_; /*остановка*/ String bus_station_; /*физический адрес местонахождения*/ String address; /*Тип ТС(обычный, спецтехника)*/ int type_proj; public void setProjName(String projName) { this.projName = projName; } public void setType_proj(int type_proj) { this.type_proj = type_proj; } public String getProjName() { return projName; } public int getType_proj() { return type_proj; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } public void setBus_station_(String bus_station_) { this.bus_station_ = bus_station_; } public String getBus_station_() { return bus_station_; } public void setRoute_name_(String route_name_) { this.route_name_ = route_name_; } public String getRoute_name_() { return route_name_; } public void setLast_station_time_(Date last_station_time_) { this.last_station_time_ = last_station_time_; } public Date getLast_station_time_() { return last_station_time_; } public void setLast_speed_(int last_speed_) { this.last_speed_ = last_speed_; } public int getLast_speed_() { return last_speed_; } public void setObj_id_(int obj_id_) { this.obj_id_ = obj_id_; } public void setProj_id_(int proj_id_) { this.proj_id_ = proj_id_; } public int getObj_id_() { return obj_id_; } public int getProj_id_() { return proj_id_; } public String getName_() { return name_; } public double getLast_lon_() { return last_lon_; } public double getLast_lat_() { return last_lat_; } public Date getLast_time_() { return last_time_; } public void setName_(String name_) { this.name_ = name_; } public void setLast_lon_(double last_lon_) { this.last_lon_ = convertCoord(last_lon_); } public void setLast_lat_(double last_lat_) { this.last_lat_ = convertCoord(last_lat_); } public void setLast_time_(Date last_time_) { this.last_time_ = last_time_; } /**перевод координат для яндекс карт * @param double coord * @return double convert coord */ private static Double convertCoord(Double coord){ double x = coord; double y = x; y = (int)x/100; x=x-y*100; double x1=(int)x; y=y+x1/60+(x-x1)/60; return y; } @Override public String toString() { return "BusObject{" + "obj_id_=" + obj_id_ + ", proj_id_=" + proj_id_ + ", last_speed_=" + last_speed_ + ", last_lon_=" + last_lon_ + ", last_lat_=" + last_lat_ + ", name_=" + name_ + ", last_time_=" + last_time_ + ", last_station_time_=" + last_station_time_ + ", route_name_=" + route_name_ + ", bus_station_=" + bus_station_ + '}'; } }
Markdown
UTF-8
14,967
3.0625
3
[ "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "MIT", "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
--- layout: post title: Mozilla’s Open Leadership Training can work for Open Austin projects date: 2017-04-23 type: post published: true thumb: mozilla-open-austin.svg thumbalt: Mozilla and Open Austin logos author: first_name: Andrew last_name: Nelson --- When I joined the Open Austin leadership team, one of my first goals was to identify specific problems in our project management that might impact members’ ability or motivation to contribute. Early on we defined that problem to be that most project ideas are never completed. However, recently we took a good look at what we are as a community and what we want to facilitate. In doing so, we realized that it’s okay for *ideas* to not be completed; they’re just ideas after all. Rather, it’s a problem when a *project* that has made commitments or set expectations never gets completed. ![A snapshot of recently updated project ideas on Open Austin’’s Github](https://andyhub.com/wordpress/wp-content/uploads/project-ideas-750x582.png)*A snapshot of recently updated project ideas on Open Austin’’s Github* We have completed [dozens of projects](https://www.open-austin.org/projects) over the years, and there are [many more](https://github.com/open-austin/project-ideas/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22Active+Project%22) actively worked on today. However, there are all together still more ideas that have been abandoned, shelved for later, or need leadership. We decided that it’s okay for ideas to be this way, in fact it’s great to have pages of unled or abandoned ideas that a newcomer could pick up and run with. However, it becomes a problem when that newcomer doesn’t have the initiative to start on a new project with no help or to continue working on a project that nobody else wants to participate in. ## Project management issues Another problem is when projects that have progressed past just an idea or that have commitments, funding, or external stakeholders are not satisfactorily completed. From some less than rigorous study and experience with this over some years, I’ve identified five causes that have prevented projects from being completed: * Unmet technical requirements * Lost client or target group * Analysis paralysis * Lost interest or commitment * Dropped out of the community ### Unmet technical requirements This is the most clear problem that often has an easy to understand solution: you get the right technology, right person, or right information to move forward or pivot. For example, Rails (and thus Ruby) was a [popular](https://github.com/blog/2047-language-trends-on-github) new language for web development around the time Code for America started up. This led to a lot of new projects in our communities being developed with Rails. But it didn’t last, and now as other languages and tools have usurped its trendiness, Rails projects may struggle a little harder than others as new members are less interested in contributing to them. Having the right person with technical knowledge and techniques can be just as important as the project’s tools. It can mean the difference between a [tech-debted](https://en.wikipedia.org/wiki/Technical_debt) prototype and a well-engineered project that requires less attention over time, which helps for volunteer projects like ours. Having the right person with the insider technical knowledge also falls under this category. For example, a project for a government body will likely move extremely slowly without the technical knowledge of its legal or procurement matters. ### Lost client or target group Many of our completed projects had at least one external stakeholder, including government workers, nonprofits, and community groups. Without dedicated support and communication affordances to maintain that relationship, a project can easily lose steam. Maintaining relationships is hard, but it affects nearly all aspects of a project for better or worse. A client can provide direction, a target group can provide research, a stakeholder can provide technical resources, and it can be too hard to replace them before volunteers move on to something more fulfilling. ### Analysis paralysis A challenge to all agile teams is keeping track of their own time and project management. A team practicing waterfall might work well by seeking volunteers only for the near term objectives and then different volunteers for later objectives, but that requires strong leadership over a long time. An agile, iterative project requires shorter management terms but also means the team must know how and when to observe, reflect, make, and repeat over and over again. Overcoming paralysis requires the agency to continue even if they lose the ability to seek clarification from a client or target group. Or if the client provides this but not strong direction, a team may spend too much time observing and reflecting. Then they risk never *making* anything. Having the discipline to prototype and potentially throw it all away after testing is critical to iterative work with less managerial overhead. ### Lost interest or commitment On a more personal level, it’s just hard to stay engaged in a project that loses its novelty. A new project idea to someone is a great motivator to learn, but depending on what they did or did not learn, that motivation can fizzle out. Time management is also critical here as we are a volunteer organization that is focused on personal projects over business-driven projects. Those who don’t align themselves accordingly may suffer from how they perceive the community and vice-versa. This can happen to regular members, leaders, and external stakeholders, each with their own repercussions to their project and the whole community. ### Dropped out of the community Finally, churn is the greatest enemy to any subscription-based endeavor. When people leave something, it’s extremely difficult to get them back, and sometimes they leave with something of great value to the community. That can be replaced in time usually, but in the meantime the consequences can cascade. If someone just ghosted, that also draws concern on a more personal level. As an intentional community based on personal projects, it can affect folks on a more emotional level that isn’t so replaceable. Maintaining a personable level of engagement is critical to a healthy community that significantly affects the other four issues I’ve described. ![Image by Mozilla.](https://cdn-images-1.medium.com/max/800/1*duMR4WTab-dVqkH8xYUdpw.jpeg)*Image by Mozilla.* ## Learning from Mozilla At Open Austin’s core are our values of open source work and open participation. We share a lot of that with Mozilla, who’s also a great example of getting things done themselves and by enabling others in their own efforts. As a leader in open project leadership, they offer this as a sort of service via their [open leadership training series](https://mozilla.github.io/open-leadership-training-series/) (OLTS). I enrolled with my [Mobile-Map-IO](https://andyhub.com/concepts/mobile-reporting/) project in their third cohort, which included a couple dozen other participants from around the world. One of the first activities we did was align our values for our individual projects with the community’s values, particularly with Mozilla’s [internet health report](https://internethealthreport.org/v01/) categories. [![Mozilla’s Internet Health Report (image by Mozilla)](https://andyhub.com/wordpress/wp-content/uploads/Internet_Health_issues_march_2017_cover-1400x770-750x413.jpg)](https://blog.mozilla.org/blog/2017/03/15/five-issues-that-will-determine-the-future-of-internet-health/)*Mozilla’s Internet Health Report (image by Mozilla)* The training series overall is about learning the best practices for working in the open, specifically people who are starting up or leading a project. It’s a mix of a few things, mostly captured by a sort of multimedia [readme](https://mozilla.github.io/open-leadership-training-series/). ![Screenshot of the OLTS readme](https://andyhub.com/wordpress/wp-content/uploads/olts-readme-750x422.png)*Screenshot of the OLTS readme* We reference this readme at nearly every cohort check-in, where we all meet virtually via Vidyo and type on Etherpad, a real-time collaborative notepad, when we have questions or are responding to prompts provided by our lead [Abby](https://acabunoc.github.io/). Before we meet, she sends two options for the whole cohort to meet, giving us a chance to schedule one or the the other. ![A usual video chat with the whole OLTS cohort](https://andyhub.com/wordpress/wp-content/uploads/olt3week4convoscreenshot-750x422.png)*A usual video chat with the whole OLTS cohort* In the meantime, she prepares [our cohort Etherpad](https://public.etherpad-mozilla.org/p/olt3-trainings) with the meeting outline and spaces for us to respond to questions. This gives us chances to participate verbally as well as textually in the conversation, engaging individuals from what they type directly instead of relying on individuals who choose to speak. ![Screenshot of how we use Etherpad](https://andyhub.com/wordpress/wp-content/uploads/etherpadscreenshot-750x422.png)*Screenshot of how we use Etherpad* As leaders, it’s important that we learn from and motivate each other. This live document editing is bolstered by more in-depth artifacts developed from these prompts and those listed on the readme. For example, we crafted vision statements, articulated the problems we want to address, and more so that others in the community can better understand the motivation, expected outcomes, and progress without the leaders being present. My Mobile Map IO artifacts are all available on my [project page](https://andyhub.com/concepts/mobile-reporting/). ## Applying this with Open Austin The artifacts are also something we can use to check ourselves, as this is generally only what we spend about 20% of our free time on. Keeping tabs on what commitments we can make in our 20% time is something I think we at Open Austin do well by using [BASEDEF](https://github.com/open-austin/cheatsheet-basedef). **B** logging, **A** pplying, **S** uggesting, **E** xtending, **D** ocumenting, **E** vangelizing, and **F** ixing are all ways folks can get involved in an idea for civic innovation. What I’m doing now for example is the B, for blogging, to share what I learned and how I could contribute to our process for improving the issues I’ve outlined. These artifacts we created are examples of the BASEDEF spec. ![The Open Canvas for my project, similar to the popular Lean and Business Model Canvases.](https://andyhub.com/wordpress/wp-content/uploads/MMIO-Open-Canvas-750x422.png)*The Open Canvas for my project, similar to the popular Lean and Business Model Canvases.* Another artifact we in OLTS used for maintaining a project is the [Open Canvas](https://mozilla.github.io/open-leadership-training-series/articles/opening-your-project/develop-an-open-project-strategy-with-open-canvas/), something similar to what Open Austin has iterated on with the [Civic Tech Project Planning Canvas](https://www.open-austin.org/civic-tech-canvas/). The canvas can also inform a roadmap, which we started building from day one to guide our direction. In order to deliver (i.e. complete to a degree) a minimally viable experience to a stakeholder, the project team must align on some near- and long-term goals that are defined in a way that stakeholders would care about. Instead of defining technical requirements or jargon-laden statements, an experience-based roadmap should define what a stakeholder would be able to do or experience at each milestone. Defining this way may help with keeping them engaged and acting as good designers, not just good hackers. And this is important, because it’s hard as a stakeholder or user to wait for volunteer―[often speculative](https://www.academia.edu/8728551/Hack_for_good_Speculative_labor_app_development_and_the_burden_of_austerity)―labor to yield a desirable experience. Finally, one last OLTS artifact that I felt was important was understanding what we would find welcoming or helpful when first reading about a project. Community is at the center of leading an open project, and without a welcoming experience to that community, a project therein may fail to catch new members. This makes well-designed and welcoming documentation a very high priority. [![Photo by Ann Larie Valentine.](https://andyhub.com/wordpress/wp-content/uploads/sanfranannie-750x563.jpg)](https://www.flickr.com/photos/sanfranannie/4136379024)*Photo by Ann Larie Valentine.* A common way of providing this is with a [readme](https://mozilla.github.io/open-leadership-training-series/articles/opening-your-project/write-a-great-project-readme/), a pleasant way of greeting someone into your project’s home, like the OLTS website. Removing the jargon from our roadmap, readme, and other artifacts is especially important for us because Open Austin is [designing for the 100%](https://www.eventbrite.com/e/lunch-and-learn-with-the-austin-innovation-office-designing-for-the-100-tickets-32426014081): everyone in our city. And like any house’s rules defined on their doormat, we could also define a code of conduct and contribution guidelines to entice folks to start making contributions in any BASEDEF way. Finally, half of the experience of OLTS is having my mentor [Minn](https://github.com/MinnSoe) who knows my name, knows my project, and wants to help me succeed. Even though I may start losing motivation, having someone asking me questions and injecting enthusiasm is hugely helpful to staying on point. Part of his goal is to get me ready for Mozilla’s [Global Sprint](https://mozilla.github.io/global-sprint/). Knowing that my project’s going to be part of some big thing way in advance is a great motivator. Open Austin does something similar with [ATX Hack for Change](http://atxhackforchange.org/), but we don’t really talk it up until the weeks leading up to the event. With a more personal welcoming experience, a constant personal peer presence, and a long-term goal to set, we might see some improvements in membership retention and engagement levels. ## Some suggestions Overall, I have six big takeaways from Mozilla’s OLTS for Open Austin. These are the things I’d like to help lead in our organization: * Motivation and alignment with shared community values * Framework for starting a project from an idea * Regular engagement with the whole community * Ample community technology and resources * Mentor who knows you and provides 1-on-1 experience * High-exposure events to nudge long-term goal setting *Originally published at [https://andyhub.com/archive/mozillas-open-leadership-training-can-work-for-open-austin-projects/](https://andyhub.com/archive/mozillas-open-leadership-training-can-work-for-open-austin-projects/).*
C++
ISO-8859-1
2,090
3.28125
3
[]
no_license
#include "Config.h" #include <fstream> #include <iostream> #include <sstream> void Config::readConfigFile(Image* image, Camera* camera) { std::ifstream file("./config.txt"); std::string line; while (std::getline(file, line)) { //para cada linha if (line[0] == '#') //comentrio continue; if (line.empty()) //linha em branco continue; std::string key; std::istringstream is_line(line); std::getline(is_line, key, ' '); if (key == "res") { //resoluao setRes(is_line, image); } if (key == "camera") { //camera setCamera(is_line, camera); } } } void Config::setRes(std::istringstream& line, Image* image) { std::string temp; std::getline(line, temp, ' '); int w = stoi(temp); std::getline(line, temp); int h = stoi(temp); std::cout << "Criando uma imagem com " << w << " pixeis por " << h << " pixeis." << std::endl; *image = Image(w, h); } void Config::setCamera(std::istringstream& line, Camera* camera) { std::string temp; std::getline(line, temp, ' '); double px = stod(temp); std::getline(line, temp, ' '); double py = stod(temp); std::getline(line, temp, ' '); double pz = stod(temp); std::getline(line, temp, ' '); double tx = stod(temp); std::getline(line, temp, ' '); double ty = stod(temp); std::getline(line, temp, ' '); double tz = stod(temp); std::getline(line, temp, ' '); double ux = stod(temp); std::getline(line, temp, ' '); double uy = stod(temp); std::getline(line, temp, ' '); double uz = stod(temp); std::getline(line, temp, ' '); double fov = stod(temp); std::getline(line, temp); double f = stod(temp); std::cout << "Criando uma camera em: X = " << px << " Y = " << py << " Z = " << pz << std::endl << " apontando para: X = " << tx << " Y = " << ty << " Z = " << tz << std::endl << " vetor de orientacao: X = " << ux << " Y = " << uy << " Z = " << uz << std::endl << "com " << fov << " graus de campo de visao e " << f << " de distancia para o plano da imagem."; *camera = Camera(Vec3(px, py, pz), Vec3(tx, ty, tz), Vec3(ux, uy, uz), fov, f); }
Python
UTF-8
7,033
2.609375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- import collections import functools import inspect import logging from typing import Tuple, Sequence, List, NamedTuple, TYPE_CHECKING from pydantic import BaseModel, Extra, validator, root_validator import numpy as np if TYPE_CHECKING: # pragma: no cover from ._parameters import Parameters # noqa from ._mpe import PathExtractionResult # noqa PointType = Sequence[int] FloatPointType = Sequence[float] PointSequenceType = Sequence[PointType] InitialPointType = Tuple[int, ...] InitialWayPointsType = Tuple[InitialPointType, ...] MPE_MODULE = 'skmpe' MIN_NDIM = 2 logger = logging.getLogger(MPE_MODULE) logger.addHandler(logging.NullHandler()) def mpe_module(obj): """Replace __module__ for decorated object Returns ------- obj : Any The object with replaced __module__ """ obj.__module__ = MPE_MODULE return obj def singledispatch(func_stub): """Single dispatch wrapper with default implementation that raises the exception for invalid signatures """ @functools.wraps(func_stub) @functools.singledispatch def _dispatch(*args, **kwargs): sign_args = ', '.join(f'{type(arg).__name__}' for arg in args) sign_kwargs = ', '.join(f'{kwname}: {type(kwvalue).__name__}' for kwname, kwvalue in kwargs.items()) allowed_signs = '' i = 0 for arg_type, func in _dispatch.registry.items(): if arg_type is object: continue i += 1 sign = inspect.signature(func) allowed_signs += f' [{i}] => {sign}\n' raise TypeError( f"call '{func_stub.__name__}' with invalid signature:\n" f" => ({sign_args}, {sign_kwargs})\n\n" f"allowed signatures:\n{allowed_signs}") return _dispatch @mpe_module class ImmutableDataObject(BaseModel): """Base immutable data object with validating fields """ class Config: extra = Extra.forbid arbitrary_types_allowed = True allow_mutation = False @mpe_module class InitialInfo(ImmutableDataObject): """Initial info data model .. py:attribute:: speed_data Speed data in numpy ndarray .. py:attribute:: start_point The starting point .. py:attribute:: end_point The ending point .. py:attribute:: way_points The tuple of way points """ speed_data: np.ndarray start_point: InitialPointType end_point: InitialPointType way_points: InitialWayPointsType = () @validator('start_point', 'end_point', 'way_points', pre=True) def _to_canonical(cls, v): # noqa return np.asarray(v).tolist() @root_validator def _check_ndim(cls, values): # noqa speed_data = values.get('speed_data') start_point = values.get('start_point') end_point = values.get('end_point') way_points = values.get('way_points') if (speed_data is None or start_point is None or end_point is None or way_points is None): return values ndim = speed_data.ndim if ndim < MIN_NDIM: raise ValueError(f'minimum dimension must be {MIN_NDIM}.') if ndim != len(start_point) or ndim != len(end_point): raise ValueError(f"the start and end points must have dimension {ndim}.") for point in way_points: if len(point) != ndim: raise ValueError(f"the start, end and all way points must have dimension {ndim}.") return values @root_validator def _check_point_duplicates(cls, values): # noqa start_point = values.get('start_point') end_point = values.get('end_point') way_points = values.get('way_points') if start_point is None or end_point is None or way_points is None: return values all_points = [start_point, end_point, *way_points] duplicates = [point for point, count in collections.Counter(all_points).items() if count > 1] if duplicates: raise ValueError( f'the points must not be duplicated, there are duplicated points: {duplicates}') return values @validator('start_point', 'end_point', 'way_points') def _check_points(cls, v, field, values): # noqa if v is None: return v # pragma: no cover if 'speed_data' not in values: return v # pragma: no cover speed_data = values['speed_data'] def validate(point, index=None): if len(point) != speed_data.ndim: # this is the concern of another validator return point n_point = f' [{index}] ' if index else ' ' for i, (n_coord, n_size) in enumerate(zip(point, speed_data.shape)): if n_coord < 0 or n_coord >= n_size: raise ValueError(f"'{field.name}' {point}{n_point}coordinate {i} " f"is out of 'speed_data' bounds [0, {n_size}).") if speed_data[point] is np.ma.masked: raise ValueError(f"'{field.name}' {point}{n_point}inside 'speed_data' masked area.") if field.name == 'way_points': for idx, p in enumerate(v): validate(p, idx) else: validate(v) return v def all_points(self) -> List[PointType]: """Returns all initial points""" return [self.start_point, *self.way_points, self.end_point] def point_intervals(self) -> List[Tuple[PointType, PointType]]: """Returns the list of the tuples of initial point intervals""" all_points = self.all_points() return list(zip(all_points[:-1], all_points[1:])) @mpe_module class PathInfo(NamedTuple): """The named tuple with info about extracted path or piece of path .. py:attribute:: path The path in numpy ndarray .. py:attribute:: start_point The starting point .. py:attribute:: end_point The ending point .. py:attribute:: travel_time The travel time numpy ndarray .. py:attribute:: extraction_result The path extraction result in :class:`PathExtractionResult` that is returned by :class:`MinimalPathExtractor` .. py:attribute:: reversed The flag is true if the extracted path is reversed """ path: np.ndarray start_point: PointType end_point: PointType travel_time: np.ndarray extraction_result: 'PathExtractionResult' reversed: bool @mpe_module class PathInfoResult(NamedTuple): """The named tuple with path info result .. py:attribute:: path Path data in numpy array .. py:attribute:: pieces The tuple of :class:`PathInfo` for every path piece """ path: np.ndarray pieces: Tuple[PathInfo, ...] @property def point_count(self) -> int: """Returns the number of path points""" return self.path.shape[0]
Shell
UTF-8
976
3.515625
4
[]
no_license
#!/bin/bash echo "method 1:" tr -s ' ' '\n' < words.txt | sort | uniq -c | sort -nr | awk '{print $2, $1}' echo "method 2:" cat words.txt | awk '{for(i=1;i<=NF;++i){count[$i]++}} END{for(i in count) {print i,count[i]}}' | sort -k2nr echo "method 3:" cat words.txt | tr -s '[[:space:]]' '\n' | sort | uniq -c | sort -nr | sed -r -e 's/[[:space:]]*([[:digit:]]+)[[:space:]]*([[:alpha:]]+)/\2 \1/g' echo "method 4:" declare -A HashWord File="words.txt" function ReadTxtFile { while read Line do Word=(${Line}) for Var in ${Word[@]} do HashWord+=([${Var}]='1') Word[${Var}]= for i in ${Word[@]} do if [[ ${Var} -eq ${i} ]];then Value=${HashWord[${Var}]} fi done done done < ${File} for Key in ${!HashWord[*]} do echo "${Key} ${#HashWord[${Key}]}" done | sort -k2nr } ### Main Login ReadTxtFile
Go
UTF-8
839
2.890625
3
[]
no_license
package manager import ( "dlmm/command" "dlmm/util" "fmt" "io" "log" "net/http" "os" ) type Manager struct { *command.Command Progress client *http.Client } func (m *Manager) Init(env *command.Command) { m.Command = env m.client = &http.Client{} } func (m *Manager) assertEnvIsSet() { if m.Command == nil || m.client == nil { log.Fatal("please set the env for manager by using 'Init' method.") } } func (m *Manager) Download() { m.assertEnvIsSet() resp, err := http.Get(*m.Command.Url) util.AssertNoError(err) defer resp.Body.Close() // chnage working directory err = os.Chdir(*m.Dir) util.AssertNoError(err) // create file file, err := os.Create(*m.FileName) util.AssertNoError(err) defer file.Close() _, err = io.Copy(file, resp.Body) util.AssertNoError(err) fmt.Println("Download success!!") }
Java
UTF-8
3,901
2.328125
2
[]
no_license
package com.xprogect.api; import android.content.Context; import com.xprogect.MyApplication; import com.xprogect.api.init.ApiException; import com.xprogect.api.init.BeanFactory; import com.xprogect.api.init.CenterParameterInterceptor; import com.xprogect.api.init.NetWorkInterceptor; import com.xprogect.contests.RequestCons; import com.xprogect.x_library.BuildConfig; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import static com.xprogect.contests.RequestCons.DEFAULT_TIME_OUT; import static com.xprogect.contests.RequestCons.STATUS_SUCCESS; /** * 创建retrofit对象和modelService对象 * 以及状态码的判断 * Created by mango on 16/8/18. */ public class ServiceGenerator<T> { private static String baseUrl; private static Retrofit mRetrofit; private static Context mContext; public static void initRetrofit() { baseUrl = RequestCons.BASE_URL; // 日志拦截 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); if (BuildConfig.DEBUG) { loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); } else { loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE); } CenterParameterInterceptor parameterInterceptor = new CenterParameterInterceptor(MyApplication.getContext()); OkHttpClient client = new OkHttpClient.Builder() //连接超时时间 .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) //写操作 超时时间 .writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) //读操作超时时间 .readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) .addInterceptor(new NetWorkInterceptor()) .addInterceptor(loggingInterceptor) .addInterceptor(parameterInterceptor) .build(); mRetrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(client) //增加返回值为Gson的支持(以实体类返回) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } public static <S> S createRetrofitService(Class<S> mDataClick, Context context) { mContext = context; return createRetrofitService(mDataClick); } public static <S> S createRetrofitService(Class<S> mDataClick) { return mRetrofit.create(mDataClick); } /** * 给返回结果去掉状态码等属性, * 如果是查询出错,则返回状态码对应的描述给用户 * * @param observable * @return */ public static Observable filterStatus(Observable observable) { return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(new ResultFilter()); } public Observable<T> filterStatuss(Observable<T> observable) { return observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } private static class ResultFilter<T> implements Func1<BeanFactory<T>, T> { @Override public T call(BeanFactory<T> tHttpBean) { if (tHttpBean.getStatus() == STATUS_SUCCESS) { return tHttpBean.getData(); } else { throw new ApiException(tHttpBean.getStatus(), tHttpBean.getMsg()); } } } }
PHP
UTF-8
1,362
3.25
3
[]
no_license
<?php namespace Win\Calendar; /** * Formata data para Humano */ class TimeAgo extends DateFormat { /** @var string[] Nome das unidades de tempo */ static private $unitsName = array( 'seconds' => ['segundo', 'segundos'], 'minutes' => ['minuto', 'minutos'], 'hours' => ['hora', 'horas'], 'days' => ['dia', 'dias'], 'weeks' => ['semana', 'semanas'], 'months' => ['mês', 'mêses'], 'years' => ['ano', 'anos'] ); /** * Retorna a data no formato humano * @return string (ex: 4 horas atrás), (ex: daqui a 5 dias) */ public static function format(Date $date) { if ($date->isEmpty()) { return 'indisponível'; } $time = time() - strtotime($date->format('d-m-y h:i:s')); if ($time == 0) { return 'agora mesmo'; } if ($time > 0) { return static::getTime($time) . ' atrás'; } if ($time < 0) { return 'daqui a ' . static::getTime($time * (-1)); } } /** * Retorna a data em unidade de tempo Humana * @param int $seconds * @return string Ex: 15 horas */ protected static function getTime($seconds) { $units = array_reverse(Date::$units); foreach ($units as $unitName => $unitTotal) { if ($seconds > $unitTotal) { $timeTotal = floor($seconds / $unitTotal); $isPlural = ($timeTotal > 1); return $timeTotal . ' ' . static::$unitsName[$unitName][$isPlural]; } } return 0; } }
TypeScript
UTF-8
2,674
2.625
3
[]
no_license
import { getRepository } from '../datastore'; import { Log } from '../datastore/entities'; import { ObjectID } from 'mongodb'; import { ObjectID as ObjectIDType } from 'typeorm' import { LogIn, LogListIn, LogListOut, LogUpdate } from '../models/log.models'; import { StatusLog } from '../sdk/constants'; export class LogService { async create(body: LogIn, level: string, project_id: ObjectIDType) { const log = new Log() log.date = new Date(); log.level = level; log.message = body.message.toLowerCase(); log.project = project_id; log.info = body.info; log.exception = body.exception; log.status = StatusLog.ACTIVE; log.history = []; const projRepository = await getRepository(Log); return await projRepository.insert(log); } async list(body: LogListIn, project_id: string) { const projRepository = await getRepository(Log); const offset = (parseInt(body.page) - 1) * parseInt(body.size); var myDate = new Date(); myDate.setDate(myDate.getDate() - 20); var myDate2 = new Date(); myDate2.setDate(myDate.getDate() + 10); const condition = { take: parseInt(body.size), skip: offset, order: { date: "DESC" }, where: { project: new ObjectID(project_id), message: new RegExp(body.text), }, }; if (body.level) { condition.where['level'] = body.level; } if (body.status) { condition.where['status'] = body.status; } if (body.dateFrom && body.dateTo) { condition.where['date'] = { $gte: new Date(body.dateFrom), $lt: new Date(body.dateTo) } } const [items, total] = await projRepository.findAndCount(condition); const result = new LogListOut(); result.items = items; result.total = total; return result; } async getById(id: string): Promise<Log> { const projRepository = await getRepository(Log); const condition = { _id: new ObjectID(id) } return await projRepository.findOne(condition); } async updateStatus(body: LogUpdate) { const projRepository = await getRepository(Log); return await projRepository.findOneAndUpdate({ _id: new ObjectID(body.id) }, { $set: { status: body.status,history:body.history }}); } async countLogsByProjectId(id:string){ const projRepository = await getRepository(Log); const condition = { project: new ObjectID(id) } return await projRepository.count(condition); } }
Java
UTF-8
4,252
3.09375
3
[]
no_license
package Controller; //javafx imports import Model.DatabaseController; import Model.Person; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; //java imports import java.util.ArrayList; public class AddFoodController extends GenericController{ private Person User;//the user that the food is being added to @FXML private TextField txt_search; @FXML private ComboBox Foods; @FXML private TextField quantity; @FXML private ComboBox MealType; @FXML private Label errorMsg; @FXML private Label name; /** * sets the user to the user signed in * @param User logged in user */ public void setUser(Person User){ this.User = User; } /** * sets the drop down of food to all the food */ public void setUpDisplay(){ name.setText("Hello, " + User.getForename()); try { DatabaseController db = new DatabaseController(); ArrayList<String> results = db.getAllLike("","foods","foodName"); ObservableList<String> observableList = FXCollections.observableList(results); Foods.setItems(observableList); } catch (Exception e) { e.printStackTrace(); } } /** * go to the dashboard * @param event button pushed */ @FXML private void GoToDashButtonAction (ActionEvent event) { goToDash(User,event); } /** * adds meal * adds diet * go to dashboard * @param event add food button pressed */ @FXML private void AddFoodsAction (ActionEvent event){ errorMsg.setText(""); DatabaseController db = new DatabaseController(); //validation for quantity if (quantity.getText().matches("^[1-9][0-9]*$")){ int i = Integer.parseInt(quantity.getText()); if (i>10){ errorMsg.setText("Error: quantity greater than 10"); quantity.setText(""); } } else { errorMsg.setText("Error: quantity not positive"); quantity.setText(""); } //validation of dropdown if (Foods.getValue()==null) { errorMsg.setText("Error: food not selected"); }else if(Foods.getValue().toString().equals("")){ errorMsg.setText("Error: food not typed in"); } else { if(!db.isStr(Foods.getValue().toString(),"foods","foodName")){ errorMsg.setText("Error: not valid food"); Foods.setValue(""); } } //validation of the meal type if (MealType.getValue()==null) { errorMsg.setText("Error: meal type not selected"); }else if(MealType.getValue().toString().equals("")){ errorMsg.setText("Error: meal type not typed in"); } else { if(!(MealType.getValue().toString().equals("Breakfast")||MealType.getValue().toString().equals("Lunch")||MealType.getValue().toString().equals("Dinner")||MealType.getValue().toString().equals("Snack"))){ errorMsg.setText("Error: not valid meal type"); MealType.setValue(""); } } if (errorMsg.getText().equals("")){ int mealId = db.addMeal(Foods.getValue().toString(),Integer.parseInt(quantity.getText()),MealType.getValue().toString());//adds meal db.addDiet(mealId,User.getID());//adds diet goToDash(User,event); } } /** * adjusts the result in the drop down of food * @param event search button pushed */ @FXML private void goSearch(ActionEvent event) { try { String toSearch = txt_search.getText(); DatabaseController db = new DatabaseController(); ArrayList<String> results = db.getAllLike(toSearch,"foods","foodName"); ObservableList<String> observableList = FXCollections.observableList(results); Foods.setItems(observableList); } catch (Exception e) { e.printStackTrace(); } } }
Markdown
UTF-8
3,005
2.734375
3
[ "MIT" ]
permissive
# Protocol Basics Protocols are instructions for Instruments like the MultispeQ on how to run a measurement. Those instructions written in the **J**ava**S**cript **O**bject **N**otation or [JSON][JSON_URL]. PhotosynQ is providing preset Protocols indicated by a <i class="fa fa-star text-warning"></i> start icon called **Staff Picks**. They are listed in the applications as standard Protocols, as well as the standard Protocols when setting up a new Project. All Protocols developed on PhotosynQ are open and accessible through the website and the applications. ?> **Tip:** Protocols can be associated with **Macros** which are small pieces of code that help you analyze a measurement immediately after it has been collected. When a Macro is available, it is indicated on the Website as well as in the Desktop Application. ## Website 1. Go to your user profile by clicking on your user name in the top menu bar. If you are not signed in, do that first. 2. Select the **Protocols** tab to list all of your Protocols. 3. Click on a Protocol to get to the Protocol page with the Protocol description, the Protocol Code and the Comments. On the right hand-side, you will further find the Protocol category, the connected macro and compatible Instruments. ## Desktop Application 1. Open your protocols by selecting **Protocols** from the left menu bar or using the shortcut `Ctrl+3 / ⌘3`. 2. Click on the **My Protocols** to list all your protocols, if it is not already available. 3. Click on a protocol in the list to show detailed information in the side bar. ![View Protocols within the Desktop Application](images/protocols-list.png) ?> **Tip:** In case you want to see the work of others, select **Explore** from the top menu. ## Mobile Application 1. Tab the <i class="fa fa-bars"></i> overflow menu in the top left corner. 2. Select **Quick Measurements** from the menu. ![View Protocols within the Mobile Android Application](images/android-quick-measurements.png) ## Protocol compatibility If a Protocol will run on an Instrument depends on the type of Instrument, as well as on the version and configuration. Make sure to read the Protocol description to see if there are limitations. When you are creating a Protocol, make sure to mention, which Instruments are supported. You can also use the discussion to check with the Protocol creator if it will be compatible with your instrument. When a Protocol is run that is not compatible, it can cause the following issues: + The Instrument will crash and needs to be restarted to continue working with it. + The Protocol will run and return results, but e.g. the wrong lights were triggered. + No or wrong data/results is returned after the Protocol is done. ?> **Tip:** You might want to make sure, your Instruments are able to run a Protocol prior to starting an experiment in the field, since it might be difficult to change the Project when you are out of your office. [JSON_URL]: https://www.w3schools.com/js/js_json_intro.asp
JavaScript
UTF-8
2,893
2.578125
3
[]
no_license
const PathFinder = require("../shared/path-finder"); const { SetUnitTargetStateChange } = require("../shared/state-change"); // Orders the units based on movement dependencies module.exports.movementSort = function (game, nonDeadUnits) { const immovableUnits = []; const noDependencyUnit = new Set(); const dependentsMap = {}; for (let i = 0; i < nonDeadUnits.length; i++) { const unit = nonDeadUnits[i]; if (unit.targetPoints.length > 0) { // Repath first game.processStateChange(SetUnitTargetStateChange.create(game.state, unit.owner, unit.position, unit.targetPoints)); if (unit.targetPoints.length > 0) { unit.desiredPath = PathFinder.findPath(game.state, unit.position, unit.targetPoints[0], { ignoreUnits: true }); } } let dependent = undefined; if (unit.targetPoints.length !== 0 && unit.desiredPath && unit.desiredPath.length !== 0) { dependent = game.state.findTarget(unit.desiredPath[0]); } if (dependent !== undefined) { if (!dependentsMap[dependent.id]) { dependentsMap[dependent.id] = []; } if (dependent.isStructure) { // I'm trying to path into a structure so I'm immovable immovableUnits.push(unit); } else { dependentsMap[dependent.id].push(unit); } } else { noDependencyUnit.add(unit); } } /*const immovableIdSet = new Set(); // Mark all immovable units DFS let i = 0; while (i < immovableUnits.length) { const front = immovableUnits[i]; immovableIdSet.add(front.id); // Any dependents should also be marked immovable if (dependentsMap[front.id]) { immovableUnits.push(...dependentsMap[front.id]); } i += 1; }*/ // Every unit is either in the dependency map or in the noDependencyUnit const result = [...immovableUnits, ...noDependencyUnit]; i = 0; while (i < result.length) { const front = result[i]; if (dependentsMap[front.id]) { result.push(...dependentsMap[front.id]); } i += 1; } const nonDegenerateNodes = new Set(); for (let i = 0; i < result.length; i++) { nonDegenerateNodes.add(result[i].id); } for (let i = 0; i < nonDeadUnits.length; i++) { if (!nonDegenerateNodes.has(nonDeadUnits[i].id)) { // Someone is stuck in a cycle UH OH // but they still need to tick!! result.push(nonDeadUnits[i]); } } return result; };
Java
UTF-8
308
1.742188
2
[]
no_license
package org.yannis.ringtail.rpc.invoker; import org.yannis.ringtail.rpc.RpcException; import org.yannis.ringtail.rpc.RpcRequest; import org.yannis.ringtail.rpc.RpcResponse; /** * Created by dell on 2016/7/1. */ public interface Invoker { RpcResponse invoke(RpcRequest request) throws RpcException; }
Java
UTF-8
1,302
2.46875
2
[]
no_license
package com.seasky.dddtemplate.interfaces.controller.test; import com.seasky.dddtemplate.dto.test.TestQueryQry; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * 示例Q线tc工厂 * * @author XueYawei * @date 2020/12/08 */ public class TestQueryTcFactory { public static Stream<TestQueryTc> getTCQryStream(){ List<TestQueryTc> testQueryTcs = new ArrayList<>(); testQueryTcs.add(buildCase01()); testQueryTcs.add(buildCase02()); return testQueryTcs.stream(); } private static TestQueryTc buildCase01() { TestQueryTc findStudentByConditionTc = new TestQueryTc("有条件"); TestQueryQry studentQry = new TestQueryQry(); studentQry.setName("阿萨德"); findStudentByConditionTc.setQryParam(studentQry); //赋值期望返回条数 findStudentByConditionTc.setExpectCount(1); return findStudentByConditionTc; } private static TestQueryTc buildCase02() { TestQueryTc findStudentByConditionTc = new TestQueryTc("空条件"); TestQueryQry studentQry = new TestQueryQry(); findStudentByConditionTc.setQryParam(studentQry); findStudentByConditionTc.setExpectCount(3); return findStudentByConditionTc; } }