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
Java
UTF-8
458
1.96875
2
[]
no_license
package com.revature.data; import java.util.List; import java.util.UUID; import com.revature.beans.Form; import com.revature.beans.Inbox; import com.revature.beans.User; public interface UserDAO { void addUser(User user); List<User> getUsers(); User getUser(String username); void updateUser(User user); void updateUserReim(Long amount, User user); List<UUID> getUserForms(String username); List<UUID> getUserInbox(String username); }
Go
UTF-8
1,460
2.953125
3
[]
no_license
package core import ( "fmt" "github.com/domac/kapok/util" "time" ) type Stats struct { Url string RespSize int64 Duration time.Duration MinRequestTime time.Duration MaxRequestTime time.Duration NumRequests int NumErrs int Num5X int Num2X int } //输出统计信息 func (aggStats *Stats) PrintStats(responders int) (res string) { avgThreadDur := aggStats.Duration / time.Duration(responders) //need to average the aggregated duration reqRate := float64(aggStats.NumRequests) / avgThreadDur.Seconds() qpsRate := float64(aggStats.NumRequests) / (float64(responders) * avgThreadDur.Seconds()) avgReqTime := aggStats.Duration / time.Duration(aggStats.NumRequests) bytesRate := float64(aggStats.RespSize) / avgThreadDur.Seconds() res += fmt.Sprintf("%v requests in %v, %v read\n", aggStats.NumRequests, avgThreadDur, util.ByteSize{float64(aggStats.RespSize)}) res += fmt.Sprintf("Requests/second:\t%.2f\nTransfer/second:\t%v\nAvg Request Time:\t%v\n", reqRate, util.ByteSize{bytesRate}, avgReqTime) res += fmt.Sprintf("Query Per Second:\t%v\n", qpsRate) res += fmt.Sprintf("Fastest Request:\t%v\n", aggStats.MinRequestTime) res += fmt.Sprintf("Slowest Request:\t%v\n", aggStats.MaxRequestTime) res += fmt.Sprintf("Number of Errors:\t%v\n", aggStats.NumErrs) res += fmt.Sprintf("Number of 2XX:\t%v\n", aggStats.Num2X) res += fmt.Sprintf("Number of 5XX:\t%v\n", aggStats.Num5X) return }
Python
UTF-8
178
2.609375
3
[]
no_license
file = open('big1.txt', 'w') file1=open('aniketsh_input.txt', 'r') data = file1.readlines() for i in range(2000): file.write(str(data)) file1.close() file.close()
Markdown
UTF-8
7,150
3.109375
3
[]
no_license
# Operating Systems and Networks Assignment 3 ## `CASH`: Cliché Average SHell ### Build and Run: The file already contains the precompiled files and you can launch the shell just by running `./cash`. If however, you wish to recompile the shell, run the following commands ```bash make clean make ./cash ``` `make clean` removes all the object files and the compiled executable. The `make` command will compile all the `.c` files inside `./src` into `.o` files. It then makes the `obj` directory if it doesn't exist and moves all the `.o` files into that directory. Finally, it links all the object files and the `./cash` executable is generated. ### Specification Implementation Details #### Specification 1: Input/Output Redirection The `execCommand()` method in `utilities.c` has been modified to parse the command and check if any kind of I/O redirection is required. If it is, then the required file is opened and the required streams are connected to them. Then the functions corresponding to the command is executed. After returning from the command specific function, at the end of the `execCommand()` function, the files are closed and streams are set to default. #### Specification 2: Command Pipelines A new function has been added in the call stack, called `handlePipes()`, which is called by `cleanCommand()` and inturn calls `execCommand()` to execute it acfter handling piping logic. Inside `handlePipes()`, we first calculate the number of pipes. If it is 0, we directly send the input string to `execCommand()`. Instead, if there are some pipes, we split to commands. Say there are `n` commands, then we create `n` pipes, meaning `2n` file descriptors and populate them using the `pipe()` function. We then create `n` child processes of the shell. We link the `STDOUT` of the `ith` child to the `ith` write end of the pipe and the `STDIN` of the `ith` child to the `(i-1)th` read end of the pipe. So, the `STDIN` of the first child is still default and the `STDOUT` of the last child is also still default. This creates a pipe chain in which the `ith` child reads the input from the output of the `(i-1)th` child. #### Specification 3:I/O Redirection within Command Pipelines The way the first two specifications have been implemented, this specification has inherently been implemented. #### Specification 4: User-defined Commands 1. `setenv var [value]`: Implemented in `cash_setenv()` in `functions.c`. The command usage is checked and then the required environment variable is set using `setenv()`. 2. `unsetenv var`: Implemented in `cash_unsetenv()` in `functions.c`. The command usage is checked and then the required environment variable is unset using `unsetenv()`. 3. `jobs`: Implemented in `jobs()` in `functions.c`. Iterates over the children in child pool and fetches each one's status from the processes' `proc/<pid>/stat` file. 4. `kjob <job number> <signal number>`: Implemented in `kjob()` in `functions.c`. Checks usage, then verifies the given job number and finally, extracts the pid of the selected job from the job pool and then sent the required signal using the `kill()` syscall. 5. `fg <job number>`: Implemented in `fg()` in `functions.c`. Checks command usage, then verifies the given job number. Once it is confirmed that the job is a valid one, it gets its pid from the child pool, gets its process group, removes the child from the pool, tells the shell to ignore all `STDIN` and `STDOUT` related events and then gives terminal control to the process group belonging to said job. The job is also sent the `SIGCONT` signal, incase it had stopped in the background. While the process runs in the foreground, the shell waits on it using the `wait()` syscall. Once the foreground process terminates or has been stopped, the terminal control is returned to the shell and the default response to `STDIN` and `STDOUT` events is restored. 6. `bg <job number>`: Implemented in `bg()` in `functions.c`. Checks command usage, then verifies the given job number. Once it is confirmed that the job is a valid one, it gets its pid from the child pool. Then it sends the `SIGCONT` signal to that process using the `kill()` method, to tell it to change its status from stopped to running. 7. `overkill`: Implemented in `overkill()` in `functions.c`. It iterates over the children in the pool and sends each one the `SIGKILL` signal and then removes them from the pool. 8. `quit`: Simply calls `exit(0)`. As for exit on `Ctrl+D`, the shell uses the `fgets()` method to read input. `fgets()` returns a `NULL` pointer when it detects the `EOF` character. A check is done on the return value of `fgets()`. If it happens to be null, the infinite I/O loop is broken out of and the shell exits. #### Specification 5: Signal Handling For both the signals, a new action was defined using the `sigaction` structure. 1. `Ctrl-Z`: The hanlder for this is relatively straightforward. It makes a new line and prints the prompt string again. To make sure that when a Ctrl-Z is hit on a foreground process, it is added to the job pool, one bit of modification needed to be made in `fExec()` and `fg()`. The `wait()` was replaced with `waitpid()` and the `WUNTRACED` flag was set. This way, we could inspect the status code to check if the process had been stopped or terminated using the `WIFSTOPPED` macro. If the process has been stopped, it is added to the child pool, because it has been sent to the background. 2. `Ctrl-C`: The hanlder for this is essentially the same as that for the previous one. It prints a new line and prints the prompt string again. ### Bonus Implementation #### Bonus Specification 1: Last Working Directory A global variable called `PREV_LOC[]` is used to store the previous working directory of the shell. Whenever `cd` is run, it is check if the given directory is valid. If so, `PREV_LOC[]` is changed to the current directory and then the `chdir()` syscall is performed. Otherwise, `PREV_LOC[]` is not altered. If the argument passed to `cd` is `-`, then `PREV_LOC[]` is passes as the argument to `chdir()`. #### Bonus Specification 2: Exit Codes A global varibale called `exitCode` is defined. It is initialized to 0 on the initial call to `generatePS()` to indicate that no command has been run yet. If `exitCode` is 0, no face is printed. At the start of `handlePipe`, `exitCode` is set to 1, which indicates a successful execution. Now, at every point that is called from `execCommand()`, wherever there is some error checking for potential problems, if the problem has occured, `exitCode` has been set to -1 to indicate failure. So, by the time `execCommand()` has been popped off the stack, if `exitCode` is still 1, a happy face is printed on the next prompt string, otherwise a sad face is printed. In case of pipes, the last child exits with its `exitCode`, which is then captured using `wait()` and set as the parent's `exitCode`. ### Custom Commands One custom command was added to the shell as well, which wasn't mentioned in the requirements: * `env` → Lists all the enivroment variables in the current instance of the shell. Implemented in `cash_env()` in `functions.c`.
Markdown
UTF-8
3,961
2.546875
3
[]
no_license
--- description: How to fetch a collection of shipping methods via API --- # List all shipping methods To fetch a collection of shipping methods, send a `GET` request to the `/api/shipping_methods` endpoint. {% page-ref page="../../fetching-resources.md" %} ## Request **GET** https://<i></i>yourdomain.commercelayer.io**/api/shipping_methods** ### **Example** {% tabs %} {% tab title="Request" %} The following request fetches a collection of shipping methods: ```javascript curl -X GET \ https://yourdomain.commercelayer.io/api/shipping_methods/ \ -H 'Accept: application/vnd.api+json' \ -H 'Authorization: Bearer your-access-token' ``` {% endtab %} {% tab title="Response" %} On success, the API responds with a `200 OK` status code, returning a paginated collection of resource objects: ```javascript { "data": [ { "id": "xYZkjABcde", "type": "shipping_methods", "links": { "self": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde" }, "attributes": { "name": "Standard shipping", "disabled_at": "2018-01-01T12:00:00.000Z", "currency_code": "EUR", "price_amount_cents": "1000", "price_amount_float": "10.00", "formatted_price_amount": "€10,00", "free_over_amount_cents": "9900", "free_over_amount_float": "99.00", "formatted_free_over_amount": "€99,00", "price_amount_for_shipment_cents": "0", "price_amount_for_shipment_float": "0.0", "formatted_price_amount_for_shipment": "€0,00", "created_at": "2018-01-01T12:00:00.000Z", "updated_at": "2018-01-01T12:00:00.000Z", "reference": "ANY-EXTERNAL-REFEFERNCE", "reference_origin": "ANY-EXTERNAL-REFEFERNCE-ORIGIN", "metadata": { "foo": "bar" } }, "relationships": { "market": { "links": { "self": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/relationships/market", "related": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/market" } }, "shipping_zone": { "links": { "self": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/relationships/shipping_zone", "related": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/shipping_zone" } }, "shipping_category": { "links": { "self": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/relationships/shipping_category", "related": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/shipping_category" } }, "delivery_lead_time_for_shipment": { "links": { "self": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/relationships/delivery_lead_time_for_shipment", "related": "https://yourdomain.commercelayer.io/api/shipping_methods/xYZkjABcde/delivery_lead_time_for_shipment" } } }, "meta": { "mode": "test" } }, { "other": "... 9 shipping_methods (first page)" } ], "meta": { "record_count": 140, "page_count": 14 }, "links": { "first": "https://yourdomain.commercelayer.io/api/shipping_methods?page[number]=1&page[size]=10", "next": "https://yourdomain.commercelayer.io/api/shipping_methods?page[number]=2&page[size]=10", "last": "https://yourdomain.commercelayer.io/api/shipping_methods?page[number]=14&page[size]=10" } } ``` {% endtab %} {% endtabs %} {% page-ref page="../../pagination.md" %} ### Sortable attributes The list of shipping methods can be sorted by the following attributes: * `name` * `disabled_at` * `price_amount_cents` * `id` * `created_at` * `updated_at` * `reference` * `reference_origin` {% page-ref page="../../sorting-results.md" %}
JavaScript
UTF-8
292
3.640625
4
[]
no_license
var myString = "I yam what I yam and always will be what I yam"; splitString = myString.split(" "); console.log(splitString) var yam = {}; splitString.forEach(function(word) { if (word in yam) { yam[word] += 1; } else { yam[word] = 1 } } ) console.log(yam)
C++
UTF-8
1,163
3.6875
4
[]
no_license
#include <iostream> #include <climits> using namespace std; /** * 输出四种整形的最大值,最小值,和对应类型占据内存大小 */ void number_max_min_byte(){ short n_short_max = SHRT_MAX; int n_int_max = INT_MAX; long n_long_max = LONG_MAX; long long n_llong_max = LLONG_MAX; cout<<"short byte:"<< sizeof n_short_max<< " short max:"<<n_short_max << " short min:"<<SHRT_MIN<<endl; cout<<"int byte:"<< sizeof n_int_max<< " int max:"<<n_int_max << " int min:"<<INT_MIN<<endl; cout<<"long byte:"<< sizeof(n_long_max)<< " long max:"<<n_long_max << " long min:"<<LONG_MIN<<endl; cout<<"long long byte:"<< sizeof(n_llong_max)<< " long long max:"<<n_llong_max << " long long min:"<<LLONG_MIN<<endl; } /** * c++中使用大括号“{}”进行变量初始化 */ void init(){ //使用大括号进行初始化,等号“=”可以写可以不写 int a = {10}; int b {12}; cout<<"a="<<a<<",b="<<b<<endl; //大括号内可以不包含任何值,在这种情况下,变量初始化为零 int c = {}; int d {}; cout<<"c="<<c<<",d="<<d<<endl; } int main() { init(); return 0; }
Python
UTF-8
1,363
3
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt #均匀分割二阶插值方法,num是间隔数,f是源 def FinE(min,max,f,num): t=np.linspace(0,max-min,num+1);n=len(t) h=t[1]-t[0] u=np.zeros(n) x=np.zeros(n) b=np.zeros(n) a=np.zeros(n) if n - 1 > 0: c = np.zeros(n - 1); c[1] = -1/2 else: c = np.zeros(1) for k in range(1,n-1): b[k]=f(t[k],h)*h*h for k in range(1,n-1): a[k]=2+c[k-1] c[k]=-1/a[k] for k in range(1,n): if a[k]!=0: x[k]=(b[k]+x[k-1])/a[k] u[n-1]=x[n-1] for k in reversed(range(0,n-1)): u[k]=x[k]-c[k]*u[k+1] print(b) return t,u #delta函数的数值形式 def delta(x,h): if abs(x-0.4)<h/2: return -1/h else: return 0 #精确解 def ExaSol(x): s=np.zeros(len(x)) for j in range(0, len(x)): if x[j]<0.4: s[j]=-0.6*x[j] else: s[j]=0.4*(x[j]-1) return s t=np.linspace(0,1,101) M=ExaSol(t) x,y=FinE(0,1,delta,100) plt.figure(figsize=(6,6)) plt.xlim((-0.01,1.01)) plt.ylim((-0.3,0.01)) plt.scatter(x,y,s=20,marker=".",color="blue") plt.plot(t,M,color="red") label = ["Exact solution","Numerical point"] plt.legend(label, loc ='lower center') plt.grid(True) plt.show()
PHP
UTF-8
343
2.734375
3
[]
no_license
<?php namespace Erik\Sample\Supplier\Client; class BarRestClient { /** * @param string $string * @param array $toArray * @return int */ public function call(string $string, array $toArray): int { // do things. // validate response // return order number return 123; } }
C#
UTF-8
882
3.453125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { string text = Console.ReadLine(); int start = text.IndexOf("<upcase>"); int end = text.IndexOf("</upcase>") + 9; while (start != -1 && end != -1) { StringBuilder sb = new StringBuilder(text); for (int i = start; i < end; i++) { if (sb[i] >= 'a' && sb[i] <= 'z') { sb[i] -= (char)32; } } sb = sb.Remove(end - 9, 9); sb = sb.Remove(start, 8); text = sb.ToString(); start = text.IndexOf("<upcase>"); end = text.IndexOf("</upcase>") + 9; } Console.WriteLine(text); } }
Python
UTF-8
2,520
3
3
[]
no_license
from PS6.load_names import all_categories, category_lines, n_letters, n_categories from PS6.char_to_tensor import lineToTensor from PS6.rnn import RNN import math import random import time import torch import torch.nn as nn n_hidden = 128 rnn = RNN(n_letters, n_hidden, n_categories) criterion = nn.NLLLoss() learning_rate = 0.005 # If you set this too high, it might explode. If too low, it might not learn n_iters = 100000 print_every = 5000 plot_every = 1000 start = time.time() # Keep track of losses for plotting current_loss = 0 all_losses = [] def categoryFromOutput(output): top_n, top_i = output.topk(1) category_i = top_i[0].item() return all_categories[category_i], category_i def randomChoice(l): return l[random.randint(0, len(l) - 1)] def randomTrainingExample(): category = randomChoice(all_categories) line = randomChoice(category_lines[category]) category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long) line_tensor = lineToTensor(line) return category, line, category_tensor, line_tensor def train(category_tensor, line_tensor): hidden = rnn.initHidden() rnn.zero_grad() outputs = None for i in range(line_tensor.size()[0]): outputs, hidden = rnn(line_tensor[i], hidden) loss = criterion(outputs, category_tensor) loss.backward() # Add parameters' gradients to their values, multiplied by learning rate for p in rnn.parameters(): p.data.add_(-learning_rate, p.grad.data) return outputs, loss.item() def timeSince(since): now = time.time() s = now - since m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s) for curr_iter in range(1, n_iters + 1): category, line, category_tensor, line_tensor = randomTrainingExample() output, loss = train(category_tensor, line_tensor) current_loss += loss # Print iter number, loss, name and guess if curr_iter % print_every == 0: guess, guess_i = categoryFromOutput(output) correct = '✓' if guess == category else '✗ (%s)' % category print('%d %d%% (%s) %.4f %s / %s %s' % (curr_iter, curr_iter / n_iters * 100, timeSince(start), loss, line, guess, correct)) # Add current loss avg to list of losses if curr_iter % plot_every == 0: all_losses.append(current_loss / plot_every) current_loss = 0
TypeScript
UTF-8
1,918
2.765625
3
[]
no_license
import { Either, Err, Ok } from '../src/either'; import { Interpreter, IOHandle, LangError } from '../src/lang/interpreter'; import * as rt from '../src/lang/runtime'; import * as ast from '../src/lang/ast'; import Big from 'big.js'; import { assert } from 'chai'; import { inspect } from 'util'; import { pureIOHandle, testIO, testPure } from './_helpers'; describe('The interpreter should evaluate an AST', () => { it('((+ 3) 5) is 8', () => { const i = new Interpreter(pureIOHandle); const expr = ast.App({ fun: ast.App({ fun: ast.Name('+'), arg: ast.Dec(Big(3)) }), arg: ast.Dec(Big(5)) }); const result = i.runAst(expr); assert.deepEqual(result, Ok(rt.Unit(8))); }); it('((x. x) 42) is 42', () => { const i = new Interpreter(pureIOHandle); const lambda = ast.makeLambda( ast.ArgSingle('x'), ast.Name('x') ); const expr = ast.App({ fun: lambda, arg: ast.Dec(Big(42)) }); const result = i.runAst(expr); assert.deepEqual(result, Ok(rt.Unit(42))); }); it('returns a runtime error when things go wrong', () => { const i = new Interpreter(pureIOHandle); const expr = ast.Name('thisNameIsNotDefined'); const result = i.runAst(expr); const runtimeError: rt.RuntimeError = rt.UndefinedName('thisNameIsNotDefined'); const langError: LangError = {type: 'runtimeError', err: runtimeError}; assert.deepEqual(result, Err(langError)); }) }); describe('The interpreter integrates the parser and the runtime', () => { testPure('2 + 2 = 4', '2 + 2', '4'); testPure('3000 * 5.1 = 15300', '3000 * 5.1', '15300'); testPure('reports tokenization (lexing) errors', 'жжж', {error: 'lexError'}); testPure('reports parsing errors', '()[[[', {error: 'parseError'}); testIO( 'can interact with I/O', 'IO:log (IO:readLine {})', ['hello'], ['hello'] ); });
Java
UTF-8
11,100
2.84375
3
[]
no_license
package work.leetcode;/* * Author: park.yq@alibaba-inc.com * Date: 2019/1/21 下午3:44 */ import com.google.common.collect.Maps; import org.apache.flink.shaded.guava18.com.google.common.collect.Queues; import work.common.Node; import work.common.Tree; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.Queue; import java.util.Stack; public class OneToOneHundred { // public static void main(String[] args) { // int[] a = new int[] {0, 4, 4,6,6, 7, 10, 10, 10, 11, 23, 40}; // reduceDuplicate(a); // // printIntArray(a); // // // int[] b = new int[] {7, 8, 9, 10, 1, 2, 4, 5}; // System.out.println(findMinValue(b)); // } public static void printIntArray(int[] a) { printIntArray(a, a.length); } public static void printIntArray(int[] a, int n) { for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } System.out.println(""); } public static int findMinValue(int[] a) { int i = 0; int j = a.length -1; while (i < j) { int mid = (i + j) >> 1; int left = 0; if (mid - 1 < 0) { left = Integer.MIN_VALUE; } else { left = a[mid -1]; } int right = 0; if (mid + 1 >= a.length) { right = Integer.MAX_VALUE; } else { right = a[mid + 1]; } // if (a[mid] > left && a[mid] < right) { if (a[mid] > a[i]) { i = mid + 1; } else { j = mid - 1; } } else { if (a[mid] > left && a[mid] > right) { return a[mid+1]; } if (a[mid] < left && a[mid] < right) { return a[mid]; } } } return -1; } // public static int maxValidate(String s) { // int leftNumber = 0; // int leftIndex = 0; // int rightNumber = 0; // int rightIndex = 0; // // int maxValidate = 0; // for (int i = 0; i < s.length(); i++) { // char c = s.charAt(i); // if (c == '(') { // leftNumber++; // leftIndex = i; // } else { // rightNumber++; // maxValidate += 2; // rightIndex = i; // } // // // // // } // } //26 public static void reduceDuplicate(int[] a) { int i = 0; int j = 1; while (j < a.length) { if (a[j] != a[i]) { a[++i] = a[j]; } j++; } } public static void number(int[] a, int[] result, int n, int N, int curr, int start) { if (curr > N) { return; } if (curr == N) { printIntArray(result, n); return; } for (int i = start; i < a.length; i++) { result[n] = a[i]; number(a, result, n+1, N, curr + a[i], i + 1); } } // public static void main(String[] args) { // int[] a = new int[] {2,3,5,7}; // int[] b = new int[a.length]; // // number(a, b, 0, 7, 0, 0); // } public static char[] multiString(String a, String b) { int lenA = a.length(); int lenB = b.length(); char[] result = new char[lenA + lenB]; for (int i = 0; i < result.length; i++) { result[i] = '\0'; } int k = lenA + lenB; for (int i = a.length() -1; i >= 0; i--) { int tmp = a.charAt(i) - '0'; k--; int m = k; int aux = 0; for (int j = b.length() - 1; j >=0; j--) { int number = tmp * (b.charAt(j) - '0') + aux + result[k]; int res = number % 10; aux = res / 10; result[m--] = (char) ('0' + res); } if (aux > 0) { result[m--] = (char) aux; } } return result; } // // public static void main(String[] args) { // String a = "123451"; // String b = "23"; // // char[] res = multiString(a, b); // // int i = 0; // while (res[i++] == '\n' && i < res.length); // while (i < res.length) { // System.out.print(res[i]); // i++; // } // } // public static void main(String[] args) { // int[] a = new int[] {1, 2, 3, 4}; // // permutation(a, 0); // } public static void permutation(int[] a, int n) { if (n == a.length) { printIntArray(a); return; } for (int i = n; i < a.length; i++) { int tmp = a[n]; a[n] = a[i]; a[i] = tmp; permutation(a, n + 1); tmp = a[n]; a[n] = a[i]; a[i] = tmp; } } private static void nQueue(int[][] a, int n, int[] aux, int len) { if (n == len) { print2Darray(a, len); return; } for (int i = 0; i < len; i++) { if (isValid(aux, n, i)) { a[n][i] = 0; aux[n] = i; nQueue(a, n + 1, aux, len); a[n][i] = 1; aux[n] = 100000; } } } private static boolean isValid(int[] a, int len, int n) { for (int i = 0; i < len; i++) { if (n == i) { return false; } double d1 = (a[i] + 1) / (i + 1); double d2 = (n + 1) / (len + 1); if (d1 == d2) { return false; } } return true; } private static void print2Darray(int[][] a, int len) { for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { System.out.print(a[i][j] + " "); } System.out.println(""); } } // public static void main(String[] args) { // int[][] a = new int[][] { // {1, 1, 1, 1, 1, 1}, // {1, 1, 1, 1, 1, 1}, // {1, 1, 1, 1, 1, 1}, // {1, 1, 1, 1, 1, 1}, // {1, 1, 1, 1, 1, 1}, // {1, 1, 1, 1, 1, 1} // }; // // int[] aux = new int[] { // 100000,100000,100000,100000,100000,100000 // }; // // nQueue(a, 0, aux, 6); // } private static void maxSum(int[] a , int n) { int max = Integer.MIN_VALUE; int sum = 0; for (int i = 0; i < a.length; i++) { int res = sum + a[i]; int tmpmax = Math.max(res, a[i]); if (tmpmax > sum) { sum = tmpmax; } } } private static void combine(int[] a, int k, int number, int[] res) { if (number == 3) { printIntArray(res); return; } for (int i = k; i < a.length; i++) { // res[number] = a[i]; combine(a, i+1, number + 1, res); } } // public static void main(String[] args) { // int[] a = new int[] {1,2,3,4,5,6}; // int[] b = new int[3]; // // //combine(a, 0, 0, b); // // } public static void allSet(int[] a, int n, boolean[] b) { if (n == a.length) { for (int i = 0; i < b.length; i++) { if (b[i]) { System.out.print(a[i] + " "); } } System.out.println(""); } b[n] = true; allSet(a, n + 1, b); b[n] = false; allSet(a, n + 1, b); } public void partition(Tree tree, int n) { } private static void decode(String number, int i, String tmp) { if (i >= number.length()) { System.out.println(tmp); return; } String s = number.substring(i,i+1); String tmp1 = tmp + ((char)(s.charAt(0) - '0' + 96)); decode(number, i + 1, tmp1); if (i + 2 < number.length()) { s = number.substring(i, i + 2); int a = Integer.valueOf(s); if (a <= 26) { tmp1 = "" + ((char)(a + 96)); decode(number, i + 2, tmp1); } } } // public static void main(String[] args) { // String s = "91432194712"; // decode(s, 0, ""); // } private static void allIpAddr(String s, int count, int start, int[] aux) { if (count == 4 && start == s.length()) { printIntArray(aux); return; } if (count >= 4 || start >= s.length()) { return; } for (int i = start + 1; i <= start + 3; i++) { if (i >= s.length()) { return; } if (isValid(s.substring(start, i))) { aux[count] = Integer.valueOf(s.substring(start, i)); allIpAddr(s, count + 1, i, aux); } } } private static boolean isValid(String s) { if (s.startsWith("0")) { return false; } return Integer.valueOf(s) <= 255; } // public static void main(String[] args) { // String s = "25525511135"; // allIpAddr(s, 0, 0, new int[4]); // } private void reverseNode(Node node, int m, int n) { //check the number // | | // --> 4--> 5 --> 6 --> 7 // --> 5--> 6 --> 4 --->7 // --> 6 --> 5 --> 4 -->7 int i = 1; Node parent = node; Node start = node; while (i < m) { parent = start; start = start.next; i++; } Node end = start; i = 1; while (i < n - m + 1) { end = end.next; } Node endNext = end.next; for (i = m; i < n; i++) { end.next = start; start = start.next; } parent.next = start; end.next = endNext; } private static void leftView(Tree tree) { if (tree == null) { return; } Queue<Tree> queue = Queues.newArrayDeque(); ((ArrayDeque<Tree>) queue).addLast(tree); while (!queue.isEmpty()) { Tree t = ((ArrayDeque<Tree>) queue).getLast(); System.out.println(t.data); if (t.right != null) { ((ArrayDeque<Tree>) queue).addLast(t.right); } else { ((ArrayDeque<Tree>) queue).addLast(t.left); } } } public static void main(String[] args) { String s = "this is a test"; System.out.println(longestUniqueString(s)); noRecursive(new int[] {1, 2, 3, 4, 5}); } public static int longestUniqueString(String s) { //do Map<Integer, Integer> map = Maps.newHashMap(); int start = 0; int end; int res = 0; for (int i = 0; i < s.length(); i++) { int tmp = s.charAt(i); if (map.get(tmp) == null) { map.put(tmp, i); } else { int pos = map.get(tmp); if (pos >= start) { if (i - pos > res) { start = pos + 1; res = i - pos; end = i; } } } } return res; } //permution not use recursive private static void noRecursive(int[] a) { Arrays.sort(a); do { printIntArray(a); } while (!Objects.equals(myper(a), a)); } private static int[] myper(int[] a) { int i = a.length -1; while (i > 0) { if (a[i] > a[i-1]) { break; } i--; } if (i > 0) { int tmp = a[i]; a[i] = a[i - 1]; a[i - 1] = tmp; reverse(a, i + 1, a.length - 1); } return a; } private static void reverse(int[] a, int start, int end) { int i = start; int j = end; while (i < j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; i++; j--; } } private static int longCommonSeq(String a, String b) { return 0; } private static int maxValidateBrace(String s) { int start = 0; int res = 0; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '{') { stack.push(i); } else { if (stack.isEmpty()) { start = i + 1; } else { int tmp = stack.pop(); if (stack.isEmpty()) { if (i - tmp + 1 > res) { res = i - start + 1; } } else { if (i - stack.firstElement() > res) { res = i - stack.firstElement(); } } } } } return res; } private static void minWindowString(String s, String t) { int[] a = new int[128]; int[] b = new int[128]; for (int i = 0; i < t.length(); i++) { b[t.charAt(i)]++; } int count = 0; int left = 0; int minWindow = Integer.MAX_VALUE; for (int i = 0; i < s.length(); i++) { if (--b[s.charAt(i)] >= 0) { //1 count++; } while (count == t.length()) { if (i - left + 1 < minWindow) { minWindow = i - left + 1; } //如果 s.charAt(left) < 0, 则表明在1处, s的left位置出现一个多余的字符, 相对于t //如s ='aab', t = 'ab' // -1,0 if (++b[s.charAt(left)] > 0) { count--; } left++; } } } private static int sumOfTree(Tree tree, int start) { if (tree == null) { return 0; } int tmp = start + tree.data * 10; return sumOfTree(tree.left, tmp) + sumOfTree(tree.right, tmp); } }
C++
WINDOWS-1251
632
2.953125
3
[]
no_license
#include <iostream> #include "Vector.h" using namespace std; int main() { setlocale(LC_ALL, "Russian"); Vector a(5),b(10),c(10); cout << a << endl; cin >> a; cout <<" - " << a << endl; a[2] = 228; cout << a << endl; cout << "Vector b - " << b << endl; cout << "Vector b=a - " << (b=a) << endl; b + 100; c = b; cout << "Vector c=b+100 - " <<c << endl; cout << "Lenth A = " << a() << endl; cout << *(a.first()) << endl; Iterator I = a.first(); ++I; cout << *I << endl; for (I = a.first(); I != a.last(); ++I) { cout << *I << endl; } system("pause"); return 0; }
SQL
GB18030
590
2.703125
3
[]
no_license
delete from HtmlLabelIndex where id=126572 / delete from HtmlLabelInfo where indexid=126572 / INSERT INTO HtmlLabelIndex values(126572,'Ȩ޲鿴, ѱǿջػɾ') / INSERT INTO HtmlLabelInfo VALUES(126572,'Ȩ޲鿴, ѱǿջػɾ',7) / INSERT INTO HtmlLabelInfo VALUES(126572,'You do not have permission to view this workflow, it may have been forced to withdraw or delete!',8) / INSERT INTO HtmlLabelInfo VALUES(126572,'o޲鿴, ѱջػɾ',9) /
Python
UTF-8
226
2.9375
3
[]
no_license
#!/usr/bin/env python for i in [1,2,3,4,5,6]: print i, print "" for i in (1,2,3,4,5,6,7): print i, print "" for i in {1,2,3,4,5,6,7}: print i, print "" for i in {'a':1,'b':2,'c':3,'m':4}: print i, print ""
Java
UTF-8
793
1.914063
2
[]
no_license
package com.test.task; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @SpringBootApplication public class TaskApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(TaskApplication.class, args); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
JavaScript
UTF-8
3,937
2.953125
3
[ "ISC" ]
permissive
'use strict'; var Readable = require('stream').Readable; var util = require('util'); function AssimilationState(stream) { this.source = null; this.waiting = false; this.encoding = stream._readableState.encoding; } function extractThenMethod(x) { if (!x || typeof x !== 'object' && typeof x !== 'function') { return null; } var then = x.then; return typeof then === 'function' ? then : null; } function Thenstream(thenable) { if (!(this instanceof Thenstream)) { return new Thenstream(thenable); } Readable.call(this); this._assimilationState = new AssimilationState(this); var self = this; function emitError(error) { process.nextTick(function() { self.emit('error', error); }); } var then = null; try { then = extractThenMethod(thenable); } catch (error) { emitError(error); return; } if (!then) { emitError(new TypeError('Expected thenable.')); return; } var once = true; try { then.call(thenable, function(source) { if (once) { once = false; try { // Note: `source` is not necessarily set asynchronously. self._setSource(source); } catch (error) { emitError(error); } } }, function(reason) { if (once) { once = false; emitError(reason); } }); } catch (error) { if (once) { once = false; emitError(error); } } } module.exports = Thenstream; util.inherits(Thenstream, Readable); Thenstream.prototype.setEncoding = function(encoding) { this._assimilationState.encoding = encoding; Readable.prototype.setEncoding.call(this, encoding); }; Thenstream.prototype._read = function() { if (this._assimilationState.source) { this._pushChunks(); } else { this._assimilationState.waiting = true; } }; Thenstream.prototype._setSource = function(source) { var self = this; // If it walks like a duck… if ( !source || typeof source !== 'object' || !source._readableState || typeof source._readableState !== 'object' || typeof source.read !== 'function' ) { throw new TypeError('Thenable did not fulfill with a usable stream.'); } // highWaterMark and objectMode are not configurable in the Thenstream; // we inherit them from the source stream. var sourceState = source._readableState; var readableState = self._readableState; readableState.highWaterMark = sourceState.highWaterMark; readableState.objectMode = sourceState.objectMode; // Only inherit encoding if it hasn't been set explicitly. if ( sourceState.encoding !== null && self._assimilationState.encoding === null ) { self.setEncoding(sourceState.encoding); } // Re-emit close and error events. source.on('close', self.emit.bind(self, 'close')); source.on('error', self.emit.bind(self, 'error')); // Update state self._assimilationState.source = source; // Push more chunks when data becomes available. function onReadable() { if (self._assimilationState.waiting) { self._assimilationState.waiting = false; self._pushChunks(); } } source.on('readable', onReadable); source.once('end', function() { source.removeListener('readable', onReadable); if (self._assimilationState.waiting) { self._assimilationState.waiting = false; self.push(null); } }); // Push chunks if reading started before the source was set. if (self._assimilationState.waiting) { self._assimilationState.waiting = false; self._pushChunks(); } }; Thenstream.prototype._pushChunks = function() { var chunk, pushAnother; do { chunk = this._assimilationState.source.read(); if (chunk === null) { this._assimilationState.waiting = true; pushAnother = false; } else { pushAnother = (this.push(chunk) !== false); } } while (pushAnother); };
SQL
UTF-8
193
2.875
3
[]
no_license
USE employees; SELECT CONCAT(first_name, ' ', last_name)FROM employees WHERE first_name = 'Maya' ORDER BY last_name; SELECT DAYOFMONTH(hire_date) FROM employees WHERE first_name = 'Maya';
TypeScript
UTF-8
3,292
2.640625
3
[]
no_license
import CustomerStatementsReport from "../model/customerStatementsReport"; import { parse } from '@fast-csv/parse'; import CustomerStatement from "../model/customerStatement"; import CustomerStatementReportItem from "../model/customerStatementReportItem"; import {isValidIBAN} from "ibantools"; export default class CustomerStatementCsvValidator { async validateCustomerStatementCsvContent(content: string, key: string): Promise<CustomerStatementsReport> { type StatementRow = { transactionReference: string; accountNumber: string; startBalance: number; mutation: number; description: string; endBalance: number; }; const reportItems: Array<CustomerStatementReportItem> = new Array<CustomerStatementReportItem>(); const stream = parse<StatementRow, CustomerStatement>({ headers: true }) .transform( (data: StatementRow): CustomerStatement => ({ transactionReference: data.transactionReference, accountNumber: data.accountNumber, startBalance: data.startBalance, mutation: data.mutation, description: data.description, endBalance: data.endBalance }), ) .on('error', error => { console.error(error); reportItems.push(new CustomerStatementReportItem(undefined, undefined, [`Failed to parse csv file records`], "FAILED")); }) .on('data', (row: CustomerStatement) => { const errors: Array<string> = new Array<string>(); if (!row.transactionReference) { errors.push("Transaction reference missing"); } else if (!row.accountNumber || !isValidIBAN(row.accountNumber)) { errors.push("Invalid account number"); } else if (!row.startBalance || isNaN(row.startBalance)) { errors.push("Start Balance invalid"); } else if (!row.mutation || isNaN(row.mutation)) { errors.push("Mutation invalid"); } else if (!row.endBalance || isNaN(row.endBalance) || row.startBalance + row.mutation !== row.endBalance) { errors.push("EndBalance invalid"); } reportItems.push(new CustomerStatementReportItem(row, row.transactionReference, errors, errors.length > 0 ? "FAIL":"SUCCESS")); console.log(JSON.stringify(row)) }) .on('end', (rowCount: number) => { console.log(`Parsed ${rowCount} rows`) }); stream.write(content); stream.end(); reportItems.forEach(it => { if (reportItems.filter(x => x.transactionReference == it.transactionReference).length > 1) { if ( it.errorMessages === undefined ) { it.errorMessages = new Array<string>(); } it.errorMessages.push("Transaction is not unique") it.status = "FAIL"; } }); return new CustomerStatementsReport(key, reportItems); } }
Go
UTF-8
856
2.953125
3
[ "Apache-2.0" ]
permissive
package state import ( "github.com/stretchr/testify/assert" "testing" ) func TestValue_InitalStateNotChanged(t *testing.T) { s := CreateState(nil, "fuel", 100) assert.Equal(t, 100, s.Get()) assert.False(t, s.Changed()) } func TestUninitializedValue_StateChanged(t *testing.T) { s := CreateState(nil, "fuel", 100) s.Set(101) assert.Equal(t, 101, s.Get()) assert.False(t, s.Changed()) } func TestValue_StateChanged(t *testing.T) { s := CreateState(nil, "fuel", 100) s.initialize() s.Set(101) assert.Equal(t, 101, s.Get()) assert.True(t, s.Changed()) } func TestValue_StateChangedReset(t *testing.T) { s := CreateState(nil, "fuel", 100) s.Set(101) s.reset() assert.False(t, s.Changed()) } func TestValue_StateInitialIsNotChanged(t *testing.T) { s := CreateState(nil, "fuel", 100) s.Set(101) assert.Equal(t, 100, s.Initial()) }
JavaScript
UTF-8
450
2.59375
3
[]
no_license
function formValidation(formData) { const expected_params = ["food", "time", "location", "number_of_ducks", "food_amount"]; for ( const key of expected_params) { if (! formData.hasOwnProperty(key) || formData[key] == "") { let key_friendly = key.split("_").join(" "); return {valid: false, message: `Missing information: ${key_friendly}`}; } } return {valid: true}; } export {formValidation};
TypeScript
UTF-8
15,699
3.171875
3
[ "MIT" ]
permissive
import {AbstractValidator, ValidationResult} from "./"; import {Severity, ValidationFailure} from "./shared"; class TestPerson { name?: string; xpInYears?: number; address?: TestAddress; email?: string; dateOfBirth?: Date; } class TestAddress { street: string; number?: string; city: string; postcode: string; } class FailureCaptor { validationFailure: ValidationFailure; } let failureCaptor = new FailureCaptor(); class TestValidator extends AbstractValidator<TestPerson> { constructor() { super(); this.validateIfString((input: TestPerson) => input.name) .isNotEmpty().hasLengthBetween(3, 20).isAlpha().withFailureCode("N1"); this.validateIfNumber((input: TestPerson) => input.xpInYears) .isGreaterThanOrEqual(3).isLessThanOrEqual(13).withSeverity(Severity.INFO); this.validateIfString(input => input.email).isEmail().unless(input => !input.address); this.validateIfDate(input => input.dateOfBirth).isSameOrAfter(new Date(2000, 0, 1)); this.validateIf((input: TestPerson) => { return input.address; }) .fulfills(address => { if (address) { return address.postcode !== "55555" && address.street !== "Le Place"; } else { return true; } }) .withFailureMessage("address is not allowed") .withSeverity(Severity.WARNING) .onFailure((failure) => { failureCaptor.validationFailure = failure; }); } } describe("AbstractValidator", () => { let validator: TestValidator; let person: TestPerson; beforeEach(() => { failureCaptor = new FailureCaptor(); validator = new TestValidator(); person = new TestPerson(); person.name = "Franz"; person.xpInYears = 8; person.dateOfBirth = new Date(2001, 2, 2); person.email = "mail@example.com"; person.address = { street: "Le other Place", city: "MyOtherTown", postcode: "22222" }; }); describe("TestValidator.validate()", () => { it("should return a positive validation result for a valid instance", () => { let result: ValidationResult = validator.validate(person); expect(result.isValid()).toBeTruthy(); }); it("should return a negative validation result if name is empty", () => { person.name = ""; let result: ValidationResult = validator.validate(person); expect(result.isValid()).toBeFalsy(); }); it("should return a proper failure-object if name is is less than 3 characters long", () => { person.name = "DJ"; let failure: ValidationFailure = validator.validate(person).getFailures()[0]; expect(failure.target).toBe(person); expect(failure.attemptedValue).toBe("DJ"); expect(failure.propertyName).toBe("name"); expect(failure.code).toBe("N1"); expect(failure.severity).toBe(Severity[Severity.ERROR]); expect(failure.message).toBe("name is invalid"); }); it("should return a negative validation result if address is forbidden", () => { person.address = { street: "Le Place", city: "MyTown", postcode: "55555" }; let result: ValidationResult = validator.validate(person); expect(result.isValid()).toBeFalsy(); }); it("should return a proper failure-object if address is forbidden", () => { person.address = { street: "Le Place", city: "MyTown", postcode: "55555" }; let failure: ValidationFailure = validator.validate(person).getFailures()[0]; expect(failure.target).toBe(person); expect(failure.propertyName).toBe("address"); expect(failure.code).not.toBeDefined(); expect(failure.severity).toBe(Severity[Severity.WARNING]); expect(failure.message).toBe("address is not allowed"); }); it("should return one failure for every validation that failed", () => { person.name = undefined; person.email = undefined; person.dateOfBirth = new Date(1999, 0, 1); person.address = { street: "Le Place", city: "MyTown", postcode: "55555" }; let result: ValidationResult = validator.validate(person); expect(result.getFailures().length).toBe(4); }); it("should trigger callback on failure", () => { person.address = { street: "Le Place", city: "MyTown", postcode: "55555" }; validator.validate(person); expect(failureCaptor.validationFailure).not.toBeNull(); expect(failureCaptor.validationFailure.target).toBe(person); expect(failureCaptor.validationFailure.propertyName).toBe("address"); }); it("should return positive validation result if invalid value is not validated due to a specified condition", () => { person.email = undefined; person.address = undefined; let result: ValidationResult = validator.validate(person); expect(result.isValid()).toBeTruthy(); }); it("should return negative validation result if invalid value is validated because of a specified condition", () => { person.email = undefined; person.address = { street: "Le other Place", city: "MyOtherTown", postcode: "22222" }; let result: ValidationResult = validator.validate(person); expect(result.isValid()).toBeFalsy(); }); }); describe("TestValidator.validateAsync()", () => { it("should return a positive validation result through a Promise", (done) => { let promise: Promise<ValidationResult> = validator.validateAsync(person); promise.then((result: ValidationResult) => { expect(result.isValid()).toBeTruthy(); done(); }); }); it("should return a negative validation result through a Promise", (done) => { person.name = undefined; let promise: Promise<ValidationResult> = validator.validateAsync(person); promise.then((result: ValidationResult) => { expect(result.isValid()).toBeFalsy(); done(); }); }); }); }); class TestAddressbook { contacts: TestPerson[]; addresses: any; } class AddressbookValidator extends AbstractValidator<TestAddressbook> { constructor() { super(); this.validateIfAny(addressbook => addressbook.addresses).isArray(); this.validateIfEach(addressbook => addressbook.contacts).isNotNull(); } } describe("AddressbookValidator", () => { let validator: AddressbookValidator; let addressbook: TestAddressbook; let person1: TestPerson; let person2: TestPerson; beforeEach(() => { validator = new AddressbookValidator(); addressbook = new TestAddressbook(); person1 = new TestPerson(); person2 = new TestPerson(); addressbook.contacts = [person1, person2]; addressbook.addresses = []; }); describe("validate()", () => { it("should return a positive result if none of the elements in the given array is null", () => { let result = validator.validate(addressbook); expect(result.isValid()).toBeTruthy(); }); it("should return a negative result if addresses is not an array", () => { addressbook.addresses = new Set(); let result = validator.validate(addressbook); expect(result.isValid()).toBeFalsy(); }); }); }); class CollectionPropClass { names: string[]; dates: Date[]; numbers: number[]; people: TestPerson[]; anything: any[]; } class CollectionValidator extends AbstractValidator<CollectionPropClass> { constructor() { super(); this.validateIfEachDate(i => i.dates).isAfter(new Date(2000, 0, 1)); this.validateIfEachString(i => i.names).hasMinLength(2); this.validateIfEachNumber(i => i.numbers).isGreaterThan(0); this.validateIfEach(i => i.people).isDefined(); this.validateIfEachAny(i => i.anything).isString(); } } describe("CollectionValidator", () => { let validator: CollectionValidator; let testInstance: CollectionPropClass; beforeEach(() => { testInstance = new CollectionPropClass(); testInstance.names = ["foo"]; testInstance.dates = [new Date(2001, 0, 1)]; testInstance.numbers = [1]; testInstance.people = [new TestPerson()]; testInstance.anything = ["foobar"]; validator = new CollectionValidator(); }); describe("validate()", () => { it("should return positive result if everything is fine", () => { const result = validator.validate(testInstance); expect(result.isValid()).toBe(true); }); it("should return positive result if everything is fine - async", (done) => { validator.validateAsync(testInstance).then(result => { expect(result.isValid()).toBe(true); done(); }).catch(reason => { fail(reason); done(); }); }); it("should return negative result if a name is too short", () => { testInstance.names.push("X"); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if a date is too old", () => { testInstance.dates.push(new Date(1999, 0, 1)); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if a number is negative", () => { testInstance.numbers.push(-1); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if anything is not a string", () => { testInstance.anything.push(0); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); }); }); class IterablePropClass { anArray: number[]; aSet: Set<string>; aMap: Map<string, string>; aReadonlyArray: ReadonlyArray<boolean>; // aReadonlySet: ReadonlySet<number>; aReadonlySet: Set<number>; // aReadonlyMap: ReadonlyMap<string, string>; aReadonlyMap: Map<string, string>; iterableWithoutSize: Iterable<number>; } class IterableValidator extends AbstractValidator<IterablePropClass> { constructor() { super(); this.validateIfIterable(i => i.anArray).isEmpty(); this.validateIfIterable(i => i.aSet).isNotEmpty(); this.validateIfIterable(i => i.aMap).hasNumberOfElements(1); this.validateIfIterable(i => i.aReadonlyArray).hasMinNumberOfElements(1); this.validateIfIterable(i => i.aReadonlySet).hasMaxNumberOfElements(2); this.validateIfIterable(i => i.aReadonlyMap).hasNumberOfElementsBetween(2, 4); this.validateIfIterable(i => i.iterableWithoutSize).contains(2); this.validateIfIterable(i => i.iterableWithoutSize).doesNotContain(3); } } describe("IterableValidator", () => { let validator: IterableValidator; let testInstance: IterablePropClass; beforeEach(() => { validator = new IterableValidator(); testInstance = new IterablePropClass(); testInstance.anArray = []; testInstance.aSet = new Set("foo"); testInstance.aMap = new Map([["foo", "bar"]]); testInstance.aReadonlyArray = [true, false]; testInstance.aReadonlySet = new Set([1, 2]); testInstance.aReadonlyMap = new Map([["foo", "bar"], ["bar", "foo"], ["foobar", "foobar"]]); testInstance.iterableWithoutSize = <Iterable<number>>{}; testInstance.iterableWithoutSize[Symbol.iterator] = function* gen() { yield* [1, 2]; }; }); describe("validate()", () => { it("should return positive result if everything is fine", () => { const result = validator.validate(testInstance); expect(result.isValid()).toBe(true); }); it("should return positive result if everything is fine - async", (done) => { validator.validateAsync(testInstance).then(result => { expect(result.isValid()).toBe(true); done(); }).catch(reason => { fail(reason); done(); }); }); it("should return negative result if anArray is not empty", () => { testInstance.anArray.push(1); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if aSet is empty", () => { testInstance.aSet = new Set(); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if aMap has not exactly one element", () => { testInstance.aMap = new Map([["foo", "bar"], ["bar", "foo"]]); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if aReadonlyArray has not at least one element", () => { testInstance.aReadonlyArray = []; const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if aReadonlySet has more than two elements", () => { testInstance.aReadonlySet = new Set([1, 2, 3]); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if aReadonlyMap has less than two or more than four elements", () => { testInstance.aReadonlyMap = new Map([["foo", "bar"]]); const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if iterableWithoutSize does not contain a 2", () => { testInstance.iterableWithoutSize = <Iterable<number>>{}; testInstance.iterableWithoutSize[Symbol.iterator] = function* gen() { yield* [0, 1]; }; const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); it("should return negative result if iterableWithoutSize does contain a 3", () => { testInstance.iterableWithoutSize = <Iterable<number>>{}; testInstance.iterableWithoutSize[Symbol.iterator] = function* gen() { yield* [1, 2, 3]; }; const result = validator.validate(testInstance); expect(result.isValid()).toBe(false); }); }); });
Java
UTF-8
185
1.984375
2
[]
no_license
package shared.exceptions; public class CannotCollectResourcesException extends Exception { public CannotCollectResourcesException(String message) { super(message); } }
Java
UTF-8
824
2.15625
2
[]
no_license
package service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import mapper.UserMapper; import pojo.User; import service.UserService; @Component("userService") public class UserServiceImpl implements UserService{ @Autowired UserMapper mapper; @Override public List<User> queryAll() { return mapper.queryAll(); } @Override public List<User> queryList(List<Integer> list) { // TODO Auto-generated method stub return mapper.queryList(list); } @Override public List<User> queryOne(int id) { // TODO Auto-generated method stub return mapper.queryOne(id); } @Override public void insert(User user) { // TODO Auto-generated method stub mapper.insert(user); } }
Markdown
UTF-8
1,533
3
3
[]
no_license
## Notice boxes You can make `info`, `warning` and `alert` boxes like this. Examples of what they look like can be found here: https://squidfunk.github.io/mkdocs-material/getting-started/ **Info box** ``` !!! info "Call for Contributions: Add languages/translations to Material" Help translate Material into more languages - it's just **one click** and takes approximately **2 minutes**: [click here](http://bit.ly/2EbzFc8) ``` <br> **Warning** ``` !!! warning "Installation on macOS" When you're running the pre-installed version of Python on macOS, `pip` tries to install packages in a folder for which your user might not have the adequate permissions. There are two possible solutions for this: 1. **Installing in user space** (recommended): Provide the `--user` flag to the install command and `pip` will install the package in a user-site location. This is the recommended way. 2. **Switching to a homebrewed Python**: Upgrade your Python installation to a self-contained solution by installing Python with Homebrew. This should eliminate a lot of problems you may be having with `pip`. ``` <br> **Failure** ``` !!! failure "Error: unrecognized theme 'material'" If you run into this error, the most common reason is that you installed MkDocs through some package manager (e.g. Homebrew or `apt-get`) and the Material theme through `pip`, so both packages end up in different locations. MkDocs only checks its install location for themes. ```
PHP
UTF-8
3,578
2.75
3
[]
no_license
<?php namespace App\Entity; use App\Repository\SpeciesRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity(repositoryClass=SpeciesRepository::class) */ class Species { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="species") * @ORM\JoinColumn(nullable=false) * @Assert\Type("App\Entity\User") */ private $user; /** * @ORM\Column(type="datetime") */ private $created_at; /** * @ORM\OneToMany(targetEntity=SpeciesFeature::class, mappedBy="species") */ private $speciesFeatures; /** * @ORM\Column(type="string", length=50) * @Assert\NotBlank * @Assert\Type("string") */ private $genus; /** * @ORM\Column(type="string", length=50) * @Assert\NotBlank * @Assert\Type("string") */ private $species; /** * @ORM\Column(type="string", length=60, nullable=true) */ private $variety; public function __construct() { $this->speciesFeatures = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): self { $this->user = $user; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->created_at; } public function setCreatedAt(\DateTimeInterface $created_at): self { $this->created_at = $created_at; return $this; } /** * @return Collection|SpeciesFeature[] */ public function getSpeciesFeatures(): Collection { return $this->speciesFeatures; } public function addSpeciesFeature(SpeciesFeature $speciesFeature): self { if (!$this->speciesFeatures->contains($speciesFeature)) { $this->speciesFeatures[] = $speciesFeature; $speciesFeature->setSpecies($this); } return $this; } public function removeSpeciesFeature(SpeciesFeature $speciesFeature): self { if ($this->speciesFeatures->contains($speciesFeature)) { $this->speciesFeatures->removeElement($speciesFeature); // set the owning side to null (unless already changed) if ($speciesFeature->getSpecies() === $this) { $speciesFeature->setSpecies(null); } } return $this; } public function getGenus(): ?string { return $this->genus; } public function setGenus(string $genus): self { $this->genus = $genus; return $this; } public function getSpecies(): ?string { return $this->species; } public function setSpecies(string $species): self { $this->species = $species; return $this; } public function getVariety(): ?string { return $this->variety; } public function setVariety(?string $variety): self { $this->variety = $variety; return $this; } public function __toString() { $variety = $this->getVariety() == '' ? '' : ' (' . $this->getVariety() . ')'; return $this->getGenus() . ' ' . $this->getSpecies() . $variety; } }
JavaScript
UTF-8
381
3.921875
4
[]
no_license
function increment(number) { let carry = 1; for (let i = number.length - 1; i >= 0; i--) { if (number[i] + 1 === 10) { number[i] = 0; carry = 1; } else { number[i]++; carry = 0; break; } } if (carry) number.unshift(carry); return number; } console.log(increment([9, 9])); // Time complexity: O(n) // Space complexity : 0(1)
C#
UTF-8
3,293
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Planner.Data; using Planner.Dto.Models; using Planner.Models; using Planner.Services.Contract; using Planner.Services.Contract.Dto; namespace Planner.Controllers { [Route("api/[controller]")] [ApiController] public class SkillsController : ControllerBase { private readonly PlannerDbContext _context; private readonly ISkillService _skillService; private readonly IMapper _mapper; public SkillsController(PlannerDbContext context, IMapper mapper, ISkillService skillService) { _context = context; _skillService = skillService; _mapper = mapper; } // GET: api/Skills [HttpGet] public async Task<List<SkillDto>> GetAlls() { return await _skillService.GetAll(); } // GET: api/Products/5 [HttpGet("{id}")] public async Task<ActionResult> GetById(int id) { var skill = await _skillService.GetById(id); if (skill == null) { return NotFound(); } return new JsonResult(skill); } // PUT: api/Products/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPut("{id}")] public async Task<IActionResult> PutSkill(int id, [FromBody]SkillModel model) { if (id != model.Id ) { return BadRequest(); } var skill = _mapper.Map<SkillModel, Skill>(model); _skillService.Update(skill); try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SkillExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Products // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPost] public async Task<ActionResult<Skill>> PostSkill([FromBody]SkillModel model) { var skill = _mapper.Map<SkillModel, Skill>(model); await _skillService.Add(skill); return CreatedAtAction("GetById", new { id = skill.Id }, skill); } // DELETE: api/Products/5 [HttpDelete("{id}")] public async Task<ActionResult<Skill>> DeleteSkill(int id) { var status = await _skillService.Delete(id); if (status == null) { return NotFound(); } return new JsonResult(status); } private bool SkillExists(int id) { return _context.Skills.Any(e => e.Id == id); } } }
Java
UTF-8
458
2.5
2
[]
no_license
package com.globeshanghai.backend.exceptions; /** * Created by stijnergeerts on 23/04/17. */ public class UserNotFoundException extends RuntimeException { /** * This exception is thrown when no content is found. * @param id The userId that is not linked to a {@link com.globeshanghai.backend.dom.user.User} */ public UserNotFoundException(String id) { super(String.format("No user entry found with id: <%s>", id)); } }
Markdown
UTF-8
5,772
2.75
3
[]
no_license
# Résumé Le projet de compilation a pour but la réalisation d'un compilateur d'un mini langage appelé pour l'occasion myC vers du code C à 3 adresses. Le langage source proposé, un mini langage C, devra donc être compilé en C à 3 adresses. Il a été réalisé par Reda CHAGUER et Houssam BAHHOU, élèves à l'Enseirb-Matmeca en deuxième année informatique. (Groupe 1) # Pré-requis Afin de faire fonctionner ce projet vous devez posséder les packages suivants : - make - gcc - flex - bison # Dossiers et contenu Le projet s'organise de la sorte : - `src/` : sources générant le compilateur `lang` * `Attribute.c` et `Attribute.h` : permet de gérer les attributs dans l'analyse de types et noms. * `Table_des_chaines.c` et `Table_des_chaines.h` : permet de récupérer les noms lors de l'analyse de noms * `Table_des_symboles.c` et `Table_des_symboles.h` : permet de générer des éléments dans la table des symboles regroupant toutes les variables attributs créés et garder en mémoire leur valeur, type, ... sous forme de liste chaînée * `lang.y` : syntaxe du compilateur `lang` * `lang.l` : lexique de compilateur `lang` - `tst/` : fichiers tests du compilateur `lang` * `funct_without_params.myc` : fichier pour tester la définition et l'appel aux fonctions sans paramètres * `func_with_params.myc` : fichier pour tester la définition et l'appel aux fonctions avec paramètres * `fibo.myc` : fichier pour tester la définition et l'appel aux fonctions récursives * `if_else.myc / while.myc / while_if.myc` : fichiers pour tester les structures de contrôles classiques (conditionelles et boucles) * `z_affect_pointer.myc` : fichier pour tester l'affectation pointeur (Le code est correct mais le grammaire ne permet pas d'initialiser des pointeurs, on obtient un fichier.c qui donne un seg fault pendant son éxecution ce qui est normal), le répértoire `/affect_pointer_avec_malloc` contient les fichiers `.c/h` corréspendants avec une intialisation avec malloc. * `MOINS_pointer.myc / PLUS_pointer.myc` : fichier pour tester les opérations arithmétiques sur les pointeurs * A l'intérieur de ces fichiers on teste aussi le mécanisme de déclarations explicite des variables, les expresssions arithmétiques arbitraires de type calculatrice et lectures ou écritures mémoires via des affectations avec variables utilisateurs - `Makefile` - `compil.sh` : script shell permettant de générer le compilateur s'il n'éxiste pas et compiler le fichier `.myc` donné en argument en `.c` et `.h` - `preC.sh` : script shell permettant de générer le code précompilé. (lang) - `README.md` # Compilation et exécution Afin de pouvoir compiler notre programme et l'utiliser, plusieurs règles du `Makefile` peuvent être utiles : - `make clean` : permet de nettoyer avant de compiler tous les fichiers produits durant la compilation - `make` : compiler tous les sources permettant de créer le compilateur `lang` - `make test` : compiler les fichier `tst/*.myc` avec notre compilateur et générer les fichiers `.c` et `.h` correspondants, et ensuite éxecuter tous les fichiers `.c` générés. - `make working_affec` : permet de compiler les fichiers `.c/h` contenus dans le répértoire `/affect_pointer_avec_malloc` Cependant, nous avons mis en place un script permettant d'automatiser toutes ces étapes, le script `compil.sh`. En exécutant ce script avec la commande `./compil.sh <fichier.myc>`, il va effectuer les actions suivantes : - compiler les sources avec `make ` si elles ne sont pas déjà compilées - vérifier que le dossier `build` a bien été crée - compiler avec notre compilateur `lang` le fichier donné en paramètre - compiler avec `gcc` les fichiers `.h` et `.c` qui ont été générés par notre compilateur `lang` Si on veut forcer la recompilation des fichiers sources, on peut utiliser l'option `-r` avec le script `preC.sh`. # Travail demandé Le projet devra assurer : - l'analyse des noms : les variables (et fonctions) utilisées sont-elles déclarées - l'analyse des types : les opérations effectués sont-elles bien typées - la production de code à trois addresses Le compilateur `lang` produit vise à couvrir quelques éléments clès de la compilation. Il comprend notamment: - un mécanisme de déclarations explicites de variables - des expressions arithmétiques arbitraire de type calculatrice - des lectures ou écritures mémoires via des affectations avec variable utilisateur - des structures de contrôles classiques (conditionelles et boucles) - un mécanisme de typage comprenant notamment `int` et `int *` - des lectures ou écritures mémoires via des pointeurs - définitions et appels de fonctions récursives - `N.B.` une pile sera utilisée pour gérer les variables locales et les arguments des fonctions. # Travail effectué Nous avons réussi à effectuer toutes les fonctionnalités du projet: - un mécanisme de déclarations explicites de variables **FONCTIONNEL** - des expressions arithmétiques arbitraire de type calculatrice **FONCTIONNEL** - des lectures ou écritures mémoires via des affectations avec variable utilisateur ou pointeurs **FONCTIONNEL** - des structures de contrôles classiques (conditionelles et boucles) **FONCTIONNEL** - un mécanisme de typage comprenant notamment `int` et `int *` **FONCTIONNEL** - des lectures ou écritures mémoires via des pointeurs **FONCTIONNEL** - définitions et appels de fonctions récursives **FONCTIONNEL** - `une pile pour la géstion des variables locales et les arguments des fonctions. **FONCTIONNEL**
PHP
UTF-8
1,114
2.65625
3
[]
no_license
<?php use Illuminate\Database\Seeder; use App\User; use App\Post; use App\Comment; class CommentSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $faker = Faker\Factory::create(); $limit = 10; $users = User::all(); $posts = Post::all(); for ($i = 0; $i < $limit; $i++) { $comment = new Comment(); $comment->text = $faker->sentence(4); $users[rand(0, count($users)-1)]->comments()->save($comment); $posts[rand(0, count($posts)-1)]->comments()->save($comment); } $comments = Comment::all(); for ($i=0;$i<count($comments);$i++) { if (rand(0, 1)==1) { $reply = new Comment(); $reply->text = $faker->sentence(4); $comment = $comments[$i]; $reply->user_id = $users[rand(0, count($users)-1)]->id; $reply->parent_id = $comment->id; $comments[$i]->replies()->save($reply); } } } }
Java
UTF-8
1,083
1.992188
2
[]
no_license
package ms55.moreplates.common.plugin; import static ms55.moreplates.common.enumeration.EnumMaterials.BLACK_IRON; import static ms55.moreplates.common.enumeration.EnumMaterials.CRYSTALTINE; import static ms55.moreplates.common.enumeration.EnumMaterials.ENDER; import static ms55.moreplates.common.enumeration.EnumMaterials.ENHANCED_ENDER; import static ms55.moreplates.common.enumeration.EnumMaterials.REDSTONE_INGOT; import static ms55.moreplates.common.enumeration.EnumMaterials.THE_ULTIMATE; import ms55.moreplates.common.plugin.core.Plugin; import ms55.moreplates.common.plugin.helper.PluginHelper; @Plugin(modid = PluginExtendedCrafting.modid, modname = PluginExtendedCrafting.modname) public class PluginExtendedCrafting extends PluginHelper { public static final String modid = "extendedcrafting"; public static final String modname = "Extended Crafting"; @Plugin.registry public static void registry() { reg2(BLACK_IRON); reg2(CRYSTALTINE); reg2(ENDER); reg2(ENHANCED_ENDER); reg2(REDSTONE_INGOT); reg2(THE_ULTIMATE); } }
Rust
UTF-8
398
3.890625
4
[]
no_license
fn main() { let arr = [1, 2, 3, 4, 5]; let arr_type: [i32; 5] = [1, 2, 3, 4, 5]; // same thing as above // element; length let arr_default = [2; 400] // a array with default values in it // arr[2] // 3 // arr[1] // 2 // looping and array for n in arr.iter() { println!("{}", n); } for i in 0..arr.len() { println!("index {}", i); } }
Python
UTF-8
3,294
3.84375
4
[]
no_license
import unittest # naive solution- take product between each number # and every other number # def get_products_of_all_ints_except_at_index(nums): # if len(nums) == 0 or len(nums) == 1: # raise Exception("Invalid input!") # products = [] # for i in range(len(nums)): # product = 1 # for j in range(len(nums)): # if i != j: # product *= nums[j] # products.append(product) # # return products # # print (get_products_of_all_ints_except_at_index([1, 7, 3, 4])) # print (get_products_of_all_ints_except_at_index([1, 2, 3])) # https://stackoverflow.com/questions/2104782/returning-the-product-of-a-list # def get_products_of_all_ints_except_at_index(nums): # final_array = [] # product = reduce(lambda x, y: x * y, nums) # # for num in nums: # final_array.append(product / num) # return final_array # # print (get_products_of_all_ints_except_at_index([1, 7, 3, 4])) # print (get_products_of_all_ints_except_at_index([1, 2, 3])) # build an array containing the product of all nums to the left of a given num # build an array containing the product of all nums to the right of a given num def get_products_of_all_ints_except_at_index(nums): if len(nums) == 0 or len(nums) == 1: raise Exception("Invalid input!") product = 1 left_arr = [1] * len(nums) for i in range(len(nums)): left_arr[i] = (product) product *= nums[i] product = 1 right_arr = [1] * len(nums) for j in range(len(nums) - 1, -1, -1): right_arr[j] = (product) product *= nums[j] final_arr = [] for i in range(len(nums)): final_arr.append(left_arr[i] * right_arr[i]) return final_arr # print (get_products_of_all_ints_except_at_index([1, 7, 3, 4])) class Test(unittest.TestCase): def test_small_list(self): actual = get_products_of_all_ints_except_at_index([1, 2, 3]) expected = [6, 3, 2] self.assertEqual(actual, expected) def test_longer_list(self): actual = get_products_of_all_ints_except_at_index([8, 2, 4, 3, 1, 5]) expected = [120, 480, 240, 320, 960, 192] self.assertEqual(actual, expected) def test_list_has_one_zero(self): actual = get_products_of_all_ints_except_at_index([6, 2, 0, 3]) expected = [0, 0, 36, 0] self.assertEqual(actual, expected) def test_list_has_two_zeros(self): actual = get_products_of_all_ints_except_at_index([4, 0, 9, 1, 0]) expected = [0, 0, 0, 0, 0] self.assertEqual(actual, expected) def test_one_negative_number(self): actual = get_products_of_all_ints_except_at_index([-3, 8, 4]) expected = [32, -12, -24] self.assertEqual(actual, expected) def test_all_negative_numbers(self): actual = get_products_of_all_ints_except_at_index([-7, -1, -4, -2]) expected = [-8, -56, -14, -28] self.assertEqual(actual, expected) def test_error_with_empty_list(self): with self.assertRaises(Exception): get_products_of_all_ints_except_at_index([]) def test_error_with_one_number(self): with self.assertRaises(Exception): get_products_of_all_ints_except_at_index([1]) unittest.main(verbosity=2)
Python
UTF-8
2,066
2.78125
3
[ "MIT" ]
permissive
import pandas as pd from matchreporter.analysis.events import is_origin_of_play_event, is_outcome_of_play_event, \ is_transition_play_event, is_middle_play_event, transpose_outcome from matchreporter.analysis.play import get_play CLOCK = 'clock' PLAYID = 'playid' KPI = 'kpi' REDUCED_ORIGIN = 'reduced_origin' REDUCED_OUTCOME = 'reduced_outcome' def analyse_plays(row_list): play_list = create_playlist(row_list) data_frame = convert_playlist_to_dataframe(play_list) data_frame = transform_dataframe(data_frame) return data_frame def transform_dataframe(data_frame): data_frame = transform_outcomes(data_frame) data_frame = transform_origins(data_frame) return data_frame def transform_outcomes(dataframe): dataframe[REDUCED_OUTCOME] = dataframe.outcome.apply(lambda row: transpose_outcome(row)) return dataframe def transform_origins(dataframe): dataframe[REDUCED_ORIGIN] = dataframe.origin.apply(lambda row: transpose_outcome(row)) return dataframe def convert_playlist_to_dataframe(play_list): data_frame = pd.DataFrame([p.__dict__ for p in play_list]) return data_frame def create_playlist(row_list): listofplays = [] play = get_play() for _, row in enumerate(row_list): if is_origin_of_play_event(row): play = set_origin(play, row) elif is_outcome_of_play_event(row): set_outcome(listofplays, play, row) elif is_transition_play_event(row): set_outcome(listofplays, play, row) play = set_origin(play, row) elif is_middle_play_event(row): play.add_event(row) else: if row[KPI] != CLOCK: print("ERROR: Unknown event: ", row[KPI], " : ", row) play_dict = {PLAYID: play.playid} row.update(play_dict) return listofplays def set_origin(play, row): play = get_play() play.add_origin_event(row) return play def set_outcome(listofplays, play, row): play.add_outcome_event(row) listofplays.append(play)
Markdown
UTF-8
9,341
3.375
3
[]
no_license
--- title: "Basics of Technical Analysis" date: 2021-09-04T18:45:47+08:00 draft: false categories: - Trading tags: - technical analysis --- In this entry, we'll be talking about the fundamentals of reading the trend of a given market. By understanding the trend of a market, we gain knowledge of its behaviour. This may help us predict what the possible next direction of the market prices will be. Is it going up, or down? In this article, I will present some useful tools and indicators available to us in the Binance platform. Note that this may be available to other major exchanges as well. ## Chart Views There are two useful chart types that I usually use, the *Line Chart* and the *Candlestick Chart*. The line chart looks something as shown below, <img src="/static/line-chart.png" loading="lazy" /> while the candlestick chart is something like this. <img src="/static/candlestick-chart.png" loading="lazy" /> The example above shows the chart for Bitcoin at the time of this writing. If you just want the summarized overview of the market trend, you may want to go with the line chart, however, if you want a more detailed presentation, maybe the candlestick chart is best for you, and this is where I am looking for most of the time. To get the line chart on Binance chart, just tap or click on the `Time` button at the top left of the chart and if you want the candlestick chart, just select the intervals at the right of the `Time` button (in the case above, the selected one is `15m`). ## Candlestick Candlesticks can be seen in charts as replacement for the plain line charts. A candlestick gives us more detailed information about a particular time frame. <img src="/static/basic-ta/candlestick.png" loading="lazy" /> If you selected a 15m time frame, the above is a representation of that time frame. What happens is that at the start of 15 minutes, the candlestick starts at the `Open (O)` marker. Then within the 15 minutes time, the price goes as high as the `High (H)` marker and goes down to `Low (L)` marker. After that, before going to the next time frame, the price ends at the `Close (C)` marker. The color of the stick is dictated by the open and close markers. If the closing price is higher than the opening price, the color is <span style="color: green;"><strong>green</strong></span> and <span style="color: red;"><strong>red</strong></span> for the opposite. The `change` is the difference between `close` and `open` prices. ## What to look for? In general, if you are a day trader and just riding the trend as I normally do, what you want to look for is a **Sign of Reversal (SOR)**. An SOR is an indication that the direction of a trend in focus is about to change. Now this is the best time to either buy or sell. If the previous trend that is about to end is downward, you may want to buy at the SOR and when the previous trend is upward, you want to sell at this point as the price may go down. Here is an example: <img src="/static/basic-ta/sample-sor.png" loading="lazy" /> Two SORs have been marked in the image above. Both are two-candlestick SORs. Basically, what you want is to find something like in `S1` and treat as buying signal and `S2` as selling signals. This is a definite profit for us right? Well, if we get them correctly, and we will, in time. As everything in trading, it's all about buying at lower expense and selling at higher returns. Buy spotting signs of reversals correctly, we maximize the use of our profit in trading. We would like to minimize the stagnant state of our money so the profit flow continues. ## Support and Resistance Support and resistance are invisible boundaries that are effective on a certain amount of time on a trend. An example of a horizontal support and resistance is shown below. <figure> <img src="/static/basic-ta/support-resistance.png" loading="lazy" /> <figcaption style="font-size: 0.75em;"><strong>BTC/USDT</strong> - 30m Timeframe - July 28-30, 2021</figcaption> </figure> The upper horizontal line is the `resistance` and the lower horizontal line is the `support`. A resistance is an indication that there are strong sellings at that level while the support is an indication of strong buys. Sometimes this two lines forms a rectangle if you close them at the end for horizontal levels and sometimes they form triangular enclosures to the trend. ## Drawing Tools One of the many drawing tools available in the trading view of binance, the simplest one that I use and recommend for you to start with is the line tool. We can use this to project a trendline and maybe spot a sign of reversal. <figure> <img src="/static/basic-ta/trendline-sor.png" loading="lazy" /> <figcaption style="font-size: 0.75em;"><strong>CHR/USDT</strong> - 15m Timeframe - August 26-27, 2021</figcaption> </figure> What I did here is I drew a line (orange line) representing resistance of the downtrend. When the trend or candlesticks escapes the line going up and did not go back down, I treat is as a sign of reversal. There are a lot of drawing tools available in the binance chart view but we will stick to the line tool in this article because of it's basic characteristics and it's easy to understand. ## Indicators There are lots of indicators also in the chart view of binance but we will only look at the few of them. These indicators are what I often used in making analysis of trends. ### Trading Volume Trading volume may be shown at the bottom of the chart in binance and it look like this. ![trading-volume](/static/basic-ta/trading-volume.png) Every bar or column in that graph represents the total volume of transactions per time frame as selected in the trading chart. So how is this useful? Well it tells us about how much buying or selling is happening. This is not easily visible in the candlesticks. ### Bollinger Band Bollinger bands are more popular and more useful in stock markets, however, you can still use them in cryptocurrency trading. ![bolling-bands](/static/basic-ta/boll.png) The above-chart has bollinger bands enabled. Two interesting parts that are sometimes useful for me is the upper and lower bound. You may see that when the candlesticks reaches the lower bound, it's a possible good time for buying and when it reaches the upper bound, that is a good time for selling. However, there are times when the chart does not goes up all the way to the upper bound, sometimes it goes back down after reaching the middle bound. The same happens when the chart came from the upper bound, it sometimes doesn't go all the way down to the lower bound. In these situations, we combine the use of bollinger bands with the sign of reversals given to us by candlesticks. This way, we get a bigger chance of predicting if the chart will go all the way up or down or is it going to come back after reaching the middle bound. ### Stochastic RSI Another one is the Stochastic RSI. There are plain RSI or *Relative Strength Index*, but the Stochastic RSI is more sensitive and this is the one I would normally use when using an RSI indicator. So what does an RSI tells us? If the graph of an RSI reaches 20% and below, it is an indication that the market is over-sell and when the graph reaches 80% and above, it is an indication that the market is over-bought. An RSI or Stochastic RSI can be displayed at the bottom of the graph as shown below. ![stochastic rsi](/static/basic-ta/stoch-rsi.png) The direction of the graph of Stochastic RSI or plain RSI can be noted to be opposite of that of the candlestick charts. RSIs are not directly an indication of sign of reversals but it may sometimes be used. RSIs are just indication of over-sell and over-buy. ### Gold and Death Cross Out of the indicators mentioned previously, this one is what I used in majority especially when making quick buys or selling limits. Here is an example of this indicator. <figure> <img src="/static/basic-ta/cross.png" loading="lazy" /> <figcaption style="font-size: 0.75em;"><strong>Golden and Death Cross</strong> - 15m Timeframe - August 28-September 1, 2021</figcaption> </figure> Death cross and Golden cross can be used as buy and sell indicators. I use this most of the time for buying entry points. What I set in the above is that the red line is the short term and the blue line is for the long term average. Usage of this is very simple. I set the buy entry when the blue line crosses the red line and going under it. If you notice in the graph above, everytime the blue goes under the red line, the candlestick chart goes up and when the blue line crosses the red line and goes over it, the candlestick chart usually goes down. Now this is not the most efficient entry for buy and sell points as you may notice but they give you the most chance of having the correct entry points giving you the most of your profit. ## Closing Remarks Now this is not a lot but I would like to think that this is a start. A start of understanding about the technical analysis of a market. Introducing beginners with few trading jargons that they may encounter along the way. I hope you like this article. We'll be talking in more detail about some of the tools here in the future entries for a clearer understanding and real life examples. Thank you for reading.
C#
UTF-8
2,843
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Bcompression { sealed public partial class Imagecompress : Form { public Imagecompress() { InitializeComponent(); } private void openbtn_Click(object sender, EventArgs e) { OpenFileDialog op = new OpenFileDialog(); op.Filter = "JPG Image(*.jpg)|*.jpg|BMP Image(*.bmp)|*.bmp|PNG Image(*.png)|.png"; if (op.ShowDialog() == DialogResult.OK) { textBox1.Text = op.FileName; pictureBox1.Image = Image.FromFile(textBox1.Text); } } private void compressbtn_Click(object sender, EventArgs e) { //textBox1.Text = openFileDialog1.FileName; String str = textBox1.Text; if (str != "") { Compress_img c = new Compress_img(); pictureBox2.Image = c.print(textBox1.Text); MessageBox.Show("Compressed!"); } else { MessageBox.Show("Select your file"); } } private void decompressbtn_Click(object sender, EventArgs e) { //textBox1.Text = openFileDialog1.FileName; String str = textBox1.Text; if (str != "") { deompress_img d = new deompress_img(); pictureBox2.Image = d.decomp(textBox1.Text); MessageBox.Show("Decompressed!"); } else { MessageBox.Show("Select your file"); } } private void Savebtn_Click(object sender, EventArgs e) { String str = textBox1.Text; if (str != "") { SaveFileDialog sv = new SaveFileDialog(); sv.Title = "Images"; sv.Filter = "JPG Image(*.jpg)|*.jpg|BMP Image(*.bmp)|*.bmp|PNG Image(*.png)|.png"; if (sv.ShowDialog() == DialogResult.OK) { pictureBox2.Image.Save(sv.FileName); MessageBox.Show("Saved!"); } } else { MessageBox.Show("Empty text Box !"); } } private void Imagecompress_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { FileCompression FC = new FileCompression(); this.Hide(); FC.Show(); } } }
Java
UTF-8
2,012
2.171875
2
[ "Apache-2.0" ]
permissive
package io.renren.modules.sys.service.impl; import io.renren.common.constants.Constants; import org.springframework.stereotype.Service; import java.util.List; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import io.renren.common.utils.PageUtils; import io.renren.common.utils.Query; import io.renren.modules.sys.dao.SysAreaDao; import io.renren.modules.sys.entity.SysAreaEntity; import io.renren.modules.sys.service.SysAreaService; @Service("sysAreaService") public class SysAreaServiceImpl extends ServiceImpl<SysAreaDao, SysAreaEntity> implements SysAreaService { @Override public PageUtils queryPage(SysAreaEntity sysArea) { IPage<SysAreaEntity> page = baseMapper.selectPage( new Query<SysAreaEntity>(sysArea).getPage(), new QueryWrapper<SysAreaEntity>() ); return new PageUtils(page); } @Override public List<SysAreaEntity> listThreeLevel() { SysAreaEntity sysAreaEntity = new SysAreaEntity(); sysAreaEntity.setId(Constants.Number.one.getKey()); listThreeLevelRecursive(sysAreaEntity); return sysAreaEntity.getSysAreaEntities(); } /** * 递归调用 设置三级省市级数据 * @param sysAreaEntity */ private void listThreeLevelRecursive(SysAreaEntity sysAreaEntity) { /** * 查询当前的级别的下一级 */ List<SysAreaEntity> sysAreaEntities = baseMapper.selectList(new QueryWrapper<SysAreaEntity>().lambda() .eq(SysAreaEntity::getPid, sysAreaEntity.getId())); if (sysAreaEntities == null || sysAreaEntities.size() == 0) { }else { sysAreaEntity.setSysAreaEntities(sysAreaEntities); for (SysAreaEntity areaEntity : sysAreaEntities) { listThreeLevelRecursive(areaEntity); } } } }
Java
UTF-8
2,132
3.5
4
[]
no_license
package hackrank; import java.util.Scanner; /** * https://www.hackerrank.com/challenges/electronics-shop/problem * * Best solution: * https://github.com/RyanFehr/HackerRank/blob/master/Algorithms/Implementation/Electronics%20Shop/Solution.java */ public class ElectronicsShop { static int getMoneySpent(int[] keyboards, int[] drives, int s){ // Complete this function boolean[] kt = new boolean[1000000]; boolean[] dt = new boolean[1000000]; int minK = Integer.MAX_VALUE; for (int i = 0; i < keyboards.length; i++) { kt[keyboards[i]]=true; if (keyboards[i]<minK) { minK=keyboards[i]; } } int minD = Integer.MAX_VALUE; for (int i = 0; i < drives.length; i++) { dt[drives[i]]=true; if (drives[i]<minD) { minD = drives[i]; } } if (minK+minD>s) { return -1; } // if (minK+minD==s) { // return minD+minK; // } int result = 0; for (int i = kt.length-1; i >=0; i--) { if (kt[i]) { for (int j = dt.length-1; j >=0 ; j--) { if (dt[j] && (i+j>result) && (i+j)<=s) { result=i+j; } } } } return result; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int s = in.nextInt(); int n = in.nextInt(); int m = in.nextInt(); int[] keyboards = new int[n]; for(int keyboards_i=0; keyboards_i < n; keyboards_i++){ keyboards[keyboards_i] = in.nextInt(); } int[] drives = new int[m]; for(int drives_i=0; drives_i < m; drives_i++){ drives[drives_i] = in.nextInt(); } // The maximum amount of money she can spend on a keyboard and USB drive, or -1 if she can't purchase both items int moneySpent = getMoneySpent(keyboards, drives, s); System.out.println(moneySpent); } }
Python
UTF-8
13,131
2.875
3
[]
no_license
from collections import defaultdict import math import numpy as np import torch def one_cold(i, n): """Inverse one-hot encoding.""" x = torch.ones(n, dtype=torch.bool) x[i] = 0 return x class HiddenStateMLPPooling(torch.nn.Module): def __init__(self, hidden_dim=128, mlp_dim=128, mlp_dim_spatial=16, out_dim=None): super(HiddenStateMLPPooling, self).__init__() self.out_dim = out_dim or hidden_dim self.spatial_embedding = torch.nn.Sequential( torch.nn.Linear(2, mlp_dim_spatial), torch.nn.ReLU(), ) self.hidden_embedding = torch.nn.Sequential( torch.nn.Linear(hidden_dim, mlp_dim - mlp_dim_spatial), torch.nn.ReLU(), ) self.out_projection = torch.nn.Linear(mlp_dim, self.out_dim) @staticmethod def rel_obs(obs): unfolded = obs.unsqueeze(0).repeat(obs.size(0), 1, 1) relative = unfolded - obs.unsqueeze(1) return relative def forward(self, hidden_states, _, obs): rel_obs = self.rel_obs(obs) spatial = self.spatial_embedding(rel_obs) hidden = self.hidden_embedding(hidden_states) hidden_unfolded = hidden.unsqueeze(0).repeat(hidden.size(0), 1, 1) embedded = torch.cat([spatial, hidden_unfolded], dim=2) pooled, _ = torch.max(embedded, dim=1) return self.out_projection(pooled) class DirectionalMLPPooling(torch.nn.Module): def __init__(self, hidden_dim=128, mlp_dim=32, mlp_dim_spatial=16, out_dim=None): super(DirectionalMLPPooling, self).__init__() self.out_dim = out_dim or hidden_dim self.spatial_embedding = torch.nn.Sequential( torch.nn.Linear(2, mlp_dim_spatial), torch.nn.ReLU(), ) self.directional_embedding = torch.nn.Sequential( torch.nn.Linear(2, mlp_dim - mlp_dim_spatial), torch.nn.ReLU(), ) self.out_projection = torch.nn.Linear(mlp_dim, self.out_dim) @staticmethod def rel_obs(obs): unfolded = obs.unsqueeze(0).repeat(obs.size(0), 1, 1) relative = unfolded - obs.unsqueeze(1) return relative @staticmethod def rel_directional(obs1, obs2): vel = obs2 - obs1 unfolded = vel.unsqueeze(0).repeat(vel.size(0), 1, 1) relative = unfolded - vel.unsqueeze(1) return relative def forward(self, _, obs1, obs2): rel_obs = self.rel_obs(obs2) spatial = self.spatial_embedding(rel_obs) rel_vel = self.rel_directional(obs1, obs2) directional = self.directional_embedding(rel_vel) embedded = torch.cat([spatial, directional], dim=2) pooled, _ = torch.max(embedded, dim=1) return self.out_projection(pooled) class FastPooling(torch.nn.Module): ## Default S-LSTM Parameters def __init__(self, cell_side=2.0, n=4, hidden_dim=128, out_dim=None, type_='occupancy', pool_size=8, blur_size=0, front=False): """ cell_side: size of each cell in real world n: number of cells along one dimension Pools in a square of side (n*cell_side) centred at the ped location """ super(FastPooling, self).__init__() self.cell_side = cell_side self.n = n self.type_ = type_ self.pool_size = pool_size self.blur_size = blur_size self.pooling_dim = 1 if self.type_ == 'directional': self.pooling_dim = 2 if self.type_ == 'social': self.pooling_dim = hidden_dim self.front = front if out_dim is None: out_dim = hidden_dim self.out_dim = out_dim self.embedding = torch.nn.Sequential( torch.nn.Linear(n * n * self.pooling_dim, out_dim), torch.nn.ReLU(), ) def forward(self, hidden_state, obs1, obs2): if self.type_ == 'occupancy': grid = self.occupancies(obs2) elif self.type_ == 'directional': grid = self.directional(obs1, obs2) elif self.type_ == 'social': grid = self.social(hidden_state, obs2) return self.embedding(grid) def occupancies(self, obs): ## Occupancy Grid return self.occupancy(obs) def directional(self, obs1, obs2): n = obs2.size(0) if n == 1: return self.occupancy(obs2, None) ## Relative Directional Grid vel = obs2 - obs1 unfolded = vel.unsqueeze(0).repeat(vel.size(0), 1, 1) relative = unfolded - vel.unsqueeze(1) ## Deleting Diagonal (Ped wrt itself) relative = relative[~torch.eye(n).bool()].reshape(n, n-1, 2) ## Occupancy Grid return self.occupancy(obs2, relative) def social(self, hidden_state, obs): n = obs.size(0) if n == 1: return self.occupancy(obs, None) ## Hiddenstate Grid hidden_state_grid = hidden_state.repeat(n, 1).view(n, n, -1) hidden_state_grid = hidden_state_grid[~torch.eye(n).bool()].reshape(n, n-1, -1) ## Occupancy Grid return self.occupancy(obs, hidden_state_grid) def occupancy(self, obs, other_values=None): """Returns the occupancy.""" n = obs.size(0) if n == 1: return torch.zeros(1, self.n * self.n * self.pooling_dim, device=obs.device) unfolded = obs.unsqueeze(0).repeat(obs.size(0), 1, 1) relative = unfolded - obs.unsqueeze(1) ## Deleting Diagonal (Ped wrt itself) relative = relative[~torch.eye(n).bool()].reshape(n, n-1, 2) if other_values is None: other_values = torch.ones(n, n-1, self.pooling_dim, device=obs.device) oij = (relative / (self.cell_side / self.pool_size) + self.n * self.pool_size / 2) range_violations = torch.sum((oij < 0) + (oij >= self.n * self.pool_size), dim=2) range_mask = range_violations == 0 # oij = oij[range_mask].long() oij[~range_mask] = 0 other_values[~range_mask] = 0 oij = oij.long() oi = oij[:, :, 0] * self.n * self.pool_size + oij[:, :, 1] # faster occupancy occ = torch.zeros(n, self.n**2 * self.pool_size**2, self.pooling_dim, device=obs.device) occ[torch.arange(occ.size(0)).unsqueeze(1), oi] = other_values # occ[oi] = other_values occ = torch.transpose(occ, 1, 2) occ_2d = occ.view(n, -1, self.n * self.pool_size, self.n * self.pool_size) occ_blurred = occ_2d occ_summed = torch.nn.functional.lp_pool2d(occ_blurred, 1, self.pool_size) # occ_summed = torch.nn.functional.avg_pool2d(occ_blurred, self.pool_size) # faster? return occ_summed.view(n, -1) class Pooling(torch.nn.Module): ## Default S-LSTM Parameters def __init__(self, cell_side=2.0, n=4, hidden_dim=128, out_dim=None, type_='occupancy', pool_size=8, blur_size=0, front=False): """ cell_side: size of each cell in real world n: number of cells along one dimension Pools in a square of side (n*cell_side) centred at the ped location """ super(Pooling, self).__init__() self.cell_side = cell_side self.n = n self.type_ = type_ self.pool_size = pool_size self.blur_size = blur_size self.pooling_dim = 1 if self.type_ == 'directional': self.pooling_dim = 2 if self.type_ == 'social': self.pooling_dim = hidden_dim self.front = front if out_dim is None: out_dim = hidden_dim self.out_dim = out_dim self.embedding = torch.nn.Sequential( torch.nn.Linear(n * n * self.pooling_dim, out_dim), torch.nn.ReLU(), ) def forward(self, hidden_state, obs1, obs2): if not self.front: if self.type_ == 'occupancy': grid = self.occupancies(obs2) elif self.type_ == 'directional': grid = self.directional(obs1, obs2) elif self.type_ == 'social': grid = self.social(hidden_state, obs2) else: if self.type_ == 'occupancy': grid = self.front_occupancies(obs2, obs1) elif self.type_ == 'directional': grid = self.front_directional(obs1, obs2) elif self.type_ == 'social': grid = self.front_social(hidden_state, obs2, obs1) return self.embedding(grid) def occupancies(self, obs): n = obs.size(0) return torch.stack([ self.occupancy(obs[i], obs[one_cold(i, n)]) for i in range(n) ], dim=0) def directional(self, obs1, obs2): n = obs2.size(0) if n == 1: return self.occupancy(obs2[0], None).unsqueeze(0) return torch.stack([ self.occupancy( obs2[i], obs2[one_cold(i, n)], (obs2 - obs1)[one_cold(i, n)] - (obs2 - obs1)[i], ) for i in range(n) ], dim=0) def social(self, hidden_state, obs): n = obs.size(0) return torch.stack([ self.occupancy(obs[i], obs[one_cold(i, n)], hidden_state[one_cold(i, n)]) for i in range(n) ], dim=0) ## Front def front_occupancies(self, obs, obs1): n = obs.size(0) return torch.stack([ self.occupancy(obs[i], obs[one_cold(i, n)], past_xy=obs1[i]) for i in range(n) ], dim=0) def front_directional(self, obs1, obs2): n = obs2.size(0) if n == 1: return self.occupancy(obs2[0], None).unsqueeze(0) return torch.stack([ self.occupancy( obs2[i], obs2[one_cold(i, n)], (obs2 - obs1)[one_cold(i, n)] - (obs2 - obs1)[i], obs1[i] ) for i in range(n) ], dim=0) def front_social(self, hidden_state, obs, obs1): n = obs.size(0) return torch.stack([ self.occupancy(obs[i], obs[one_cold(i, n)], hidden_state[one_cold(i, n)], obs1[i]) for i in range(n) ], dim=0) def occupancy(self, xy, other_xy, other_values=None, past_xy=None): """Returns the occupancy.""" if other_xy is None or \ xy[0] != xy[0] or \ other_xy.size(0) == 0: return torch.zeros(self.n * self.n * self.pooling_dim, device=xy.device) if other_values is None: other_values = torch.ones(other_xy.size(0), 1, device=xy.device) mask = torch.isnan(other_xy[:, 0]) == 0 oxy = other_xy[mask] other_values = other_values[mask] if not oxy.size(0): return torch.zeros(self.n * self.n * self.pooling_dim, device=xy.device) if not self.front: ## Distance oij = ((oxy - xy) / (self.cell_side / self.pool_size) + self.n * self.pool_size / 2) else: relative_pos = oxy - xy ##Rotate (N x 2) ## obs2[y] - obs1[y], obs2[x] - obs1[x] diff = [xy[1] - past_xy[1], xy[0] - past_xy[0]] velocity = np.arctan2(diff[0].item(), diff[1].item()) theta = (np.pi / 2) - velocity ct = math.cos(theta) st = math.sin(theta) r = torch.Tensor([[ct, st], [-st, ct]]) relative_pos = torch.einsum('tc,ci->ti', relative_pos, r) ## Distance oij = (relative_pos / (self.cell_side / self.pool_size) + torch.Tensor([self.n * self.pool_size / 2, 0])) range_violations = torch.sum((oij < 0) + (oij >= self.n * self.pool_size), dim=1) range_mask = range_violations == 0 oij = oij[range_mask].long() other_values = other_values[range_mask] if oij.size(0) == 0: return torch.zeros(self.n * self.n * self.pooling_dim, device=xy.device) oi = oij[:, 0] * self.n * self.pool_size + oij[:, 1] # print("Oij", oij) # print("Oi", oi) # slow implementation of occupancy # occ = torch.zeros(self.n * self.n, self.pooling_dim, device=xy.device) # for oii, v in zip(oi, other_values): # occ[oii, :] += v # faster occupancy occ = torch.zeros(self.n**2 * self.pool_size**2, self.pooling_dim, device=xy.device) occ[oi] = other_values occ = torch.transpose(occ, 0, 1) occ_2d = occ.view(1, -1, self.n * self.pool_size, self.n * self.pool_size) # optional, blurring (avg with stride 1) has similar effect to bilinear interpolation if self.blur_size: occ_blurred = torch.nn.functional.avg_pool2d( occ_2d, self.blur_size, 1, int(self.blur_size / 2), count_include_pad=True) else: occ_blurred = occ_2d occ_summed = torch.nn.functional.lp_pool2d(occ_blurred, 1, self.pool_size) # occ_summed = torch.nn.functional.avg_pool2d(occ_blurred, self.pool_size) # faster? return occ_summed.view(-1)
PHP
UTF-8
802
2.625
3
[]
no_license
<?php $p_columnax=$_POST["param1"]; $p_columnay=$_POST["param2"]; include '../../../dbcon/conectar_mysql.php'; $db = new ConectarMySQL(); $resultado=$db->traer_matriz($db->sentencia("CALL analisis_correlacion('$p_columnax','$p_columnay');")); $R=round($resultado[0][0],4); if ($R>0.5) { $msj='La correlacion de datos es fuertemente positiva'; }elseif ($R<(-0.5)) { $msj='La correlacion de datos es fuertemente negativa'; }else{ $msj='La correlacion de datos es nula'; } ?> <br> <div class="alert alert-dismissable alert-success"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true"> × </button> <h4> Mensaje </h4> <strong>Resultado Obtenido! <br></strong> <?php echo "$msj"; ?> <br> <strong><?php echo "Valor de R = $R"; ?></strong> </div>
Python
UTF-8
287
3.3125
3
[]
no_license
import calendar import math import random cal = calendar.month(2020, 3) print(cal) result = math.sqrt(49) print(result) number = random.randint(1000, 2000) print(number) movies = ["Aladdin", "Toy story", "Avenger: Endgame", "Lion King"] watch = random.choice(movies) print(watch)
Java
UTF-8
2,322
1.992188
2
[]
no_license
package org.miq.test.middleware; import java.util.ArrayList; import java.util.List; import org.miq.test.common.BaseProvider; import org.miq.test.common.Kwargs; import org.miq.test.webui.AngularSelect; import org.miq.test.webui.Form; import org.miq.test.webui.FormButton; import org.miq.test.webui.Input; import org.miq.test.common.Tuple; /** * File: cfme/middleware/provider.py * */ public class HawkularProvider extends BaseProvider { private FormButton addButtonHandler = new FormButton("Add this Middleware Manager"); private FormButton saveButtonHandler = new FormButton("Save changes"); private Form mainFormHandler; private String name; private String hostname; private String port; private Object credentials; private Object key; public HawkularProvider(String name, String hostName, String port, Object credentials, Object key) { this.name =name; this.hostname = hostName; this.port = port; this.credentials = credentials; this.key = key; List<Tuple> fields = new ArrayList<Tuple>(); fields.add(new Tuple("type_select", new AngularSelect("server_emstype"))); fields.add(new Tuple("name_text", new Input("name"))); fields.add(new Tuple("hostname_text", new Input("hostName"))); fields.add(new Tuple("port_text", new Input("port"))); this.mainFormHandler = new Form(fields.toArray(new Tuple[0]) ); } public String string_name() { return "middleware"; } public String page_name() { return "middleware"; } public String edit_page_suffix() { return "provider_edit_detail"; } public String detail_page_suffix() { return "provider_detail"; } public String refresh_text() { return "Refresh items and relationships"; } public String quad_name() { return null; } public Form properties_form() { return mainFormHandler ; } public FormButton add_provider_button() { return addButtonHandler; } public FormButton save_button() { return saveButtonHandler; } @Override protected Kwargs _form_mapping(boolean create, Kwargs kwargs) { Kwargs mapping = new Kwargs(); mapping.put("name_text", kwargs.get("name")); if (create) { mapping.put("type_select", kwargs.get("Hawkular")); } mapping.put("hostname_text", kwargs.get("hostname")); mapping.put("port_text", kwargs.get("port")); return mapping; } }
Java
UTF-8
800
3.484375
3
[]
no_license
package main.java.composite.demo001; /** * 组合模式:用树状结构表示“部分-整体”的层次结构,以便部分和整体保持一致性,共有类似的逻辑</br> * * <b>使用场合:</b>需求中体现部分和整体的关系,希望用户可以以统一的方式访问整体和部分,复用逻辑,就应该考虑使用组合模式</br> * @author wangjiuliang * */ public class CompositeTest { public static void main(String[] args) { Component root = new Composite("root"); root.add(new Leaf("Leaf-A")); root.add(new Leaf("Leaf-B")); Component c = new Composite("Leaf-C"); root.add(c); // root.remove(c); Component x = new Composite("X"); x.add(new Leaf("Leaf-XA")); x.add(new Leaf("Leaf-XB")); root.add(x); root.display(1); } }
Markdown
UTF-8
5,994
3.546875
4
[ "MIT" ]
permissive
# Bounce Algorithm [University of Applied Sciences Potsdam](http://www.fh-potsdam.de/) Semester: Winter 2015/16 Course: [11EG-B: Eingabe/Ausgabe (Steel Ant)](https://incom.org/workspace/6176) Supervisor: [Fabian Morón Zirfas](https://fhp.incom.org/profil/270) This Project was realized with [P5js](http://p5js.org), a Processing library for JavaScript, during the course *Eingabe/Ausgabe* at the *University of Applied Sciences Potsdam*. **Final digital result: [here](http://miduku.github.io/bounce-algorithm/html-algorithm/index.html)** ## Beginnings Our first assignment was to create an *analog algorithm* and let our course-mates solve it. It was very rudimentary and not very precise, which made us think about formulating it even better. Several changes had to be made to come up with the first iteration for other people, instead of our course-mates, to solve: ### v1.0a German: 1. Setze den Stift an einer beliebigen Stelle am Rand der Zeichenfläche an. 2. Zeichne eine gerade Linie in beliebiger Richtung, jedoch so, dass sie nicht 90° oder 0° vom Rand positioniert ist. 3. Falls man den Rand der Zeichenfläche erreicht, ändere die Richtung um 90° und führe die Zeichnung fort. 4. Nach der 10. Richtungsänderung, führe die Zeichnung fort bis der Rand der Zeichenfläche erreicht wurde. 5. Hebe den Stift an und wiederhole den ersten Schritt so oft wie man mag. Verwende einen beliebigen schwarzen Stift. Zeichne auf einem weißen quadratischen Notizzettel. Keine weiteren Werkzeuge dürfen verwendet werden English: 1. Put down pen at any place of the edge of the artboard. 2. Draw a staight line in any direction but it mustn't be positioned 90° or 0° from the edge. 3. If you arrive at the edge of the artboard, change the direction to 90° and continue drawing. 4. After repeating changing direction 10 times, continue drawing the line until you arrive at the edge of the artboard. 5. Lift the pen and repeat step 1 as often as you like. Use any black pen. Draw on white square notepaper. No other tools may be used. ### Result ![v1.0a-01](assets/img/algorithmus-v1.0a.jpg) ![v1.0a-02](assets/img/algorithmus-v1.0b.jpg) ## Continuation As one can see, the first iteration of the analog algorithm resulted in different results. Our next assignment was therefore to edit the whole code even more to see what the changes will result to. For this second iteration we asked people again to solve it: ### v1.1a German: Lese alle Schritte gründlich durch, verwende die beigelegten Stifte (schwarz, rot) und zeichne auf den beigelegten Zettel. Zähle und merke dir wieviele Handfalten du auf deiner linken Hand hast. Schreibe diese Zahl zusätzlich unten rechts auf die Rückseite des Zettels auf. Keine weiteren Werkzeuge dürfen verwendet werden. 1. Fange am oberen Rand der Zeichenfläche an mit dem roten Stift eine gerade Linie zu zeichnen; Die Linie muss einen anderen Rand erreichen. 2. Beim Erreichen des Randes, setze dort einen schwarzen Punkt. Ändere die Richtung um einen rechten Winkel und führe die Zeichnung (wie im ersten Schritt) mit dem roten Stift fort. 3. Wiederhole die ersten beiden Schritte 9 mal. Führe die letzte Zeichnung fort bis der Rand der Zeichenfläche erreicht wurde. 4. Hebe den Stift an und wiederhole alle Schritte (ab dem ersten) so oft wie die Anzahl deiner Handfalten. English: Thoroughly read all the steps, use the given pens (black, red) and draw on the given piece of paper. Count and remember how many hand wrinkles you have on your left hand. Write down this number on the lower right of the back of the piece of paper. No other tools may be used. 1. Start from the upper edge of the canvas and continuously draw a straight line with the red pen; The line must reach another edge. 2. Upon reaching the edge, place a black dot there. Change your direction to a right angle und continue your drawing (like in step one) with the red pen. 3. Repeat the first two steps 9 times. Continue drawing the last line until you reach the edge of the canvas. 4. Lift the pen and repeat all steps (from the first) as often as the amount of your hand wrinkles. ### Result 2 ![v1.1a-01](assets/img/algorithmus-v1.1a.jpg) ![v1.1a-02](assets/img/algorithmus-v1.1b.jpg) ## Digital translation Our final assignment of the project was to translate our analog algorithm into a digital one. We wrote our code in JavaScript using P5js. Since I only implemented one rule into my algorithm at first (turning ninety degrees at the edge of the canvas), I had to think of a second one to make it more *interesting*. The second rule was then to connect the corners with an additional line to create triangles every time the line reaches the edge. ### Result 3 **Final digital result: [here](http://miduku.github.io/bounce-algorithm/html-algorithm/index.html)** ![v1.2.0-03](assets/img/v1.2.0_screen03.png) ![v1.2.0-04](assets/img/v1.2.0_screen04.png) ![v1.2.0-05](assets/img/v1.2.0_screen05.png) ![v1.2.0-06](assets/img/v1.2.0_screen06.png) ![v1.2.0-08](assets/img/v1.2.0_screen08.png) ## Mockups As this algorithm works best in its animated form coming up with possible real life implementations seemed rather difficult but not impossible. The following list, with its corresponding images bellow, shows some ideas of such implementations: 1. Animated CD-Cover with LED Display [(animated mockup)](http://miduku.github.io/bounce-algorithm/html-mockups/index-cdcover.html) 2. Animated art pieces with LED Display on the wall [(animated mockup)](http://miduku.github.io/bounce-algorithm/html-mockups/index-wall.html) 3. Animated 'Live Wallpapers' for smartphones 4. Reaction based smartphone game ![Animated CD-Cover with LED Display](assets/img/mockup-cdcover.png) ![Animated art pieces with LED Display on the wall](assets/img/mockup-wall.png) ![Animated 'Live Wallpapers' for smartphones](assets/img/mockup-n4-animwallpaper.png) ![Reaction based smartphone game](assets/img/mockup-n4-game.png)
Java
UTF-8
2,433
1.851563
2
[]
no_license
/** * Copyright 2007 Verticon, Inc. All Rights Reserved. * * $Id$ */ package com.verticon.tracker; import com.verticon.osgi.metatype.OCD; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Generic Event Inclusion</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link com.verticon.tracker.GenericEventInclusion#getSpecies <em>Species</em>}</li> * <li>{@link com.verticon.tracker.GenericEventInclusion#getOcd <em>Ocd</em>}</li> * </ul> * </p> * * @see com.verticon.tracker.TrackerPackage#getGenericEventInclusion() * @model * @generated */ public interface GenericEventInclusion extends EObject { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String copyright = "Copyright 2007 Verticon, Inc. All Rights Reserved."; /** * Returns the value of the '<em><b>Species</b></em>' attribute list. * The list contents are of type {@link com.verticon.tracker.AnimalType}. * The literals are from the enumeration {@link com.verticon.tracker.AnimalType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Species</em>' attribute list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Species</em>' attribute list. * @see com.verticon.tracker.AnimalType * @see com.verticon.tracker.TrackerPackage#getGenericEventInclusion_Species() * @model required="true" * @generated */ EList<AnimalType> getSpecies(); /** * Returns the value of the '<em><b>Ocd</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Ocd</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Ocd</em>' reference. * @see #setOcd(OCD) * @see com.verticon.tracker.TrackerPackage#getGenericEventInclusion_Ocd() * @model required="true" * @generated */ OCD getOcd(); /** * Sets the value of the '{@link com.verticon.tracker.GenericEventInclusion#getOcd <em>Ocd</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Ocd</em>' reference. * @see #getOcd() * @generated */ void setOcd(OCD value); } // GenericEventInclusion
C++
UTF-8
2,595
3.03125
3
[ "MIT" ]
permissive
#include "MapManager.hpp" namespace mv { MapManager* MapManager::instance; void MapManager::createWorld(uint8_t defaultStateNumber) { for (int j = 0; j < unitWorldSize.y; j++) { for (int i = 0; i < unitWorldSize.x; i++) { map.emplace_back(sf::Vector2i{i,j}, cellDimensions, defaultStateNumber); } } } MapManager::MapManager(sf::Vector2i uWorldSize, const sf::Vector2f & cellDim) :Ticker(this) { if (uWorldSize.x <= 0 || cellDim.x <= 0 || uWorldSize.y <= 0 || cellDim.y <= 0) { Logger::Log(constants::error::mapManager::NEGATIVE_VALUES, Logger::STREAM::BOTH, Logger::TYPE::ERROR); return; } MapManager::unitWorldSize = uWorldSize; MapManager::cellDimensions = cellDim; } MapManager & MapManager::getInstance() { if (instance == 0) Logger::Log(constants::error::singleton::SINGLETON_NOT_INITED, Logger::STREAM::BOTH, Logger::TYPE::ERROR); return *instance; } void MapManager::createInstance(sf::Vector2i uWorldSize, const sf::Vector2f & cellDim) { if (instance == 0) instance = new MapManager(uWorldSize,cellDim); else { Logger::Log(constants::error::singleton::SINGLETON_INITED, Logger::STREAM::CONSOLE, Logger::TYPE::INFO); } } sf::Vector2i MapManager::getUnitWorldSize() { return MapManager::unitWorldSize; } sf::Vector2f MapManager::getCellDimensions() { return MapManager::cellDimensions; } std::vector<Cell>* MapManager::getCellStorage() { return &map; } bool MapManager::constructWholeWorld(const std::string& defaultState) { initialState = StateSystem::getNumberOfState(defaultState); if (!StateSystem::isStateExist(initialState)) { Logger::Log(constants::error::stateSystem::NUMBER_HAS_NOT_FOUND, Logger::STREAM::BOTH, Logger::TYPE::ERROR); return false; } MapManager::createWorld(initialState); } void MapManager::updateCells() { for (auto&var : map) var.update(); } void MapManager::setDefaultState(Cell& cell) { cell.setState(initialState); } void MapManager::resetAllCells() { for (auto&var : map) var.setState(initialState); } void MapManager::setOutlineColor(const sf::Color & color) { for (auto&var : map) var.setOutlineColor(color); } bool MapManager::isInMap(sf::Vector2i & unitPosition) { return isInMap(unitPosition.x, unitPosition.y); } bool MapManager::isInMap(unsigned int i, unsigned int j) { return i >= 0 && i < unitWorldSize.x && j >= 0 && j < unitWorldSize.y; } Cell& MapManager::getCell(int i, int j) { return map[i+j*unitWorldSize.x]; } void MapManager::tick() { updateCells(); } }
C
UTF-8
243
3.21875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main(void) { setbuf(stdout, NULL); char nombre[20]; printf("Ingrese nombre: "); fflush(stdin); scanf("%s", nombre); printf("Usted ingreso: %s\n\n", nombre); system("PAUSE"); return 0; }
Python
UTF-8
49
3.140625
3
[]
no_license
#x=int(input()) for y in range(1,8): print(y)
JavaScript
UTF-8
348
3.6875
4
[]
no_license
'use strict' module.exports = function filterForNumbers(iterable) { // loop over iterable, adding numeric values to a new array let numberArray = [] for(let item of iterable){ if(typeof item === 'number'){ numberArray.push(item) } } // then return the new array of numbers return numberArray }
Markdown
UTF-8
7,434
2.671875
3
[]
no_license
# KSDG ASP.NET MVC Workshop #1 # ## 簡介 ## 這是一個簡單的 MVC 留言板程式,它有下列功能: 1. 留言與回覆留言。 2. 編輯與刪除留言與回覆。 3. 整合Facebook登入。 4. 切換主版。 5. 在 Validate Request = true 的情況下允許 HTML 內容。 6. 使用 Bootstrap, Bootsnipp 以及 Fontawesome 簡單美化。 ## 環境與前置需求 ## - Visual Studio 2013 Community Edition, Professional or Ultimate Edition - SQL Server Express LocalDb - 網路環境 ## Steps ## ### 建立 MVC 專案 ### 1. 建立一個空白的 MVC 專案 (ASP.NET 空白專案,勾選 MVC 作為核心參考) ### 建立資料庫 ### 1. 在 App_Data 資料夾中新增一個空白資料庫 (這會需要 SQL Server Express LocalDb,但若自己有 SQL Server Express 或 SQL Server 也能用,但方法會不同)。 2. 在資料庫內新增 GuestBooks 表格,其指令碼為: CREATE TABLE [dbo].[GuestBooks] ( [Id] UNIQUEIDENTIFIER NOT NULL, [IdReply] UNIQUEIDENTIFIER NULL, [Name] NVARCHAR (250) NOT NULL, [Email] VARCHAR (500)NOT NULL, [Subject] NVARCHAR (250) NOT NULL, [Body] NVARCHAR (4000) NOT NULL, [DateCreated] DATETIME DEFAULT (getdate()) NOT NULL, PRIMARY KEY CLUSTERED ([Id] ASC) ); ### 建立 Model ### 1. 新增 ADO.NET 實體資料模型,使用由資料庫產生的Code-First模型。 2. 連到剛才新增的資料庫,勾選 GuestBooks 表格,並勾選物件單數化或複數化。 3. 完成精靈,產生 DbContext 與 GuestBook 類別。 ### 建立 Controller ### 1. 新增 HomeController 於 Controllers 資料夾。 ### 建立主版頁 ### 1. 在 Views 資料夾內新增一個 Shared 資料夾,並新增兩個版型配置頁 (Layout Page),分別是 _MasterPage.cshtml 與 _MasterPage2.cshtml。 2. 由 NuGet 安裝 Bootstrap 以及 Fontawesome 套件。 3. 修改 _MasterPage.cshtml 加入 Bootstrap 版型,並加入 PageCSS 以及 PageScripts 兩個 section。 <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" /> <link href="~/Content/font-awesome.min.css" rel="stylesheet" /> <link href="~/Content/MasterPage1.css" rel="stylesheet" /> @RenderSection("PageCSS", false); </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Guest Book MVC</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li> <a href="#">About</a> </li> <li> <a href="#">Services</a> </li> <li> <a href="#">Contact</a> </li> </ul> </div> </div> </nav> <div class="container"> @RenderBody() </div> <script src="~/Scripts/jquery-1.9.1.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> @RenderSection("PageScripts", false); </body> </html> 之後的 View 新增,除了部份檢視頁 (Partial View) 或有明確指示外,均以 _MasterPage.cshtml 作主版型。 ### 建立列表頁 ### 1. 在 HomeController 中新增 Index 方法的 View,利用 Scaffolding 產生,Model 為 GuestBook Model。 2. 在 Index 方法中加入下列程式。 public ActionResult Index() { using (WorkshopDb db = new WorkshopDb()) { query = db.GuestBooks; return View(query.ToList()); } } 3. 測試 Index 頁面,但當下沒有資料。 ### 建立新增表單 ### 1. 在 HomeController 中新增 Create 方法,以及其 View,一樣用 Scaffolding 產生。 2. 在 Create 方法中加入下列程式碼。 public ActionResult Create(Guid? id = null) { if (id == null) ViewBag.PostId = ""; else ViewBag.PostId = id.Value.ToString(); return View(); } 4. 建立另一個 Create 方法,處理來自表單的 POST。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(GuestBook Model, Guid? id = null) { if (!ModelState.IsValid) { return View(); } var Model = new GuestBook(); // create data. using (WorkshopDb db = new WorkshopDb()) { if (id == null) { Model.Id = Guid.NewGuid(); Model.DateCreated = DateTime.Now; db.GuestBooks.Add(Model); } else { Model.Id = Guid.NewGuid(); Model.IdReply = id.Value; Model.DateCreated = DateTime.Now; db.GuestBooks.Add(Model); } db.SaveChanges(); } return RedirectToAction("Index"); } 3. 測試 Create,應可以正常新增資料。 ### 建立明細頁 (可瀏覽主題回覆) ### 1. 修改 Index 方法,讓它可以接受 ID。 public ActionResult Index(Guid? id) { using (WorkshopDb db = new WorkshopDb()) { IQueryable<GuestBook> query = null; if (id == null) { query = db.GuestBooks.Where(i => i.IdReply == Guid.Empty); return View("Thread", query.ToList()); } else { query = db.GuestBooks.Where(i => i.Id == id.Value); ViewBag.PostId = id.Value.ToString(); if (query.Any()) return View("ThreadView", query.First()); else return HttpNotFound(); } } } 2. 修改Index.cshtml的名稱為Thread.cshtml,並新增一個View名為ThreadView.cshtml (空白View即可)。 3. ### 建立修改表單 ### ### 刪除功能 ### ### 分頁能力 ### ### Facebook 整合 ### ### 切換 Master Page (Layout) ### ### 美化表單 ### ### 上傳到 GitHub ###
Java
UTF-8
4,347
2.390625
2
[]
no_license
package com.sicredi.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; @Service public class CompletableFutureService { private static final Logger LOGGER = LoggerFactory.getLogger(CompletableFutureService.class); private List<List<String>> linesCompletableFuture = new ArrayList<>(); public static final String PROBLEMA_NA_IMPORTACAO_PARA_O_REGISTRO_AGENCIA_CONTA_SALDO_STATUS_ERROR = "Problema na importacao para o registro -> Agencia: {}, Conta: {}, saldo: {}, status: {}, error: {}"; @Autowired private ImportFile importFile; @Autowired private ApplicationContext appContext; public void init(List<List<String>> lines) { linesCompletableFuture = lines; List<CompletableFuture<List<String>>> futures = new ArrayList<>(); linesCompletableFuture.stream().skip(1).forEach(line -> { try { futures.add(importFile.importCVS(line)); } catch (ParseException e) { line.add(Boolean.FALSE.toString()); LOGGER.error(PROBLEMA_NA_IMPORTACAO_PARA_O_REGISTRO_AGENCIA_CONTA_SALDO_STATUS_ERROR, line.get(0), line.get(1), line.get(2), line.get(3), e.getLocalizedMessage()); } }); generateFile(futures); } //TODO utilizar esse metodo para controlar o tempo de execucao das threads, // caso seja excedido definir o false para o resultado da analise. private static void interruptExecution(AtomicBoolean cancelled, List<String> line, CompletableFuture<?> result) { // Interromper a execucao se chegar no tempo limite try { result.get(10, TimeUnit.MINUTES); } catch (TimeoutException | InterruptedException | ExecutionException e) { cancelled.set(true); line.add(Boolean.FALSE.toString()); Thread.currentThread().interrupt(); } } private void generateFile(List<CompletableFuture<List<String>>> futures) { try { List<List<String>> retorno = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).thenApply(unused -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()) ).thenApply(lists -> lists ).get(); writeCVSCompletableFuture(retorno); } catch (InterruptedException e) { LOGGER.error("Erro na atualizacao do arquivio. Erro: {}", e.getLocalizedMessage()); Thread.currentThread().interrupt(); } catch (ExecutionException e) { LOGGER.error("Erro na execucao. Erro: {}", e.getLocalizedMessage()); } } private void writeCVSCompletableFuture(List<List<String>> strings) { File csvFile = new File("resultCompletableFuture.csv"); try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));) { linesCompletableFuture.get(0).add("processado"); csvWriter.println(linesCompletableFuture.get(0).stream().map(String::trim).collect(Collectors.joining(";"))); for (List<String> item : strings) { csvWriter.println(item.stream().map(String::trim).collect(Collectors.joining(";"))); } } catch (IOException e) { LOGGER.error("Erro na escrita do arquivio. Erro: {}", e.getLocalizedMessage()); } finally { initiateShutdown(0); } } private void initiateShutdown(int returnCode) { LOGGER.info("Shutting Down Servico"); int exitCode = SpringApplication.exit(appContext, () -> returnCode); System.exit(exitCode); } }
Java
UTF-8
245
1.648438
2
[]
no_license
package com.koncana.validation.entity.repository; import org.springframework.data.repository.CrudRepository; import com.koncana.validation.entity.models.Modules; public interface IModuleRepository extends CrudRepository<Modules, Integer>{ }
Markdown
UTF-8
1,903
3.265625
3
[]
no_license
--- layout: post title: Looking for a Place To Call Home? tags: - Home Buyer Tips - Real Estate excerpt: Everyone needs a place they can come home to at the end of the day. enclosure: pullquote: We’ve helped people find their home for the past 20 years. enclosure_type: video/mp4 enclosure_time: use_youtube_image: false youtube_alternate_image: /uploads/9-14-22-eagon-yt.jpg youtube_code: 0ucNz5H9W3A --- {% include youtube.html %} {% include excerpt.html %} Hey there, Sandy with Sandy and Company, and today we are asking, “Where do you call home?” I did some traveling this summer, and to a point, it was a little difficult to come home from some of those. However, there is also a part of me that is always very grateful once I do.&nbsp; They say our home is a castle. **They say no matter how humble, there's no place like home.** As fabulous as vacations are for me, there is an equal part that’s really wonderful about coming home, home to my kitchen, to my yard, to my devotional spot on the couch. This is where real lives, day-to-day, good life happens, and I am blessed. {% include pullquote.html %} So we come back to you. **Where is your home? Where is your castle?** Is there something we can help you with? Because that's what we do. That’s what we’ve done for the last 20 years—is help people get into their home. I've had a couple of clients that have said very specifically, “I just want to get home,” and that's what we do. So what can we do to help you get your home, your castle, to be the place that you get to come home to at the end of a day, at the end of a vacation? Let's talk. Private message me, email me, give me a call. Let's talk and see what we can do to make your home, your castle, and the place where you want to be. Stay safe, stay blessed, stay healthy. Have a super day, and I'm excited to talk with you about your castle in your home.
JavaScript
UTF-8
10,019
2.953125
3
[]
no_license
/** * Common database helper functions. */ class DBHelper { static get DB_PROMISE() { // If the browser doesn't support service worker, // we don't care about having a database if (!navigator.serviceWorker) { return Promise.resolve(); } return idb.open('restaturant-reviews', 2, function(upgradeDb) { switch(upgradeDb.oldVersion) { case 0: const store = upgradeDb.createObjectStore('restaurants', { keyPath: 'id' }); store.createIndex('by-id', 'id'); case 1: const reviewsStore = upgradeDb.createObjectStore('reviews', { keyPath: 'id' }); reviewsStore.createIndex('by-restaurant-id', 'restaurant_id'); } }); } /** * Database URL. * Change this to restaurants.json file location on your server. */ static get DATABASE_URL() { const port = 1337 // Change this to your server port return `http://localhost:${port}`; } /** * Fetch all restaurants. */ static fetchRestaurants(callback) { fetch(`${DBHelper.DATABASE_URL}/restaurants`) .then(data => data.json()) .then(restaurants => { DBHelper.DB_PROMISE.then(db => { const tx = db.transaction('restaurants', 'readwrite'); const restaurantStore = tx.objectStore('restaurants'); restaurants.forEach(restaurant => { restaurantStore.put(restaurant); }); }); callback(null, restaurants) }) .catch(error => { DBHelper.DB_PROMISE.then(db => { const tx = db.transaction('restaurants'); const restaurantStore = tx.objectStore('restaurants'); restaurantStore.getAll().then(restaurants => { callback(null, restaurants); }) }) .catch(error => callback(error, null)); }); } /** * Fetch a restaurant by its ID. */ static fetchRestaurantById(id, callback) { // fetch restaurant by id with proper error handling. fetch(`${DBHelper.DATABASE_URL}/restaurants/${id}`) .then(data => data.json()) .then(restaurant => { DBHelper.DB_PROMISE.then(db => { const tx = db.transaction('restaurants', 'readwrite'); const restaurantStore = tx.objectStore('restaurants'); restaurantStore.put(restaurant); }); return restaurant; }) .then(restaurant => { DBHelper.fetchReviewsById(id).then(reviews => { restaurant.reviews = reviews; callback(null, restaurant); }) }) .catch(() => { DBHelper.DB_PROMISE.then(db => { const tx = db.transaction(['restaurants', 'reviews']); const restaurantStore = tx.objectStore('restaurants'); const reviewsStore = tx.objectStore('reviews'); const reviewsIndex = reviewsStore.index('by-restaurant-id'); restaurantStore.get(Number(id)).then(restaurant => { return restaurant || {}; }) .then(restaurant => { reviewsIndex.getAll(Number(id)).then(reviews => { restaurant.reviews = reviews; callback(null, restaurant); }); }); }) .catch(error => callback(error, null)); }); } /** * Fetch a reviews by restaurant ID. */ static fetchReviewsById(id) { return fetch(`${DBHelper.DATABASE_URL}/reviews?restaurant_id=${id}`) .then(data => data.json()) .then(reviews => { DBHelper.DB_PROMISE.then(db => { const tx = db.transaction('reviews', 'readwrite'); const reviewStore = tx.objectStore('reviews'); reviews.forEach(review => { reviewStore.put(review); }); }); return reviews; }) .catch(() => { DBHelper.DB_PROMISE.then(db => { const tx = db.transaction('reviews'); const reviewsStore = tx.objectStore('reviews'); const reviewsIndex = reviewsStore.index('by-restaurant-id'); reviewsIndex.getAll(`${id}`).then(reviews => { return reviews; }) }) .catch(error => error); }); } /** * Fetch restaurants by a cuisine type with proper error handling. */ static fetchRestaurantByCuisine(cuisine, callback) { // Fetch all restaurants with proper error handling DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Filter restaurants to have only given cuisine type const results = restaurants.filter(r => r.cuisine_type == cuisine); callback(null, results); } }); } /** * Fetch restaurants by a neighborhood with proper error handling. */ static fetchRestaurantByNeighborhood(neighborhood, callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Filter restaurants to have only given neighborhood const results = restaurants.filter(r => r.neighborhood == neighborhood); callback(null, results); } }); } /** * Fetch restaurants by a cuisine and a neighborhood with proper error handling. */ static fetchRestaurantByCuisineAndNeighborhood(cuisine, neighborhood, callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { let results = restaurants if (cuisine != 'all') { // filter by cuisine results = results.filter(r => r.cuisine_type == cuisine); } if (neighborhood != 'all') { // filter by neighborhood results = results.filter(r => r.neighborhood == neighborhood); } callback(null, results); } }); } /** * Fetch all neighborhoods with proper error handling. */ static fetchNeighborhoods(callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Get all neighborhoods from all restaurants const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood) // Remove duplicates from neighborhoods const uniqueNeighborhoods = neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i) callback(null, uniqueNeighborhoods); } }); } /** * Fetch all cuisines with proper error handling. */ static fetchCuisines(callback) { // Fetch all restaurants DBHelper.fetchRestaurants((error, restaurants) => { if (error) { callback(error, null); } else { // Get all cuisines from all restaurants const cuisines = restaurants.map((v, i) => restaurants[i].cuisine_type) // Remove duplicates from cuisines const uniqueCuisines = cuisines.filter((v, i) => cuisines.indexOf(v) == i) callback(null, uniqueCuisines); } }); } /** * Restaurant page URL. */ static urlForRestaurant(restaurant) { return (`./restaurant.html?id=${restaurant.id}`); } /** * Restaurant image URL. */ static imageUrlForRestaurant(restaurant) { return (`/img/${restaurant.photograph}`); } /** * Map marker for a restaurant. */ static mapMarkerForRestaurant(restaurant, map) { // https://leafletjs.com/reference-1.3.0.html#marker const marker = new L.marker([restaurant.latlng.lat, restaurant.latlng.lng], {title: restaurant.name, alt: restaurant.name, url: DBHelper.urlForRestaurant(restaurant) }) marker.addTo(newMap); return marker; } /** * Toggle restaurant as favorite */ static toggleFavorite(restaurantId, isFavorite, callback) { const putUrl = `${DBHelper.DATABASE_URL}/restaurants/${restaurantId}/?is_favorite=${isFavorite}`; const putOptions = { method: 'PUT' }; DBHelper.sendRequest(putUrl, putOptions, callback); } /** * Post new review */ static postReview(data, callback) { const postUrl = `${DBHelper.DATABASE_URL}/reviews/`; const postOptions = { method: 'POST', body: JSON.stringify(data) }; DBHelper.sendRequest(postUrl, postOptions, callback); } /** * Try to make fetch request if online; otherwise save request to local storage queue */ static sendRequest(url, options, callback) { if(navigator.onLine) { fetch(url, options) .then(resp => { callback(null); }) .catch(error => { callback(error); }); } else { DBHelper.queueRequest({url, options}); callback('OFFLINE'); } } /** * Add request to local storage queue when offline */ static queueRequest(requestData) { let requestQueue = JSON.parse(localStorage.getItem('requestQueue')) || []; requestQueue.push(requestData); localStorage.setItem('requestQueue', JSON.stringify(requestQueue)); } /** * Loop through request queue and make the requests */ static clearRequestQueue() { let requestQueue = JSON.parse(localStorage.getItem('requestQueue')) || null; if(requestQueue && requestQueue.length > 0) { // from https://serviceworke.rs/request-deferrer_service-worker_doc.html let sent = requestQueue.reduce((prevRequest, requestData) => { return prevRequest.then(() => { return fetch(requestData.url, requestData.options); }); }, Promise.resolve()); sent.then(() => { localStorage.setItem('requestQueue', '[]'); updateRestaurants(); }); } else { //request queue is empty } } }
C++
UTF-8
5,826
2.78125
3
[ "MIT" ]
permissive
/** * ofxSoundObject.cpp * * Created by Marek Bereza on 10/08/2013. */ #include "ofxSoundMixer.h" //---------------------------------------------------- ofxSoundMixer::ofxSoundMixer():ofxSoundObject(OFX_SOUND_OBJECT_PROCESSOR){ chanMod = OFX_SOUND_OBJECT_CHAN_MIXER; masterVolume = 1.0f; masterPan = 0.5f; setName ("Sound Mixer"); masterVol.set("Master Vol", 1, 0, 1); masterVol.addListener(this, &ofxSoundMixer::masterVolChanged); } //---------------------------------------------------- void ofxSoundMixer::masterVolChanged(float& f) { mutex.lock(); masterVolume = masterVol; mutex.unlock(); } //---------------------------------------------------- ofxSoundMixer::~ofxSoundMixer(){ std::lock_guard<std::mutex> lck(connectionMutex); connections.clear(); connectionVolume.clear(); } //---------------------------------------------------- ofxSoundObject* ofxSoundMixer::getConnectionSource(size_t connectionNumber){ ofxSoundObject* src = nullptr; { std::lock_guard<std::mutex> lck(connectionMutex); if (connectionNumber < connections.size()) { src = connections[connectionNumber]; } } return src; } //---------------------------------------------------- ofxSoundObject* ofxSoundMixer::getChannelSource(int channelNumber){ return getConnectionSource(channelNumber); } //---------------------------------------------------- void ofxSoundMixer::disconnectInput(ofxSoundObject * input){ std::lock_guard<std::mutex> lck(connectionMutex); for (size_t i =0; i<connections.size(); i++) { if (input == connections[i]) { connections.erase(connections.begin() + i); connectionVolume.erase(connectionVolume.begin() + i); break; } } } //---------------------------------------------------- void ofxSoundMixer::setInput(ofxSoundObject *obj){ std::lock_guard<std::mutex> lck(connectionMutex); for (size_t i =0; i<connections.size(); i++) { if (obj == connections[i]) { ofLogNotice("ofxSoundMixer::setInput") << " already connected" << endl; return; } } connections.push_back(obj); connectionVolume.push_back(1);//default volume for channel is 1 } //---------------------------------------------------- size_t ofxSoundMixer::getNumChannels(){ std::lock_guard<std::mutex> lck(connectionMutex); return connections.size(); } size_t ofxSoundMixer::getNumConnections(){ std::lock_guard<std::mutex> lck(connectionMutex); return connections.size(); } //---------------------------------------------------- void ofxSoundMixer::setMasterVolume(float vol){ mutex.lock(); masterVolume = vol; mutex.unlock(); } //---------------------------------------------------- float ofxSoundMixer::getMasterVolume(){ return masterVolume; } //---------------------------------------------------- float ofxSoundMixer::getMasterPan(){ return masterPan; } //---------------------------------------------------- void ofxSoundMixer::setMasterPan(float pan){ mutex.lock(); masterPan = pan; mutex.unlock(); } //---------------------------------------------------- bool ofxSoundMixer::getObjectConnectionIndex(ofxSoundObject& obj, size_t& index){ std::lock_guard<std::mutex> lck(connectionMutex); for (size_t i =0; i<connections.size(); i++) { if (&obj == connections[i]) { index = i; return true; } } return false; } //---------------------------------------------------- bool ofxSoundMixer::isConnectedTo(ofxSoundObject& obj){ std::lock_guard<std::mutex> lck(connectionMutex); for (size_t i =0; i<connections.size(); i++) { if (&obj == connections[i]) { return true; } } return false; } //---------------------------------------------------- void ofxSoundMixer::setChannelVolume(int channelNumber, float vol){ setConnectionVolume(channelNumber, vol); } //---------------------------------------------------- void ofxSoundMixer::setConnectionVolume(size_t connectionIndex, float vol){ std::lock_guard<std::mutex> lck(connectionMutex); if (connectionIndex < connectionVolume.size()) { connectionVolume[connectionIndex] = vol; } } //---------------------------------------------------- float ofxSoundMixer::getChannelVolume(int channelNumber){ return getConnectionVolume(channelNumber); } //---------------------------------------------------- float ofxSoundMixer::getConnectionVolume(size_t connectionIndex){ std::lock_guard<std::mutex> lck(connectionMutex); if (connectionIndex < connectionVolume.size()) { return connectionVolume[connectionIndex]; } return 0; } //---------------------------------------------------- // this pulls the audio through from earlier links in the chain and sums up the total output void ofxSoundMixer::audioOut(ofSoundBuffer &output) { if(connections.size()>0) { output.set(0);//clears the output buffer as its memory might come with junk ofSoundBuffer tempBuffer; tempBuffer.resize(output.size()); tempBuffer.setNumChannels(output.getNumChannels()); tempBuffer.setSampleRate(output.getSampleRate()); for(int i = 0; i < connections.size(); i++){ if (connections[i] != nullptr && connectionVolume[i] > 0) { tempBuffer.set(0); connections[i]->audioOut(tempBuffer); float v = connectionVolume[i]; for (int j = 0; j < tempBuffer.size(); j++) { output.getBuffer()[j] += tempBuffer.getBuffer()[j] * v; } } } /* if(output.getNumChannels() == 2) { output.stereoPan(1-masterPan, masterPan); }*/ output*=masterVolume; } } //----------------------------------------------------
Java
UTF-8
1,107
3.015625
3
[]
no_license
package org.freecode.demo; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; public class TimeConverter { public static void main(String[] args) { //Calendar cal = new GregorianCalendar(); String gmtTmStr = "2018-01-30 11:45:30"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdfPST = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); sdfPST.setTimeZone(TimeZone.getTimeZone("PST")); Date aDate = null; Date localDate = null; try { aDate = sdf.parse(gmtTmStr); localDate = sdfPST.parse(gmtTmStr); } catch (ParseException pe) { pe.printStackTrace(); } // cal.setTime(aDate); System.out.println("UTC: " + aDate + ", PST: " + localDate); //long ms = cal.getTimeInMillis(); long ms = aDate.getTime(); Calendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("PST")); cal2.setTimeInMillis(ms); System.out.println("PST: " + cal2.getTime()); } }
C++
UTF-8
2,966
3.421875
3
[]
no_license
// // 18_11.cpp // // // Created by Pengyan Qin on 7/28/15. // // #include <iostream> #include <fstream> using namespace std; // 1 represents black, 0 represents white // time complexity: O(n) bool is_valid(int *A, int n, int k){ for(int i = 0; i <= k; i += k){ // only 2 times for(int j = 0; j <= k; ++j){ if(*(A + i*n + j) == 0 || *(A + j*n + i) == 0 ) return false; } } return true; } // brute force // time complexity: O(n^4) int maximum_subsquare(int *A, int n){ for(int k = n-1; k > 0; --k){ // the side length of subsquare for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ // the start point of subsquare if((i + k < n) && (j + k < n)){ if(is_valid(A + i*n + j, n, k)) return k+1; } else break; } } } return -1; } // time complexity: O(n^3) // check square reduced to O(1) by preprocessing struct ones{ int onesright; int onesdown; ones():onesright(0), onesdown(0){} }; ones* preprocessing(int *A, int n){ ones* M = new ones[(n+1)*(n+1)]; for(int i = n; i >= 0; --i){ for(int j = n ; j >= 0; --j){ if(i == n || j == n || *(A + i*n + j) == 0 ){ *(M + i*n + j) = ones(); } else{ (M + i*n + j)->onesright = (M + i*n + j + 1)->onesright + 1; (M + i*n + j)->onesdown = (M + (i + 1)*n + j)->onesdown + 1; } } } for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ cout << "(" << (M + i*n + j)->onesright << ", " << (M + i*n + j)->onesdown << ")" << " "; } cout << endl; } return M; } int maximum_subsquare_helper(ones *A, int n){ for(int k = n-1; k >= 0; --k){ for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ // the start point of subsquare if((i + k < n) && (j + k < n)){ if((A + i*n + j)->onesdown == k+1 && (A + i*n + j)->onesright == k+1 && (A + i*n + j + k)->onesdown == k+1 && (A + (i + k)*n + j)->onesright == k+1) return k+1; } else break; } } } return -1; } int maximum_subsquare1(int *A, int n){ ones * Ah = preprocessing(A, n); return maximum_subsquare_helper(Ah, n); } int main(){ fstream fin; string filename = "18_11.in"; fin.open(filename.c_str()); if(!fin.is_open()){ cout << "fail to open " << endl; exit(1); } int n; fin >> n; int *A = new int[n*n]; for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ fin >> *(A + i*n + j); } } cout << maximum_subsquare(A, n) << endl; cout << maximum_subsquare1(A, n) << endl; }
Java
UTF-8
5,952
2.328125
2
[]
no_license
package hoopsnake.geosource.data; import android.app.Activity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.ref.WeakReference; import ServerClientShared.FieldWithContent; import hoopsnake.geosource.IncidentActivity; import hoopsnake.geosource.R; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; /** * Created by wsv759 on 07/03/15. * * Abstract implementation of AppField, wrapping an underlying vanilla Java FieldWithContent * object. (the object that is actually sent to the server.) * * This class is constructed with a FieldWithContent reference as a parameter. That reference is * guaranteed to stay up to date with the modifications to this class's wrapped field. So other * objects can make use of that reference. * * All implementations of AppField should extend this. */ public abstract class AbstractAppField implements AppField { private int fieldPosInList; //change this if and only if a new implementation is incompatible with an old one private static final long serialVersionUID = 1L; private static final int POSITION_VIEW_FIELD_TITLE = 0; /** * Underlying field object that contains the attributes to be acted upon by * the app. Its type should match the AppField that wraps it. */ FieldWithContent wrappedField; public IncidentActivity getActivity() { if (activityRef != null) return activityRef.get(); return null; } @Override public void setActivity(IncidentActivity activity){ this.activityRef = new WeakReference<IncidentActivity>(activity); } /** * The activity that will be displaying this field on the UI. This reference will not prevent the UI from being destroyed. */ private WeakReference<IncidentActivity> activityRef; String LOG_TAG = "geosource ui"; /** * Construct a new AppField, wrapping (not copying) a FieldWithContent. * Thus the reference to that FieldWithContent is guaranteed to remain up to date. * @param fieldToWrap a FieldWithContent that will be wrapped (not copied). * @param fieldPosInList the field's position in the field list. *@param activity @precond fieldToWrap is not null, and is of the correct type. activity is not null. * @postcond a new AppField is created with fieldToWrap as an underlying field. */ public AbstractAppField(FieldWithContent fieldToWrap, int fieldPosInList, IncidentActivity activity) { assertNotNull(fieldToWrap); assertNotNull(activity); this.wrappedField = fieldToWrap; setActivity(activity); this.fieldPosInList = fieldPosInList; } /** * Naive implementation, to be overridden by most extensions of this class. */ @Override public boolean contentIsFilled() { return wrappedField.getContent() != null; } @Override public String getTitle() { return wrappedField.getTitle(); } @Override public boolean isRequired() { return wrappedField.isRequired(); } @Override public boolean contentIsSuitable(Serializable content) { return content == null || wrappedField.contentMatchesType(content); } @Override public void setContent(Serializable content) { assertTrue(contentIsSuitable(content)); wrappedField.setContent(content); } @Override public View getFieldViewRepresentation(final int requestCodeForIntent) { Activity activity = getActivity(); if (activity == null) return null; /* * The complete view representing this field: a horizontal linear layout containing the field title, followed by its content. * (The content will be filled in by the particular implementation of AppField.) */ ViewGroup fieldView = (RelativeLayout) activity.getLayoutInflater().inflate(R.layout.field_view, null); TextView titleView = (TextView) fieldView.findViewById(R.id.field_title_view); String fieldLabel = getTitle() + ":"; if (isRequired()) fieldLabel += "*"; titleView.setText(fieldLabel); View contentView = getContentViewRepresentation(requestCodeForIntent); //Make sure the contentView knows its own position in the field list, so that if it launches a new activity, we can find it back. contentView.setTag(fieldPosInList); fieldView.addView(contentView); RelativeLayout.LayoutParams cvParams = (RelativeLayout.LayoutParams) contentView.getLayoutParams(); cvParams.addRule(RelativeLayout.RIGHT_OF, titleView.getId()); return fieldView; } /** * @param requestCodeForIntent a request code by which the returned view will be able to launch new activities. * @return the view representing the field's content itself, to be placed to the left of the textview * that represents the title for this field. */ abstract View getContentViewRepresentation(final int requestCodeForIntent); /** Serializable implementation. */ private void readObjectNoData() throws InvalidObjectException { Log.e(LOG_TAG, "no data received from file system for reserialization of AppField."); } private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException { wrappedField = (FieldWithContent) in.readObject(); fieldPosInList = in.readInt(); } private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(wrappedField); out.writeInt(fieldPosInList); } }
Java
UTF-8
348
1.882813
2
[ "Apache-2.0" ]
permissive
package com.couchbase.client.spring.cache.wiring.xml; import java.util.List; public class CouchbaseCluster { public static final com.couchbase.client.java.CouchbaseCluster create(List<String> nodes, String username, String password) { return com.couchbase.client.java.CouchbaseCluster.create(nodes).authenticate(username, password); } }
C#
UTF-8
1,077
2.640625
3
[ "MIT" ]
permissive
using System; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; namespace MiModeloMVC.Models { public class Clientes { // {get; } Consultar su valor // {set; } Establecer su valor public int ID {get; set;} [StringLength (60, MinimumLength=3)] public string nombre {get; set;} [Display (Name="Fecha de Alta")] [DataType (DataType.Date)] [DisplayFormat (DataFormatString="{0:yyyy-MM-dd}", ApplyFormatInEditMode=true)] public DateTime fechaAlta {get; set;} [Range (18, 75)] public int edad {get; set;} } public class EmpDBContext : DbContext { public EmpDBContext () { } public DbSet<Clientes> Clientes {get; set;} // use this if not was configured in by dependency injection in Startup.ConfigureServices protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=clientes.db"); } } }
C#
UTF-8
533
2.765625
3
[ "MIT" ]
permissive
using System.ComponentModel; using System.Runtime.CompilerServices; namespace DynamicNotifyPropertyChanged { /// <summary> /// Empty class that implements <see cref="INotifyPropertyChanged"/>. /// </summary> public abstract class BaseNotifyPropertyChangedClass : INotifyPropertyChanged { public event PropertyChangedEventHandler? PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
Python
UTF-8
9,501
2.828125
3
[]
no_license
# Tomer Shay, 323082701 import hashlib import os import random import matplotlib.pyplot as plt import numpy as np import sys if len(sys.argv) < 2: print("not enough arguments!") exit(-1) img_file_name = sys.argv[1] if len(sys.argv) < 3: print("you must enter the number of colors (k)!") exit(-1) k = int(sys.argv[2]) # flags colors_flag = "-c" in sys.argv loss_graph_flag = "-g" in sys.argv loss_value_flag = "-l" in sys.argv image_out_flag = "-i" in sys.argv pixels_3d_flag = "-p" in sys.argv only_one = "-o" in sys.argv str_for_hash = "" flags_str = "" if colors_flag: str_for_hash += "-c " if loss_graph_flag: str_for_hash += "-g " if loss_value_flag: str_for_hash += "-l " if image_out_flag: str_for_hash += "-i " if pixels_3d_flag: str_for_hash += "-p " if only_one: str_for_hash += "-o " flags_str = str_for_hash str_for_hash += str(k) str_for_hash += img_file_name output_dir_name = f"output{hashlib.sha1(str_for_hash.encode('utf-8')).hexdigest()}" if not os.path.exists(output_dir_name): os.mkdir(output_dir_name) print("output folder name: " + output_dir_name) printed_messages = "" orig_pixels = plt.imread(img_file_name) img_pixels = orig_pixels.astype(float) / 255. orig_pixels = img_pixels.copy() pixels = img_pixels.copy().reshape(-1, 3) # pixels is array of all the pixels in the image # calculate the distance between two 3D points def pixel_cet_dist(a, b): # a - pixel, b - centroid x = a[0] - b[0] y = a[1] - b[1] z = a[2] - b[2] return np.sqrt(x ** 2 + y ** 2 + z ** 2) # calculate the closest centroid (by minimum distance) def close_cent(pixel_cor, centroids_arr): min_dist = 3 min_i = -1 for e in range(len(centroids_arr)): cent = centroids_arr[e] dist = pixel_cet_dist(pixel_cor, cent) if dist < min_dist: min_dist = dist min_i = e return min_i # calculate the average of 3D pixels (x avg, y avg and z avg) def avg_pixels(pixels_arr): global pixels x_avg, y_avg, z_avg = 0, 0, 0 # x - red, y - green, z - blue pixels_index_arr = np.array(pixels_arr) pixel_count = len(pixels_index_arr) if pixel_count == 0: return -1 for pixel_i in pixels_index_arr: x_avg += pixels[pixel_i][0] y_avg += pixels[pixel_i][1] z_avg += pixels[pixel_i][2] return [x_avg / pixel_count, y_avg / pixel_count, z_avg / pixel_count] # for each centroid, calculate its new position (by average) def change_cents(cents_map): global centroids new_cents = [] for e in cents_map: new_cent = avg_pixels(cents_map[e]) if new_cent == -1: # if there is no pixels related to that centroid new_cents.append(centroids[e]) else: new_cents.append(new_cent) return new_cents # add all of the nearest pixels to the list of their centroid def iteration(centroids_arr): cents_map = {} for e in range(len(centroids_arr)): cents_map[e] = [] for e in range(len(pixels)): cents_map[close_cent(pixels[e], centroids_arr)].append(e) return cents_map # calculate the average distance of all the pixels from their centroid. def calc_loss(cents_map, cents): global img_pixels, pixels dist_sum = 0 for e in cents_map: for pixel_i in cents_map[e]: dist_sum += pixel_cet_dist(pixels[pixel_i], cents[e]) return dist_sum / len(img_pixels) def rand_rgb(): temp = [] for _ in range(3): temp.append(random.randint(0, 255) / 255.) return temp loss_cents_map = {} num_of_checks = 20 if only_one: num_of_checks = 1 for i in range(num_of_checks): centroids = [] for _ in range(k): centroids.append(rand_rgb()) orig_cents = centroids.copy() centroids_map = {} loss_values = [] iter_values = [] new_centroids = [] for iter in range(50): centroids_map = iteration(centroids) new_centroids = np.array(change_cents(centroids_map)).round(4) if np.array_equal(new_centroids, centroids): # all centroids didn't move at all break centroids = new_centroids loss_values.append(calc_loss(centroids_map, centroids)) iter_values.append(iter) loss_cents_map[round(loss_values[-1], 2)] = {"centroids": centroids.copy(), "original centroids": orig_cents.copy(), "loss values": loss_values.copy(), "iteration values": iter_values.copy(), "centroids map": centroids_map.copy()} if (i > 5 and len(loss_cents_map.keys()) == 1) or (i > 10 and len(loss_cents_map.keys()) <= 3): break # print(f"[iter {k}]: loss: {round(loss_values[-1], 2)}") min_key = min(loss_cents_map.keys()) min_values = loss_cents_map[min_key] if colors_flag: # if there is -c flag, output the final chosen colors to "colors_k{k}.txt" file. file_name_str = f"colors_k{k}.txt" f = open(output_dir_name + "/" + file_name_str, "w") f.write(f"{','.join([str(i) for i in np.array(min_values['centroids'] * 225).astype(int)])}") f.close() to_print = f"{file_name_str} contains the only {len(min_values['centroids'])} colors that been used in the final " \ f"image. " printed_messages += "\n" + to_print print(to_print) if loss_value_flag: # if there is -l flag, output the final loss value to "loss_k{k}.txt" file. file_name_str = f"loss_k{k}.txt" f = open(output_dir_name + "/" + file_name_str, "w") f.write(f"{min_key}") f.close() to_print = f"{file_name_str} contains the final loss value of the best iteration." printed_messages += "\n" + to_print print(to_print) if image_out_flag: # if there is -k flag, create the output compressed file. for i in range(len(min_values["centroids map"])): for j in range(len(min_values["centroids map"][i])): pixels[min_values["centroids map"][i][j]] = min_values["centroids"][i] # change the pixel by its centroid img_pixels = pixels.reshape(128, 128, 3) file_name_str = f"final_image_k{k}.jpeg" plt.imsave(output_dir_name + "/" + file_name_str, img_pixels) to_print = f"{file_name_str} contains the final image with only {len(min_values['centroids'])} colors." printed_messages += "\n" + to_print print(to_print) if loss_graph_flag: # if there is -g flag, create the output loss function graph. plt.plot(min_values["iteration values"], min_values["loss values"]) plt.text(min_values["iteration values"][-1], min_values["loss values"][-1], str(round((min_values["loss values"])[-1], 2))) plt.xlabel('iteration') plt.ylabel('loss value') title_str = "K-Means, k = " + str(len(min_values["centroids"])) plt.title(title_str) file_name_str = f"loss_graph_k{k}.png" plt.savefig(output_dir_name + "/" + file_name_str) to_print = f"{file_name_str} contains the loss function graph of the algorithm." printed_messages += to_print print(to_print) if pixels_3d_flag: # if there is -p flag, create the output pixels graph. fig = plt.figure() ax = fig.add_subplot(projection='3d') temp_pixels = orig_pixels.reshape(-1, 3) for pixel in temp_pixels: r_val = pixel[0] g_val = pixel[1] b_val = pixel[2] ax.scatter(r_val * 255, g_val * 255, b_val * 255, facecolor=(r_val, g_val, b_val)) for centroid in min_values["original centroids"]: # original centroids, before the k-means algorithm r_val = centroid[0] g_val = centroid[1] b_val = centroid[2] ax.scatter(r_val * 255, g_val * 255, b_val * 255, s=150, edgecolor="black", facecolor="gold") ax.set_xlabel('Red') ax.set_ylabel('Green') ax.set_zlabel('Blue') ax.view_init(25, 10) title_str = "K-Means, k = " + str(len(min_values["centroids"])) plt.title(title_str) file_name_str = f"3D_model_init_k{k}.png" plt.savefig(output_dir_name + "/" + file_name_str) to_print = f"{file_name_str} contains the centroids and the pixels position in a 3D space. The centroids are " \ f"bigger and their color is yellow. " printed_messages += "\n" + to_print print(to_print) fig = plt.figure() ax = fig.add_subplot(projection='3d') for centroid in min_values["centroids"]: # new centroids, after the k-means algorithm r_val = centroid[0] g_val = centroid[1] b_val = centroid[2] ax.scatter(r_val * 255, g_val * 255, b_val * 255, s=100, edgecolor=(1 - r_val, 1 - g_val, 1 - b_val), facecolor=(r_val, g_val, b_val)) ax.set_xlabel('Red') ax.set_ylabel('Green') ax.set_zlabel('Blue') ax.view_init(20, 10) title_str = "K-Means, k = " + str(len(min_values["centroids"])) plt.title(title_str) file_name_str = f"3D_model_after_k{k}.png" plt.savefig(output_dir_name + "/" + file_name_str) to_print = f"{file_name_str} contains the centroids position in a 3D space. The centroid's color is their real " \ f"color. " printed_messages += to_print print(to_print) f = open(output_dir_name + "/details.txt", "w") f.write( f"This output folder contains all the output files for the K-Means algorithm with k = {k} on the {img_file_name}" f" image file.\nThe flags used in the algorithm are: {flags_str}\n\n" + printed_messages) f.close()
Markdown
UTF-8
2,978
2.9375
3
[]
no_license
TECHNICAL DESCRIPTION. This is a description of the class design and its tests. * This is an Objective-C project using the Sprite Kit framework. I have been writing Objective-C code for 3 months so I would still count myself as a newbie, and I haven't (yet) paid much attention to coding standards or stylistic elements. My code may appear to be very C#-like, which is the language I have most experience with. * Tests are written using the Appple XCode provided test library. * All classes are prefixed with the string DTI (my initials). MAIN CODEBASE. * DTIGameBoard. This class is responsible for holding the current state of the game board and performing new moves on it. It also manages determining the next best move, which is a rule-based approach. * DTIComputerPlayerRule and its subtypes implement rules. These are run through in preference order until one of the rules "chooses" to make a play. Most of these rules are fairly simple, but DTIForkRule and DTIBlockForkRule are fairly involved and nasty (see TODO). * DTIGameScene is the UI and manages graphical nodes, lines, and dialog boxes. * DTIGame manages the interaction between DTIGameBoard and DTIGameScene. It maintains a score of how many games have been lost and drawn, and (cheekily) how many have been won but the count will never increase. It also manages resetting of games. TESTS. * Tests have names in the form testWhenAThenB; A is a game state and then B is the action that is expected to occur. * In DTIGameBoardTests, each game board state is played out. Since I’ve used a rule-based approach to playing perfectly, testing is straightforward as each of the rules must be adhered to and can be tested. * Some DTIGameBoardTests use the DTISequenceGenerator class when there are a large number of game sequences to test; others use hardcoded sequence strings. All of these tests can take a string of the form “X—X—O” and set up the initial game state using that, using a method called playSequence which converts this string representation to an actual game board. * There are no tests for the view class, DTIGameScene. However, I’ve tried to keep this class to UI construction and input code only, with any logic performed in DTIGame. DTIGame has good coverage. NOTE ON THE RULE-BASED SOLUTION. I am aware that there is a minimax solution to this problem. When I set out to implement this I did not believe the rule-based approach would be a huge amount of code, and I believed its advantages were: * that its requirements could be cleared captured as tests, making it easy to prove that the solution worked * that it would run much quicker than a minimax solution * that is would be simpler to randomize computer actions and make more enjoyable In hindsight, the amount of code required for DTIForkRule and DTIBlockForkRule would cause me to reconsider using the minimax alogorithm (see TODO).
PHP
UTF-8
3,055
3.609375
4
[]
no_license
<?php use Modules\Module; namespace Modules; class Date extends Module{ /** * Checks to see if a time overlaps a list of times * @param date $start_time * @param date $end_time * @param array $times * @return boolean */ public function timeOverlap($start_time, $end_time, array $times){ $ustart = strtotime($start_time); $uend = strtotime($end_time); foreach($times as $time){ $start = strtotime($time["start"]); $end = strtotime($time["end"]); if($ustart <= $end && $uend >= $start){ return true; } } return false; } /** * Takes two dates to find the number of day * @param date $date1 * @param date $date2 * @return int */ public function dateDiff($date1, $date2){ $time1 = strtotime($date1); $time2 = strtotime($date2); return abs($time1 - $time2) / (24 * 60 * 60); } /** * Takes to dates and/or times to find the time difference * @param datetime $date1 * @param datetime $date2 * @return string */ public function timeDiff($date1, $date2){ $time1 = strtotime($date1); $time2 = strtotime($date2); $seconds = abs($time1 - $time2); $hours = floor($seconds / (60 * 60)); $divisor_for_minutes = $seconds % (60 * 60); $minutes = floor($divisor_for_minutes / 60); $divisor_for_seconds = $divisor_for_minutes % 60; $seconds = ceil($divisor_for_seconds); return "$hours:$minutes:$seconds"; } /** * Gets the number of seconds in a time * @param time $time * @return int */ public function timeToSec($time){ $times = array_replace(array(0, 0, 0), explode(":", $time)); $th = (int)$times[0] * 60 * 60; $tm = (int)$times[1] * 60; return $th + $tm + (int)$times[2]; } public function minToSec($minutes){ return $minutes * 60; } /** * Tests to see if the date is a weekday (Monday - Friday) * @param date $date * @return boolean */ public function isWeekday($date){ $d = date('w', strtotime($date)); return ($d != 6 && $d != 0) ? true : false; } /** * Tests to see if the date is a weekend (Saturday or Sunday) * @param date $date * @return boolean */ public function isWeekend($date){ $d = date('w', strtotime($date)); return ($d == 6 || $d == 0) ? true : false; } /** * Returns a pretty fomatted date: * Sunday March 2nd 2014 * @param date $date * @param string $format * @return string */ public function prettyDate($date, $format = "l F jS Y"){ $time = strtotime($date); return date($format, $time); } }
Markdown
UTF-8
4,479
2.5625
3
[]
no_license
--- author: Il Gorgonauta comments: true date: 2013-05-07 17:31:06+00:00 layout: post link: http://www.atomodelmale.it/2013/05/07/prime-visioni-tutte-le-uscite-al-cinema-di-maggio-2013/ slug: prime-visioni-tutte-le-uscite-al-cinema-di-maggio-2013 title: Prime visioni, tutte le uscite al cinema di maggio 2013 wordpress_id: 13204 categories: - Prime Visioni --- ![great_gatsby](http://www.atomodelmale.it/wp-content/uploads/2013/05/great_gatsby-300x137.jpg)Il ritorno dello scatenato gruppo di amici di "Una notte da Leoni", ma anche l'apparizione sul grande schermo del "Grande Gatbsy". Non possono mancare gli inossidabili piloti di "Fast and Furios". Queste le uscite più "calde" del mese di maggio. Si comincia proprio giovedì 16 con "**Il Grande Gatbsy**". Tratto dall'omonimo romanzo di Francis Scott Fitzgerald, il film racconta la storia di un giovane e misterioso uomo di nome James Gatsby (Leonardo di Caprio), famoso per le sue grandissime feste nel suo lussuoso palazzo. Lo scopo di tutto ciò si rivelerà essere il tentativo di riprendersi Daisy, un amore passato che ormai si era costruito una nuova vita con suo marito e sua figlia. Si passa a giovedì 23 con i bolidi di "**Fast and Furios 6**". La pellicola, la sesta della serie _Fast and Furious_, riprende là dove si era conclusa la precedente. Dom e Brian hanno rubato al boss di rio Hernan Reyes 100 milioni di dollari, ma non possono tornare a casa per timore di esser scoperti. In fuga per il mondo, accettano la proposta che presenta loro l'agente Luke Hobbs, da tempo a caccia di un'organizzazione di piloti mercenari. Se daranno una mano per catturare i ricercati, i nostri eroi potranno tornare ad abbracciare i famigliari. Si chiude infine giovedì 30 con "**Una notte da leoni 3**".  Alan, Phil, Stu e Doug rivivono una notte indimenticabile. Tutto comincia con la morte del padre di Alan che successivamente attraversa un periodo di crisi tale da portarlo al ricovero in un ospedale psichiatrico. Dopo la sua fuga dall'ospedale, gli amici Phil, Stu e Doug cercano di riacciuffarlo, rincorrendolo tra Tijuana, Los Angeles e Las Vegas.![Fire with fire](http://www.atomodelmale.it/wp-content/uploads/2013/05/Fire-with-fire.jpg) Da segnalare anche "**Fire with Fire**" e "**L'uomo con i pugni di ferro**". Nel primo un uomo assiste a un brutale doppio omicidio. Deve perciò abbandonare il suo lavoro di vigile del fuoco ed entrare nel programma di protezione testimoni, cercando di provare la colpevolezza dell’esecutore dell’omicidio, un boss del crimine di Long Beach. Nel secondo un fabbro con un talento per il Kung fu si trasferisce in un villaggio della Cina feudale, dove sarà costretto dalle due famiglie rivali a costruire armi sempre più infallibili. Per ultimo ecco "**Effetti collaterali**", in uscita lo scorso primo maggio. Emily e Martin Taylor sono una coppia di successo. Belli, ricchi e amanti dei piaceri della vita. Posseggono una villa, una barca a vela e ogni lusso possibile e immaginabile. Una vita da sogno, fino a quando Martin non viene incarcerato con l’accusa di "insider trading". Da questo momento, per Emily nulla sarà più come prima. In con­clu­sione, come tradizione, l’elenco completo delle uscite **1 maggio**. Il cecchino / Benur - Gladiatore in affitto / Effetti collaterali / Hansel & Gretel: Cacciatori di streghe / Miele / Muffa / Snich - L'infiltrato; **2 maggio**. La finestra di Alice / Il commissario Torrente - il braccio idiota della legge / I Love One Direction. 7 maggio. Una canzone per il paradiso; **9 maggio**.  Bellas Mariposas / 20 anni di meno / Anime nella nebbia / No - I giorni dell'arcobaleno / La Casa / Confessions / Fedele alla Linea - Giovanni Lindo Ferretti / Filarmonica della Scala 2013 - Bobby McFerrin / Fire with Fire / Mi rifaccio vivo / The Parade - La sfilata / Sta per piovere / Teatro Bolshoi: Romeo e Giulietta / L'uomo con i pugni di ferro / L'ultimo pastore / Una canzone per il paradiso; **16 maggio**. Il grande Gatsby / AmeriQua / Benvenuti a Saint-Tropez / A Lady in Paris / Teatro Bolshoi - Esmeralda / Post Tenebras Lux; **21 maggio**. La grande bellezza; **22 maggio**. The Fast and the Furious 6; **23 maggio**. Amaro amore / Epic / Hates - House at the End of the Street; **30 maggio**. Ti ho cercata in tutti i necrologi / Akira / Gli aristogatti / Esterno sera / Slow Food Story / Una notte da leoni 3 / Nederlands Dans Theater - Evening 4 / Solo Dio perdona / To be or not to be; e il trailer a caso del mese.
Python
UTF-8
11,318
2.625
3
[]
no_license
from flask import Flask from flask import request, jsonify from tinydb import TinyDB, Query import requests app = Flask(__name__) # Use TinyDB db = TinyDB('db.json') DB = Query() # Initialize important constants LIST_URL = 'http://172.17.0.55/list-demo' MAX_TRANSFER_AMOUNT = 1000000000 ZERO_QUORUM = 0 HALF_QUORUM = 2 FULL_QUORUM = 4 NEIGHBORS = [ '1406566400', '1406543580', '1406573356', '1306398983', ] # ======== HELPER METHODS ======== # return IPs of neighbors corresponding to a list of IDs def get_neighbor_ips(): neighbors = NEIGHBORS neighbor_ips = [] ips = requests.get(LIST_URL).json() for ip in ips: for neighbor in neighbors: if ip['npm'] == neighbor: neighbor_ips.append(ip['ip']) return neighbor_ips # Transfer an amount of money of user_id to ip_tujuan def transfer_to_neighbor(user_id, nilai, ip_tujuan): url = 'http://' + ip_tujuan + '/ewallet/transfer' try: print("[transferCabang] Trying to connect to: {}".format(ip_tujuan)) response = requests.post(url, json={ 'user_id': user_id, 'nilai': nilai }, timeout=1) response = response.json() print("[transferCabang] Finished connecting to: {}".format(ip_tujuan)) if response['status_transfer'] >= 0: print("[transferCabang] Succesfully transferring: {} to {}".format(nilai, ip_tujuan)) return 1 else: print("[transferCabang] Failed transferring {}".format(ip_tujuan)) return -2 except Exception as e: print(e) print("[transferCabang] Can't connect to: {}".format(url)) return -3 # return IP address of first IP that has user_id as member # return -1 if can't get user_id on all nodes def pass_get_total_saldo(user_id): neighbor_ips = get_neighbor_ips() for neighbor_ip in neighbor_ips: url = 'http://' + neighbor_ip + '/ewallet/getSaldo' try: response = requests.post(url, json={ 'user_id': user_id }, timeout=1) response = response.json() if response['nilai_saldo'] >= 0: # call getTotalSaldo next_url = 'http://' + neighbor_ip + '/ewallet/getTotalSaldo' try: response = requests.post(next_url, json={ 'user_id': user_id }, timeout=2) response = response.json() print("[passGetTotalSaldo] Sucessfully getting saldo of: {}, from {}".format(response['nilai_saldo'], neighbor_ip)) return response['nilai_saldo'] except Exception as e: print(e) print("[passGetTotalSaldo] Error getTotalSaldo from {}".format(neighbor_ip)) except Exception as e: print(e) print("[passGetTotalSaldo] Can't connect to: {}".format(url)) return -1 # return -3 if can't connect to one of the host # return >=0 as the total saldo if successful def get_neighbors_total_saldo(user_id): total_saldo = 0 neighbor_ips = get_neighbor_ips() for neighbor_ip in neighbor_ips: url = 'http://' + neighbor_ip + '/ewallet/getSaldo' try: print("[getNeighborsSaldo] Trying to connect to: {}".format(neighbor_ip)) response = requests.post(url, json={ 'user_id': user_id }, timeout=1) response = response.json() print("[getNeighborsSaldo] Finished connecting to: {}".format(neighbor_ip)) if response['nilai_saldo'] >= 0: print("[getNeighborsSaldo] Succesfully adding: {}, from {}".format(response['nilai_saldo'], neighbor_ip), ) nilai_saldo = response['nilai_saldo'] total_saldo += nilai_saldo else: print("[getNeighborsSaldo] Failed getting saldo from {}".format(neighbor_ip)) except Exception as e: print(e) print("[getNeighborsSaldo] Can't connect to: {}".format(url)) return -3 return total_saldo # return the number of available neighbors def quorum_check(): neighbor_ips = get_neighbor_ips() available = 0 for neighbor_ip in neighbor_ips: url = 'http://' + neighbor_ip + '/ewallet/ping' try: status = requests.post(url, json={}, timeout=0.5) status = status.json() if status['pong'] == 1: available += 1 print("url {} available".format(url)) else: print("url {} not available".format(url)) except: print("Can't connect to: {}".format(url)) return available # ======== ROUTING ======== @app.route('/ewallet/ping', methods=['GET', 'POST']) def ping(): if request.method == 'POST': pong = 1 else: pong = -99 response = { "pong" : pong } return jsonify(response) @app.route('/ewallet/register', methods=['POST']) def register(): if request.method == 'POST': if quorum_check() >= HALF_QUORUM: req = request.get_json() user_id = req.get('user_id', None) nama = req.get('nama', None) if user_id and nama: result = db.search(DB.user_id == user_id) if len(result) == 0: db.insert({ 'user_id' : user_id, 'nama' : nama, 'nilai_saldo' : 0 }) status_register = 1 else: status_register = -4 else: status_register = -99 else: status_register = -2 else: status_register = -99 response = { 'status_register' : status_register } return jsonify(response) @app.route('/ewallet/getSaldo', methods=['POST']) def get_saldo(): if request.method == 'POST': quorum_result = quorum_check() if quorum_result >= HALF_QUORUM: req = request.get_json() user_id = req.get('user_id', None) if user_id: result = db.search(DB.user_id == user_id) if len(result) == 0: nilai_saldo = -1 else: nilai_saldo = result[0]['nilai_saldo'] else: nilai_saldo = -99 else: nilai_saldo = -2 else: nilai_saldo = -99 response = { 'nilai_saldo' : nilai_saldo } return jsonify(response) @app.route('/ewallet/transfer_cabang', methods=['POST']) def transfer_cabang(): if request.method == 'POST': quorum_result = quorum_check() if quorum_result >= HALF_QUORUM: req = request.get_json() user_id = req.get('user_id', None) nilai = req.get('nilai', None) ip_tujuan = req.get('ip_tujuan', None) if user_id and nilai and ip_tujuan: neighbor_ips = get_neighbor_ips() if ip_tujuan in neighbor_ips: result = db.search(DB.user_id == user_id) if len(result) > 0: nilai = int(nilai) saldo_awal = result[0]['nilai_saldo'] if(nilai >= 0 and nilai <= MAX_TRANSFER_AMOUNT and nilai <= saldo_awal): # Lakukan transfer ke tujuan do_transfer_status = transfer_to_neighbor(user_id, nilai, ip_tujuan) if do_transfer_status >= 0: # Kurangi saldo dengan nilai transfer db.update({ 'nilai_saldo' : saldo_awal - nilai }, DB.user_id == user_id) status_transfer = 1 else: # Failed to transfer to neighbor status_transfer = -7 else: # Amount not valid status_transfer = -5 else: # User not found in DB status_transfer = -4 else: # Tujuan IP Address not in list of neighbors status_transfer = -6 else: # Missing field status_transfer = -99 else: # Quorum not met status_transfer = -2 else: # Request method not supported status_transfer = -99 response = { 'status_transfer': status_transfer } return jsonify(response) @app.route('/ewallet/transfer', methods=['POST']) def trasfer(): if request.method == 'POST': quorum_result = quorum_check() if quorum_result >= HALF_QUORUM: req = request.get_json() user_id = req.get('user_id', None) nilai = req.get('nilai', None) if user_id and nilai: result = db.search(DB.user_id == user_id) if len(result) > 0: nilai = int(nilai) if(nilai >= 0 and nilai <= MAX_TRANSFER_AMOUNT): saldo_awal = result[0]['nilai_saldo'] db.update({ 'nilai_saldo' : saldo_awal + nilai }, DB.user_id == user_id) status_transfer = 1 else: status_transfer = -5 else: status_transfer = -4 else: status_transfer = -99 else: status_transfer = -2 else: status_transfer = -99 response = { 'status_transfer': status_transfer } return jsonify(response) @app.route('/ewallet/getTotalSaldo', methods=['POST']) def get_total_saldo(): if request.method == 'POST': quorum_result = quorum_check() if quorum_result >= FULL_QUORUM: req = request.get_json() user_id = req.get('user_id', None) if user_id: result = db.search(DB.user_id == user_id) if len(result) == 0: print("[getTotalSaldo] Passing getTotalSaldo command to neighbor") nilai_saldo = pass_get_total_saldo(user_id) else: print("[getTotalSaldo] Getting saldo of all neighbors") total_saldo = get_neighbors_total_saldo(user_id) if total_saldo >= 0: nilai_saldo = total_saldo else: nilai_saldo = -3 else: nilai_saldo = -99 else: nilai_saldo = -2 else: nilai_saldo = -99 response = { 'nilai_saldo' : nilai_saldo } return jsonify(response) # Run on localhost port 80, allow all connection, allow multi-threading if __name__ == '__main__': app.run(host="0.0.0.0", port=80, threaded=True)
C
UTF-8
3,953
3.046875
3
[]
no_license
/** * tx - disk-send * * XMODEM-512 (512K block) routines * * Thomas Cherryhomes <thom.cherryhomes@gmail.com> * * Licensed under GPL Version 3.0 */ #include <i86.h> #include <stdio.h> #include <stdlib.h> #include "xmodem-send.h" #include "int14.h" #include "int13.h" #define START_DELAY_TIME_MS 3000 // approx 3 secs. #define BYTE_XMODEM_START 0x43 // C (for CRC) ProtocolState state=START; unsigned char block_num=1; short cylinder=0; unsigned char head=0; unsigned char sector=1; char* buf; DiskGeometry geometry; /** * Calculate 16-bit CRC */ unsigned short xmodem_calc_crc(char* ptr, short count) { unsigned short crc; char i; crc=0; while (--count >= 0) { crc = crc ^ (unsigned short) *ptr++ << 8; i=8; do { if (crc & 0x8000) crc = crc << 1 ^ 0x1021; else crc = crc << 1; } while (--i); } return crc; } /** * XMODEM-512 send file - main entrypoint. */ void xmodem_send(void) { buf=malloc(512); if (int13_disk_geometry(&geometry)==1) { printf("Could not retrieve disk geometry for device 0x80. Aborting.\n"); free(buf); return; } while (state!=END) { switch (state) { case START: xmodem_state_start(); break; case BLOCK: xmodem_state_block(); break; case CHECK: xmodem_state_check(); break; case REBLOCK: break; case END: break; } } free(buf); } /** * Send CRC START (0x43) character and delay for 3 seconds, waiting for SOH. */ void xmodem_state_start() { short wait_time=START_DELAY_TIME_MS; while (wait_time>0) { delay(1); wait_time--; if (int14_data_waiting()!=0) { if (int14_read_byte()=='C') { state=BLOCK; printf("Starting Transfer.\n"); return; } } } printf("Trying Again...\n"); } /** * Send an XMODEM-512 block with CRC */ void xmodem_state_block(void) { short i=0; unsigned short calced_crc; if (int13_read_sector(cylinder,head,sector,buf)==0) { printf("Sending Cylinder: %4d, Head: %2d, Sector: %2d...",cylinder,head,sector); int14_send_byte(0x01); // SOH int14_send_byte(block_num); // block # (mod 256) int14_send_byte(0xFF-block_num); // 0xFF - BLOCK # (simple checksum) for (i=0;i<512;i++) // Send the data int14_send_byte(buf[i]); calced_crc=xmodem_calc_crc(buf,512); int14_send_byte((calced_crc>>8)); // CRC Hi int14_send_byte(calced_crc&0xFF); // CRC Lo state=CHECK; } else { printf("Could not read C: %4d, H: %2d, S: %2d from drive. Cancelling.\n",cylinder,head,sector); int14_send_byte(0x18); // CANCEL state=END; } } /** * Wait for ack/nak/cancel from receiver */ void xmodem_state_check(void) { unsigned char b; if (int14_data_waiting()!=0) { b=int14_read_byte(); switch (b) { case 0x06: // ACK printf("ACK!\n"); block_num++; block_num&=0xff; state=BLOCK; xmodem_set_next_sector(); // so if we're at end, it can be overridden. break; case 0x15: // NAK printf("NAK!\n"); state=BLOCK; // Resend. break; case 0x18: // CAN printf("CANCEL!\n"); state=END; // end. break; default: printf("Unknown Byte: 0x%02d: %c",b,b); } } } /** * Set next sector (in response to ACK) */ void xmodem_set_next_sector(void) { if (sector>=geometry.s) { sector=1; if (head>=geometry.h) { head=0; if (cylinder>geometry.c) state=END; else cylinder++; } else head++; } else sector++; }
C#
UTF-8
1,839
2.53125
3
[ "Apache-2.0" ]
permissive
using LLM; using LLMListView_Sample.Models; using LLMListView_Sample.ViewModels; using System.Linq; using Windows.UI.Xaml.Controls; namespace LLMListView_Sample.Views { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private MainPageViewModel _viewModel = new MainPageViewModel(); public MainPage() { this.InitializeComponent(); this.DataContext = _viewModel; } private void LLMListView_ItemSwipeBeginTrigger(object sender, LLM.SwipeReleaseEventArgs args) { if (_viewModel._oldListItem != null && _viewModel._oldListItem != sender) { //reset old list item ((MyCustomClass)_viewModel._oldListItem.Content).IsSwipedLeft = false; ((MyCustomClass)_viewModel._oldListItem.Content).IsSwipedRight = false; } var swipedItem = sender as LLMListViewItem; var swipedItemDataContext = swipedItem.Content as MyCustomClass; //set new list item in local reference _viewModel._oldListItem = swipedItem; //Note: Uncomment to see Fix Swipe Mode break's and one of the item's right to left swipe stop's working //trying to change swiped item RightSwipeLength //if (swipedItemDataContext.IsVisible) //{ // swipedItem.RightSwipeMaxLength = 80.0; //} //else //{ // swipedItem.RightSwipeMaxLength = 180.00; //} //Set Selected Item _viewModel.Selected = _viewModel.MyItemSource.FirstOrDefault(p => p.Text1.Equals(swipedItemDataContext.Text1)); } } }
JavaScript
UTF-8
2,219
3
3
[]
no_license
import DisjointSetItem from './DisjointSetItem' export default class DisjointSet { /** * 并查集 * @param {function(value:*)} keyCallback */ constructor(keyCallback) { this.keyCallback = keyCallback // 集合中的元素 this.items = {} } /** * 构造并查集中的元素 * @param {*} itemValue * @returns {DisjointSet} */ makeSet(itemValue) { const disjointSetItem = new DisjointSetItem(itemValue, this.keyCallback) // 如果之前没添加过,再进行添加 if (!this.items[disjointSetItem.getKey()]) { this.items[disjointSetItem.getKey()] = disjointSetItem } return this } /** * 查找某个元素属于哪个集合 * @param {*} itemValue * @returns {string|null} */ find(itemValue) { const templateDisjointItem = new DisjointSetItem( itemValue, this.keyCallback ) const requireDisjointItem = this.items[templateDisjointItem.getKey()] if (!requireDisjointItem) { return null } return requireDisjointItem.getRoot().getKey() } /** * Rank合并 * @param {*} valueA * @param {*} valueB * @returns {DisjointSet} */ union(valueA, valueB) { const rootKeyA = this.find(valueA) const rootKeyB = this.find(valueB) if (rootKeyA === null || rootKeyB === null) { throw new Error('One or two values are not in sets') } // 如果两个元素已经在同一个集合中直接返回 if (rootKeyA === rootKeyB) { return this } const rootA = this.items[rootKeyA] const rootB = this.items[rootKeyB] // 如果rootB树比rootA树大,rootB作为根节点 if (rootA.getRank() < rootB.getRank()) { rootB.addChild(rootA) return this } // 否则rootA作为根节点 rootA.addChild(rootB) return this } /** * 判断两个元素是否在同一个集合 * @param {*} valueA * @param {*} valueB * @returns {boolean} */ inSameSet(valueA, valueB) { const rootKeyA = this.find(valueA) const rootKeyB = this.find(valueB) if (rootKeyA === null || rootKeyB === null) { throw new Error('One or two values are not in sets') } return rootKeyA === rootKeyB } }
Java
UTF-8
3,321
2.328125
2
[]
no_license
package biai.main.execute; import biai.models.TestData; import biai.models.TrainingData; import biai.neuralnet.NeuralNet; import biai.testdatapreparer.TestDataPreparer; import org.encog.Encog; import org.encog.ml.data.MLDataSet; import org.encog.neural.networks.BasicNetwork; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.context.annotation.PropertySource; import biai.trainingdatapreparer.TrainingDataPreparer;; import javax.annotation.Resource; import java.util.Properties; @PropertySource(value = "claspath:/neutralnet.properties") public class NeuralNetLife { @Autowired private NeuralNet neuralNet; @Resource(name = "neuralNetProperties") private Properties properties; @Autowired private TrainingDataPreparer trainingDataPreparer; @Autowired private TestDataPreparer testDataPreparer; public void executeNeuralNetLife() { try { System.out.println(properties.getProperty("welcomeMessage")); int layerNumber = Integer.parseInt(properties.getProperty("layerNumber")); String layerSizesString = properties.getProperty("layerSizes"); String[] layerSizesArr = layerSizesString.split(","); int[] layerSizesInt = new int[layerSizesArr.length]; for(int i=0;i<layerSizesInt.length;++i) layerSizesInt[i] = Integer.parseInt(layerSizesArr[i]); BasicNetwork cardNetwork = neuralNet.createBasicNetwork(layerNumber, layerSizesInt); TrainingData trainingData = trainingDataPreparer.readTrainingDataFromFile(properties.getProperty("inputFile")); trainingDataPreparer.normalizeTrainingData(trainingData); MLDataSet trainingSet = neuralNet.createDataSet(trainingData.getInputArray(), trainingData.getOutputArray()); int maxEpochs = Integer.parseInt(properties.getProperty("maxEpochs")); double minError = Double.parseDouble(properties.getProperty("minError")); neuralNet.trainNeuralNet(cardNetwork, trainingSet, maxEpochs, minError); TestData testData = testDataPreparer.readTestDataFromFile(properties.getProperty("testFile")); testDataPreparer.normalizeInputTestData(testData); MLDataSet testSet = neuralNet.createDataSet(testData.getInputData(), testData.getOutputData()); neuralNet.testNeuralNet(cardNetwork, testSet, testData.getOutputData()); testDataPreparer.retriveOutputTestData(testData); testDataPreparer.saveTofile(properties.getProperty("outputFile"), testData.getOutputList()); Encog.getInstance().shutdown(); } catch (Exception en){ System.out.print(en); return; } return; } @Required public void setNeuralNet(final NeuralNet neuralNet) { this.neuralNet = neuralNet; } @Required public void setTrainingDataPreparer(final TrainingDataPreparer trainingDataPreparer) { this.trainingDataPreparer = trainingDataPreparer; } @Required public void setTestDataPreparer(final TestDataPreparer testDataPreparer) { this.testDataPreparer = testDataPreparer; } }
Python
UTF-8
364
3.703125
4
[]
no_license
string_a = "{}".format(10) print(string_a) print(type(string_a)) format_a = "{}만 원".format(5000) format_b = "파이썬 열공하여 첫 연봉 {}만 원 만들기".format(5000) format_c = "{} {} {}".format(3000, 4000, 5000) format_d = "{} {} {}".format(1, "문자열", True) print(format_a) print(format_b) print(format_c) print(format_d)
C#
UTF-8
2,424
3.609375
4
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace AnalysisOfEnvelopes { class View { public double InputFirstSide() { Console.WriteLine("Enter A side:"); double aSide = double.Parse(Console.ReadLine()); while ((aSide <= 0) || (aSide >= 51)) { Console.WriteLine("Side A must be bigger than 0 and lower than 51\nEnter A side:");//Почему 51 aSide = double.Parse(Console.ReadLine()); } return aSide; } public double InputSecondSide() { Console.WriteLine("Enter B side:"); double bSide = double.Parse(Console.ReadLine()); while ((bSide <= 0) || (bSide >= 51)) { Console.WriteLine("Side B must be bigger than 0 and lower than 51\nEnter B side:");//Почему 51 bSide = double.Parse(Console.ReadLine()); } return bSide; } public double InputThirdSide() { Console.WriteLine("Enter C side:"); double cSide = double.Parse(Console.ReadLine()); while ((cSide <= 0) || (cSide >= 51)) { Console.WriteLine("Side C must be bigger than 0 and lower than 51\nEnter C side:");//Почему 51 cSide = double.Parse(Console.ReadLine()); } return cSide; } public double InputFourthSide() { Console.WriteLine("Enter D side:"); double dSide = double.Parse(Console.ReadLine()); while ((dSide <= 0) || (dSide >= 51)) { Console.WriteLine("Side D must be bigger than 0 and lower than 51\nEnter D side:");//Почему 51 dSide = double.Parse(Console.ReadLine()); } return dSide; } public void NewAnalysisOfEnvelopes() { string answer;//Валидация ответа do { AnalysisOfEnvelopes analysisOfEnvelopes = new AnalysisOfEnvelopes(InputFirstSide(), InputSecondSide(), InputThirdSide(), InputFourthSide()); analysisOfEnvelopes.CompareSides(); Console.WriteLine("Do you want to continue?(y/n)"); answer = Console.ReadLine(); } while (answer == "y"); } } }
Markdown
UTF-8
341
2.609375
3
[]
no_license
# Very-Simple-CRUD A very simple CRUD console application with storing data in an "Arraylist". I'm using: Java 8, IntelliJ IDEA, GitHub / Git, JUnit Очень простое консольное приложение CRUD с сохранением данных в "Arraylist". Использую: Java 8, IntelliJ IDEA, GitHub/Git, JUnit
Swift
UTF-8
5,768
2.59375
3
[]
no_license
// // TripListTableViewController.swift // sally201UI // // Created by Sally on 4/20/19. // Copyright © 2019 Sally. All rights reserved. // import UIKit import MapKit class TripListTableViewController: UITableViewController { let shared = TripDataModel.sharedInstance let user = User(username: LoggedInUser, password: "N/A") override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) let closure : ([Trip]) -> () = { responseArray in for i in 0..<responseArray.count{ print(responseArray[i].tripName) } DispatchQueue.main.async{ self.shared.currentTrips = responseArray print(self.shared.currentTrips.count) self.tableView.reloadData() } } shared.getCurrentTrips(user: user, closure) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows print(shared.currentTrips.count) return shared.currentTrips.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "tripCell", for: indexPath) as! TripTableViewCell let tripForRow = shared.currentTrips[indexPath.row] let dateString = getDateString(trip: tripForRow) cell.setData(city: tripForRow.tripName, date: dateString) // if let activity = sharedInstance.currentTrips[indexPath.row]{ // // let url = URL(string: activity.Image) // // cell.setData(foodImageURL: url, title: activity.Name) // } else { // let url = URL(string: "") // cell.setData(foodImageURL: url, title: "Panda Express") // } // Configure the cell... return cell } func getDateString(trip: Trip) -> String { var beginString = "N/A" var endString = "N/A" let dateBegin = getDate(string: trip.date_Begin) let dateEnd = getDate(string: trip.date_End) let formatter = DateFormatter() formatter.dateFormat = "MM/dd" if let begin = dateBegin{ beginString = formatter.string(from: begin) } if let end = dateEnd{ endString = formatter.string(from: end) } return ("\(beginString) - \(endString)") } func getDate(string: String) -> Date?{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX let date = dateFormatter.date(from: string) return date } func fetchCityAndCountry(from location: CLLocation, completion: @escaping (_ city: String?, _ error: Error?) -> ()){ CLGeocoder().reverseGeocodeLocation(location){ placemarks, error in completion(placemarks?.first?.locality, error) } } /*func getCityName(trip: Trip) -> String{ }*/ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "tripInfo"){ print("segue") let infoViewController = segue.destination as! TripViewController if let indexPath = tableView.indexPathForSelectedRow{ infoViewController.tripData = shared.currentTrips[indexPath.row] } } } }
Markdown
UTF-8
10,730
2.515625
3
[]
no_license
--- date: 2020-12-2T17:09:00-04:00 title: "Mengumpulkan Review Konsumen Tidak Pernah Semudah Ini" categories: - Blog tags: - Machine Learning - Artificial Intelligence - Web Scrape - Home Tester - Market Research - Konsumen - Review Konsumen - Research - RVest - Tutorial --- Di dunia *market research*, data terkait konsumen bisa dibagi menjadi dua: 1. Data persepsi. 2. Data habit. ----- ## Data Persepsi Persepsi (dari bahasa Latin: *perceptio* atau *percipio*) adalah tindakan menyusun, mengenali, dan menafsirkan informasi sensoris guna memberikan gambaran dan pemahaman tentang lingkungan. Data persepsi merupakan data yang berasal dari pemahaman, ide, atau pendapat pribadi dari konsumen. Untuk mendapatkan data ini, cara terbaik yang bisa dilakukan adalah dengan cara survey (DITANYAKAN langsung kepada responden). ----- ## Data Habit Habit atau kebiasaan adalah suatu hal yang lazim, umum, dan yang biasa dilakukan. Menurut Peter Cape (2013): > *When you ask people randomly throughout the day what they are doing > (behavior), 30% of the time there will be a mismatch between what they > are doing and what they are thinking about.* Oleh karena itu, cara terbaik untuk mendapatkan data ini adalah dengan memanfaatkan sumber data lain seperti jejak digital, data transaksi, dan lainnya. Data seperti ini sebaiknya tidak ditanyakan langsung. Jika terpaksa ditanyakan langsung, sebaiknya ada metode untuk melakukan validasi atas jawaban tersebut. ----- Sebagai *market researcher*, saya tahu betul bagaimana sulitnya mencari data persepsi. Berdasarkan pengalaman saya selama ini, saya sangat percaya bahwa metode seperti *face-to-face* interview adalah cara terbaik untuk mendapatkan data persepsi konsumen. Namun biasanya ada tiga hal yang membuat F2F interview menjadi sulit dilakukan: 1. Waktu yang mepet. 2. Biaya yang terbatas. 3. Kekurangan tenaga (*man power*). Di zaman transformasi digital seperti sekarang ini, kadang kita hanya butuh duduk sejenak dan mencari apa yang kita mau di internet. Sama seperti mencari data persepsi konsumen. > Jika dulu saya harus mencari konsumen untuk dijadikan responden. Kini > responden sendiri yang **“datang”** memberikan data persepsinya. *Lho, gimana maksudnya?* ----- Beberapa waktu lalu, seorang rekan kerja saya menginformasikan mengenai keberadaan situs yang menampung *review* konsumen bernama [*Home Tester Club Indonesia*](https://www.hometesterclub.com/id/id/). ![](https://raw.githubusercontent.com/ikanx101/ikanx101.github.io/master/_posts/home%20tester%20club/blog-post_files/figure-gfm/unnamed-chunk-1-1.png)<!-- --> ----- ## Situs Home Tester Club Indonesia Berdasarkan informasi di situsnya: > *Home Tester Club* adalah komunitas para pembeli yang menguji dan > membagikan *review* produk untuk membantu pembeli lainnya berbelanja > lebih baik. *Home Tester Club* adalah rumahnya ribuan *review* produk. > Dengan bergabung di sini kamu akan mendapat kesempatan menguji coba > produk gratis dan produknya akan diantar langsung ke rumah kamu. Namun demikian, tidak semua *member* mendapatkan produk gratis untuk diuji. Beberapa *member* masih bisa memberikan *review* berdasarkan pengalaman pribadi mereka menggunakan produk yang mereka beli dengan uang pribadi. Jika kita asumsikan semua *member* memberikan *review* yang jujur, maka data *review* ini sangat kaya akan informasi. ----- ## Bagaimana cara saya mengeksplorasi data ini? Sebelum berbicara lebih jauh mengenai cara saya mengeksplorasi, pertanyaan paling mendasar yang harus saya jawab adalah: > **Bagaimana cara saya mengambil semua data yang ada di situs > tersebut?** Pertanyaan di atas adalah pertanyaan **paling standar** yang biasa dihadapi oleh semua orang di zaman sekarang. *hehe* ----- ## *Webscraping* **Home Tester Club** Seperti biasa, saya menggunakan **R** untuk membuat beberapa baris algoritma yang bertugas untuk mendapatkan data yang saya mau. Dari situs tersebut, ada beberapa data yang bisa saya ambil, yakni: 1. Nama produk. 2. Deskripsi produk. 3. *Rating* produk. 4. Berapa banyak *reviewers*. 5. Isi komentar atau *review*. Berikut adalah *functions* algoritma yang saya buat: ``` r scrape_func = function(url){ data = read_html(url) %>% {tibble( merek = html_nodes(.,"#htc-breadcrumb .active") %>% html_text(), rate = html_nodes(.,".pp-ratereview-counter li") %>% html_text() %>% paste(collapse = " "), deskripsi = (html_nodes(.,".text-left") %>% html_text())[[1]] )} return(data) } ``` Cukup gunakan *function* tersebut ke *links* masing-masing produk di situs tersebut. Sebagai *showcase*, saya akan mengambil `384` produk yang ada di kategori [**Dapur Makanan**](https://www.hometesterclub.com/id/id/reviews/category-food-pantry). *Links* `384` produk itu tersedia di [sini](https://raw.githubusercontent.com/ikanx101/belajaR/master/Bukan%20Infografis/Home%20Tester%20Club/Scraping%20Bahan/links.txt). Data saya *scrape* pada tanggal `1 Desember 2020 pukul 14∶34∶57 WIB`. ----- ## *Showcase*: Semua Produk di Kategori **Dapur Makanan** Setelah saya bersihkan data hasil *scrape*, saya dapatkan data berupa tabel seperti di bawah ini: ## [1] "Contoh 10 data teratas hasil scrape" ## # A tibble: 10 x 4 ## merek rate_no review_no deskripsi ## <chr> <dbl> <dbl> <chr> ## 1 Bango Bumbu Kuline… 4.8 61 "Sajikan berbagai #KelezatanAsli daera… ## 2 Oreo Dutch Cocoa W… 4.8 1555 "" ## 3 JAWARA Cabai Tabur… 4.6 1332 "" ## 4 JAWARA Cabai Tabur… 4.6 1272 "" ## 5 Mayumi 4.8 1119 "Saus creamy serbaguna yang terbuat da… ## 6 Royco Kaldu Jamur 4.7 1314 "" ## 7 Roti Tawar Funwari… 4.8 920 "Roti tawar yang dibuat dengan menggun… ## 8 Koko Krunch dengan… 4.9 4904 "Sereal sarapan dengan gandum utuh ras… ## 9 Serasa Food Bumbu … 4.7 205 "Bumbu berkualitas tinggi, menggunakan… ## 10 Finna Bumbu Masak … 4.6 228 "bumbu Tom Yum yang terbuat dari bahan… Mari kita cek beberapa analisa sederhana berikut ini: ----- ### *Top Reviewed Product* Dari `384` produk yang ada di kategori **dapur makanan**, ada beberapa produk yang paling banyak di-*review* oleh *member*. Mari kita lihat **Top 20** produk yang paling banyak di-*review*. <img src="https://raw.githubusercontent.com/ikanx101/ikanx101.github.io/master/_posts/home%20tester%20club/blog-post_files/figure-gfm/unnamed-chunk-4-1.png" width="672" /> Sekarang kebalikannya, kita cek 20 produk terbawah yang paling sedikit di-*review* oleh *member*: <img src="https://raw.githubusercontent.com/ikanx101/ikanx101.github.io/master/_posts/home%20tester%20club/blog-post_files/figure-gfm/unnamed-chunk-5-1.png" width="672" /> ### Sebaran Banyaknya *Reviews* Kalau kita lihat sebaran data banyaknya *reviews*, saya dapatkan informasi berikut: <img src="https://raw.githubusercontent.com/ikanx101/ikanx101.github.io/master/_posts/home%20tester%20club/blog-post_files/figure-gfm/unnamed-chunk-6-1.png" width="672" /> Dari graifk sebaran di atas, kita bisa melihat ada ketidakmerataan banyaknya *reviews* yang diberikan oleh *member*. Sebagian kecil produk mendapatkan lebih dari `1000` *reviews*. Mayoritas dari produk mendapatkan *reviews* sebanyak 128.5 (nilai tengah - median - dari data *review*). Kita bisa melihat bahwa beberapa produk Nutrifood mendapatkan *reviews* di kisaran angka tersebut kecuali produk **Tropicana Slim Beras Merah** yang mendapatkan *reviews* yang cukup banyak sehingga masuk **Top 20 Reviewed Products**. ### *Top Rating Product* *Member* bisa memberikan *rating* kepada produk yang pernah dikonsumsinya menggunakan skala `1-5`. Produk apa saja yang mendapatkan *rating* terbaik? <img src="https://raw.githubusercontent.com/ikanx101/ikanx101.github.io/master/_posts/home%20tester%20club/blog-post_files/figure-gfm/unnamed-chunk-7-1.png" width="672" /> Mungkin kalian bertanya-tanya, kenapa `59` produk yang ditampilkan? Karena produk urutan ke `60` memiliki nilai yang sama dengan produk urutan ke `61` sampai produk urutan ke `116`. ### Sebaran *Rating* Produk Mari kita lihat bersama bagaimana sebaran dari *rating* yang diberikan oleh *member*: <img src="https://raw.githubusercontent.com/ikanx101/ikanx101.github.io/master/_posts/home%20tester%20club/blog-post_files/figure-gfm/unnamed-chunk-8-1.png" width="672" /> Ternyata mayoritas produk memiliki rating yang baik (diatas skala `4`). Hanya sebagian kecil produk saja yang memiliki rating dibawah `3.5`. Penasaran produk apa saja yang mendapatkan nilai rendah di antara produk-produk yang bergelimang rating bagus? ## [1] "Produk yang memiliki rating di bawah 3.5" ## # A tibble: 6 x 3 ## merek rate_no review_no ## <chr> <dbl> <dbl> ## 1 Bee Huat Crisp Chocolate 3.4 111 ## 2 Biskotto Maxi Class 3.3 76 ## 3 Indomie Bite Mie 3.3 233 ## 4 Snek Ku ShoyueMi Rasa Pedas 3 71 ## 5 Chocomory Mini Choco Bar Cashew 2.5 3 ## 6 Gado Telur Siap Saji 0 0 Hanya ada `6` produk yang memiliki rating di bawah `3.5`. *Special cases* ada pada **Chocomory** dan **Gado Telur**: - Hanya ada `3` *member* saja yang memberikan *rating* dan *review* pada produk **Chocomory**. - Belum ada *member* yang memberikan *rating* dan *review* pada produk **Gado Telur Siap Saji**. ----- # *What’s Next?* ## Beberapa Produk yang Ada di Kategori **Dapur Makanan** Ternyata setelah saya lihat dengan seksama, ada beberapa pasang produk dan kompetitornya yang ada di sana. Menarik jika kita lakukan analisa *head-to-head* dari pasangan produk tersebut. Apa saja analisanya? > Tentunya analisa terkait dengan data komentar *member* yang berupa > *free text*. Hal yang bisa dilakukan: 1. *Wordcloud*, 2. *Bigrams*, 3. *Topic modelling* 4. *Crosswords* 5. *Log odds ratio* Nah, ada satu hal baru yang ingin saya lakukan (karena dari dulu belum sempat mengerjakannya). Apa itu? *Sentiment analysis*. Doakan semoga yang terakhir ini bisa dilakukan dengan baik *yah*. Sekian dulu tulisan ini, hasil analisa komentar akan saya tulis di tulisan berikutnya. --- Dukung selalu _blog_ ini agar bisa terus bertumbuh dengan cara klik iklan selepas Kamu membaca setiap tulisan yang ada _yah_.
Markdown
UTF-8
1,877
2.96875
3
[]
no_license
--- permalink: /finding-mods/ --- # Finding Mods There are two primary places to acquire mods for BL2 and TPS: Github and Nexus Mods. Github has been the primary place to store mods for some time now, but more modders have been using Nexus recently. ## ModCabinet The ModCabinet wiki is a place where github mods get sorted out into categories, and it's the preferred way to find BL2/TPS mods. It gives you a nice way to browse through the mods to see what's there. You can [find the ModCabinet wiki here](https://github.com/BLCM/ModCabinet/wiki). The ModCabinet automatically gets updated when modders add or update mods to the BLCM Github repo. [![ModCabinet Header](/img/bl2modcabinet.png)](/img/bl2modcabinet.png) ## Direct Github Access You can also download mods for both BL2 and TPS directly from [the BLCMods Github page](https://github.com/BLCM/BLCMods), though the process can be a bit confusing for github newbies. When you browse to a mod file you want to download, it will either have a `Raw` button or a `Download` button, in the upper right hand corner of the file's contents: [![Raw Button](/img/github_raw.png)](/img/github_raw.png) [![Download Button](/img/github_download.png)](/img/github_download.png) Right-click on that button and choose `Save Link As...` to save the file to your computer, and then use BLCMM to import the mod. ## Nexus Downloading and finding mods on Nexus is more straightforward than on Github, though you do need an account on Nexus in order to download mods. - [Borderlands 2 Mods at Nexus](https://www.nexusmods.com/borderlands2) - [Borderlands: The Pre-Sequel Mods at Nexus](https://www.nexusmods.com/borderlands2) # Other Links For information about how to use the mods you've downloaded, see [Running Mods](/running-mods/). For information on some of the major mod packs, see [Major Mod Packs](/mod-packs/).
Shell
UTF-8
378
3.703125
4
[]
no_license
#!/bin/sh for selected_jpg in *.jpg do new_suffix='.png' #echo "$selected_jpg" selected_filename=` echo $selected_jpg | cut -d. -f1 ` selected_png=${selected_filename}${new_suffix} #echo "$selected_png" if [ -e "$selected_png" ] then echo "$selected_png" already exists exit 1 fi convert "$selected_jpg" "$selected_png" done
Python
UTF-8
3,191
2.671875
3
[ "Apache-2.0" ]
permissive
import logging import os from functools import partial from pathlib import Path from gluonts.dataset.common import TrainDatasets, load_datasets from gluonts.dataset.repository._lstnet import generate_lstnet_dataset from gluonts.dataset.repository._m4 import generate_m4_dataset m4_freq = "Hourly" pandas_freq = "H" dataset_path = Path(f'm4-{m4_freq}') prediction_length = 48 dataset_recipes = { # each recipe generates a dataset given a path "m4_hourly": partial( generate_m4_dataset, m4_freq="Hourly", pandas_freq="H", prediction_length=48, ), "m4_daily": partial( generate_m4_dataset, m4_freq="Daily", pandas_freq="D", prediction_length=14, ), "m4_weekly": partial( generate_m4_dataset, m4_freq="Weekly", pandas_freq="W", prediction_length=13, ), "m4_monthly": partial( generate_m4_dataset, m4_freq="Monthly", pandas_freq="M", prediction_length=18, ), "m4_quarterly": partial( generate_m4_dataset, m4_freq="Quarterly", pandas_freq="3M", prediction_length=8, ), "m4_yearly": partial( generate_m4_dataset, m4_freq="Yearly", pandas_freq="12M", prediction_length=6, ), "exchange_rate": partial( generate_lstnet_dataset, dataset_name="exchange_rate" ), "electricity": partial( generate_lstnet_dataset, dataset_name="electricity" ), "traffic": partial(generate_lstnet_dataset, dataset_name="traffic"), "solar-energy": partial( generate_lstnet_dataset, dataset_name="solar-energy" ), } dataset_names = list(dataset_recipes.keys()) def get_dataset( dataset_name: str, regenerate: bool = False, path: str = "./" ) -> TrainDatasets: """ Parameters ---------- dataset_name name of the dataset, for instance "m4_hourly" regenerate whether to regenerate the dataset even if a local file is present. If this flag is False and the file is present, the dataset will not be downloaded again. path where the dataset should be saved Returns ------- dataset obtained by either downloading or reloading from local file. """ assert ( dataset_name in dataset_recipes.keys() ), f"{dataset_name} is not present, please choose one from {dataset_recipes.keys()}." dataset_path = Path(path) / dataset_name dataset_recipe = dataset_recipes[dataset_name] if not os.path.exists(dataset_path) or regenerate: logging.info(f"downloading and processing {dataset_name}") dataset_recipe(dataset_path=dataset_path) else: logging.info( f"using dataset already processed in path {dataset_path}." ) return load_datasets( metadata=dataset_path, train=dataset_path / 'train', test=dataset_path / 'test', ) if __name__ == '__main__': for dataset in dataset_names: print(f"generate {dataset}") ds = get_dataset(dataset, regenerate=True) print(ds.metadata) print(sum(1 for _ in list(iter(ds.train))))
Python
UTF-8
3,106
3.125
3
[]
no_license
""" Program author name: Analia Treviño-Flitton - This function opens and reads in a file with the results from a local BLASTx search. It parses the document for the Best Hit, the E-value, and the Identities then saves them to a text document. """ def blast_parser(file): # Regex for query import re ## Open & Read with open(file, 'r') as f: blast_file = f.read() re_query = r"Query=\s(\w+)" query = re.findall(re_query, blast_file) # Regex for BestHit re_best = r"(>\w+.+\w+.+\s+\w+.+\w.+)" best = re.findall(re_best, blast_file) best_list = [] # Trim over shoot for i in range(len(best)): list_item = re.sub(r"(\n\s+Length.+\d)", "", (best[i])) best_list.append(list_item) # Regex for E-val re_eval = r"(\d[e].\d+)" e_val = re.findall(re_eval, blast_file) # Only keep the 1st of 4 returned e_val = (e_val[0::4]) # Regex for IDs re_id = r"Identities\s.\s(\d+.\d+\s.\d+..)" iden = re.findall(re_id, blast_file) # Write output file out_file = open("blastxParse_results.txt", 'w') out_file.write("Summary of Blastx Results\n\n") for i in (range(0, (len(query)))): formatting = query[i], "\tBest Hit: " + best_list[i], "\n\nE-Value: " + e_val[i], "\t\tIdentities: " + iden[i], "\n\n\n\n" for x in formatting: out_file.write(str(x)) out_file.write("Written by Analia Treviño-Flitton\n\n") out_file.close() x = "BlastResults.txt" blast_parser(x) def user_blast_parser(): ## Regex for query import re ## User Input file_name = str(input("Please enter the name of the BLASTx results file you would like to parse:")) out_file_name = str(input("Please name the file you would like to save the results to including file extension ")) ## Open & Read with open(file_name, 'r') as f: blast_file = f.read() re_query = r"Query=\s(\w+)" query = re.findall(re_query, blast_file) # Regex for BestHit (lowest E-val) re_best = r"(>\w+.+\w+.+\s+\w+.+\w.+)" best = re.findall(re_best, blast_file) best_list = [] # Trim over shoot for i in range(len(best)): list_item = re.sub(r"(\n\s+Length.+\d)", "", (best[i])) best_list.append(list_item) # Regex for E-val re_eval = r"(\d[e].\d+)" e_val = re.findall(re_eval, blast_file) # Only keep the 1st of 4 returned e_val = (e_val[0::4]) # Regex for IDs re_id = r"Identities\s.\s(\d+.\d+\s.\d+..)" iden = re.findall(re_id, blast_file) # Write output file out_file = open(out_file_name, 'w') out_file.write("Summary of Blastx Results\n\n") for i in (range(0, (len(query)))): formatting = query[i], "\tBest Hit: " + best_list[i], "\n\nE-Value: " + e_val[i], "\t\tIdentities: " + iden[i], "\n\n\n\n" for x in formatting: out_file.write(str(x)) out_file.write("Written by Analia Treviño-Flitton\n\n") out_file.close() user_blast_parser()
C++
UTF-8
2,445
2.5625
3
[]
no_license
#include <stdlib.h> //#include <random> #include <opencv2/opencv.hpp> //#include <float.h> #include "imio.hpp" using namespace cv; //using namespace std; float mean_c[3] = {104,117,123}; int img_in(char* file_path, float** pdst, int* c, int* h, int* w){ Mat img; img = imread(file_path); if(!img.data){ return -1; } unsigned char *data = img.data; *c = img.channels(); *h = img.rows; *w = img.cols; int count = (*c)*(*h)*(*w); *pdst = (float*) malloc(count*sizeof(float)); float *it = *pdst; for(int c_ = 0;c_<img.channels();c_++){ for(int i = 0;i<img.rows*img.cols;i++){ *(it) = (float)(data[img.channels()*i+c_]-mean_c[c_]); it++; } } return 0; } /* int noise(float* dst, int c, int h, int w){ default_random_engine e; uniform_real_distribution<float> u(0,10); for(int i = 0;i<c*h*w;i++){ dst[i] = u(e); } return 0; } */ int img_out(char* file_path, float* src, int c, int h, int w){ //linear_map(src,c,h,w); Mat img; img.create(h,w,CV_8UC(c)); unsigned char *data = img.data; for(int c_ = 0;c_<c;c_++){ for(int i = 0;i<h*w;i++){ float pix = (*src)+mean_c[c_]; pix = pix<0?0:pix; pix = pix>255?255:pix; data[i*c+c_] = (unsigned char)pix; src++; } } imwrite(file_path,img); return 0; } int img_show(float* src, int c, int h, int w){ Mat img; img.create(h,w,CV_8UC(c)); unsigned char *data = img.data; for(int c_ = 0;c_<c;c_++){ for(int i = 0;i<h*w;i++){ float pix = (*src)+mean_c[c_]; pix = pix<0?0:pix; pix = pix>255?255:pix; data[i*c+c_] = (unsigned char)pix; src++; } } namedWindow("imshow", WINDOW_AUTOSIZE); imshow("imshow", img); waitKey(0); return 0; } void sub_mean(float* src, float* mean, int c, int h, int w){ float sum = 0; for(int i = 0;i<c*h*w;i++){ sum+=src[i]; } sum/=(c*h*w); *mean = sum; for(int i = 0;i<c*h*w;i++){ src[i]-=sum; } } void add_mean(float* src, float mean, int c, int h, int w){ for(int i = 0;i<c*h*w;i++){ src[i]+=mean; } } /* void linear_map(float* src, int c, int h, int w){ for(int c_ = 0; c_<c;c_++){ float min = FLT_MAX; float max = FLT_MIN; for(int h_ = 0;h_<h;h_++){ for(int w_ = 0;w_<w;w_++){ float pix = src[h_*w+w_]; min = (pix<min)?(pix):(min); max = (pix>max)?(pix):(max); } } float d = max-min; for(int h_ = 0;h_<h;h_++){ for(int w_ = 0;w_<w;w_++){ float pix = src[h_*w+w_]; src[h_*w+w_] = (255.0/d*(pix-min)); } } src+=(h*w); } } */
Java
UTF-8
7,112
2.09375
2
[]
no_license
package com.service.imp; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import com.dao.IBugDB; import com.pojo.Bug; import com.pojo.Comment; import com.pojo.Project; import com.pojo.User; import com.service.IBugsService; public class BugsService implements IBugsService { IBugDB iBugsDao; public void setiBugsDao(IBugDB iBugsDao) { this.iBugsDao = iBugsDao; } private static Logger logger = Logger.getLogger(BugsService.class); @Override public Boolean addbug(Bug bug) { // TODO Auto-generated method stub Boolean boolean1=false; try { String key=null; key=iBugsDao.addBug( bug); List<String> imgs=bug.getImages(); for (int i = 0; i < imgs.size(); i++) { if (!"upload/".equals(imgs.get(i))) { iBugsDao.addImage( key, imgs.get(i)); } } boolean1=true; } catch (Exception e) { // TODO Auto-generated catch block logger.error("提交bug录入出错!",e); }finally{ } return boolean1; } @Override public List<Bug> selectAllBugs(String start,String end) { // TODO Auto-generated method stub List<Bug> bugs=null; try { bugs=iBugsDao.showAllBugs( start, end); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return bugs; } @Override public Boolean updateBug(String Status, String bugId) { // TODO Auto-generated method stub Boolean flag=false; try { iBugsDao.updateBugStatus( bugId, Status); flag=true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return flag; } @Override public List<Project> selectProjects() { // TODO Auto-generated method stub List<Project> projects=null; try { projects=iBugsDao.selectProjects(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return projects; } @Override public List<User> selectUsers() { // TODO Auto-generated method stub List<User> users=null; try { users=iBugsDao.selectUsers(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return users; } @Override public Bug selectBugByID(String bugid) { // TODO Auto-generated method stub Bug bug=null; try { bug=iBugsDao.selectBugByID( bugid); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return bug; } @Override public Boolean updateBugProcessUser(String bugid, String uid) { // TODO Auto-generated method stub Boolean flag=false; try { iBugsDao.updateBugProcessUserid( bugid, uid); flag=true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return flag; } @Override public Boolean addcomment(Comment comment) { // TODO Auto-generated method stub Boolean res=false; try { iBugsDao.addComment( comment.getBugid(), comment.getContent(), comment.getUserid()); res=true; } catch (Exception e) { // TODO: handle exception }finally{ } return res; } @Override public String bugToMe(String uid) { // TODO Auto-generated method stub String count="0"; try { count=iBugsDao.bugToMe( uid); } catch (Exception e) { // TODO: handle exception }finally{ } return count; } @Override public String mySubmitBug(String uid) { // TODO Auto-generated method stub String count="0"; try { count=iBugsDao.mySubmitBug( uid); } catch (Exception e) { // TODO: handle exception }finally{ } return count; } @Override public String stillNotSolvedBug() { // TODO Auto-generated method stub String count="0"; try { count=iBugsDao.stillNotSolvedBug(); } catch (Exception e) { // TODO: handle exception }finally{ } return count; } @Override public String allBugCount() { // TODO Auto-generated method stub String count="0"; try { count=iBugsDao.allBugCount(); } catch (Exception e) { // TODO: handle exception }finally{ } return count; } @Override public String allSolvedBug() { // TODO Auto-generated method stub String count="0"; try { count=iBugsDao.allSolvedBug(); } catch (Exception e) { // TODO: handle exception }finally{ } return count; } @Override public List<Bug> selectbugToMe(String uid, String start, String end) { // TODO Auto-generated method stub List<Bug> bugs=null; try { bugs=iBugsDao.selectbugToMe(uid, start, end); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return bugs; } @Override public List<Bug> mySubmitBug(String uid, String start, String end) { // TODO Auto-generated method stub List<Bug> bugs=null; try { bugs=iBugsDao.mySubmitBug(uid, start, end); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return bugs; } @Override public List<Bug> stillNotSolvedBug(String start, String end) { // TODO Auto-generated method stub List<Bug> bugs=null; try { bugs=iBugsDao.stillNotSolvedBug(start, end); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return bugs; } @Override public List<Bug> allSolvedBug(String start, String end) { // TODO Auto-generated method stub List<Bug> bugs=null; try { bugs=iBugsDao.allSolvedBug(start, end); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ } return bugs; } @Override public Map<String, Object> getCount(String uid) { // TODO Auto-generated method stub String toMe=bugToMe(uid); String submitted=mySubmitBug(uid); String existed=stillNotSolvedBug(); String solved=allSolvedBug(); String allBug=allBugCount(); Map<String, Object> map= new HashMap<String, Object>(); map.put("toMe", toMe); map.put("submitted", submitted); map.put("existed", existed); map.put("solved", solved); map.put("allBug", allBug); return map; } @Override public Map<String,String> addPro(String proName, String proDesc) { // TODO Auto-generated method stub Map<String,String> msg=null; try { msg=iBugsDao.addPro(proName,proDesc); } catch (Exception e) { // TODO: handle exception } return msg; } @Override public void activePro(String id, String status) { // TODO Auto-generated method stub try { iBugsDao.activePro(id,status); } catch (Exception e) { // TODO: handle exception } } }
Python
UTF-8
7,903
2.65625
3
[ "MIT" ]
permissive
from typing import Callable, Optional, Union, Sequence import numpy as np import torch from torch.nn import Module from torch.nn.utils import clip_grad_norm_ from torch.optim import Optimizer from ..im.utils import identity, dmap, zip_equal, collect from .utils import * __all__ = 'optimizer_step', 'train_step', 'inference_step', 'multi_inference_step' def optimizer_step( optimizer: Optimizer, loss: torch.Tensor, scaler: Optional[torch.cuda.amp.GradScaler] = None, clip_grad: Optional[float] = None, accumulate: bool = False, **params, ) -> torch.Tensor: """ Performs the backward pass with respect to ``loss``, as well as a gradient step or gradient accumlation. If a ``scaler`` is passed - it is used to perform the gradient step (automatic mixed precision support). If a ``clip_grad`` is passed - gradient will be clipped by this value considered as maximum l2 norm. ``accumulate`` indicates whether to perform gradient step or just accumulate gradients. ``params`` is used to change the optimizer's parameters. Examples -------- >>> optimizer = Adam(model.parameters(), lr=1) >>> optimizer_step(optimizer, loss) # perform a gradient step >>> optimizer_step(optimizer, loss, lr=1e-3) # set lr to 1e-3 and perform a gradient step >>> optimizer_step(optimizer, loss, betas=(0, 0)) # set betas to 0 and perform a gradient step >>> optimizer_step(optimizer, loss, accumulate=True) # perform a gradient accumulation Notes ----- The incoming ``optimizer``'s parameters are not restored to their original values. """ set_params(optimizer, **params) if scaler is not None: # autocast is not recommended during backward with torch.cuda.amp.autocast(False): scaler.scale(loss).backward() if not accumulate: if clip_grad is not None: scaler.unscale_(optimizer) assert not isinstance(clip_grad, bool), "Use of boolean clip_grad value (e.g. False) can lead to " \ "unexpected behaviour. " clip_grad_norm_(get_parameters(optimizer), clip_grad) scaler.step(optimizer) scaler.update() else: loss.backward() if not accumulate: if clip_grad is not None: clip_grad_norm_(get_parameters(optimizer), clip_grad) optimizer.step() if not accumulate: optimizer.zero_grad(set_to_none=True) return loss def train_step( *inputs: np.ndarray, architecture: Module, criterion: Callable, optimizer: Optimizer, n_targets: int = 1, loss_key: Optional[str] = None, scaler: Optional[torch.cuda.amp.GradScaler] = None, clip_grad: Optional[float] = None, accumulate: bool = False, gradient_accumulation_steps: int = 1, **optimizer_params, ) -> np.ndarray: """ Performs a forward-backward pass, and make a gradient step or accumulation, according to the given ``inputs``. Parameters ---------- inputs inputs batches. The last ``n_targets`` batches are passed to ``criterion``. The remaining batches are fed into the ``architecture``. architecture the neural network architecture. criterion the loss function. Returns either a scalar or a dictionary of scalars. In the latter case ``loss_key`` must be provided. optimizer n_targets how many values from ``inputs`` to be considered as targets. loss_key in case ``criterion`` returns a dictionary of scalars, indicates which key should be used for gradient computation. scaler a gradient scaler used to operate in automatic mixed precision mode. clip_grad maximum l2 norm of the gradient to clip it by. accumulate whether to accumulate gradients or perform optimizer step. gradient_accumulation_steps optimizer_params additional parameters that will override the optimizer's current parameters (e.g. lr). Notes ----- Note that both input and output are **not** of type ``torch.Tensor`` - the conversion to and from ``torch.Tensor`` is made inside this function. References ---------- `optimizer_step` """ architecture.train() if n_targets >= 0: n_inputs = len(inputs) - n_targets else: n_inputs = -n_targets assert 0 <= n_inputs <= len(inputs) inputs = sequence_to_var(*inputs, device=architecture) inputs, targets = inputs[:n_inputs], inputs[n_inputs:] with torch.cuda.amp.autocast(scaler is not None or torch.is_autocast_enabled()): loss = criterion(architecture(*inputs), *targets) if loss_key is not None: optimizer_step( optimizer, loss[loss_key] / gradient_accumulation_steps, scaler=scaler, clip_grad=clip_grad, accumulate=accumulate, **optimizer_params, ) return dmap(to_np, loss) optimizer_step( optimizer, loss / gradient_accumulation_steps, scaler=scaler, clip_grad=clip_grad, accumulate=accumulate, **optimizer_params, ) return to_np(loss) def inference_step(*inputs: np.ndarray, architecture: Module, activation: Callable = identity, amp: bool = False) -> np.ndarray: """ Returns the prediction for the given ``inputs``. Notes ----- Note that both input and output are **not** of type ``torch.Tensor`` - the conversion to and from ``torch.Tensor`` is made inside this function. Inputs will be converted to fp16 if ``amp`` is True. """ architecture.eval() # NumPy >= 1.24 warns about underflow during cast which is really insignificant if amp: with np.errstate(under='ignore'): inputs = tuple(np.asarray(x, dtype=np.float16) for x in inputs) with torch.no_grad(): with torch.cuda.amp.autocast(amp or torch.is_autocast_enabled()): return to_np(activation(architecture(*sequence_to_var(*inputs, device=architecture)))) @collect def multi_inference_step(*inputs: np.ndarray, architecture: Module, activations: Union[Callable, Sequence[Union[Callable, None]]] = identity, amp: bool = False) -> np.ndarray: """ Returns the prediction for the given ``inputs``. The ``architecture`` is expected to return a sequence of torch.Tensor objects. Notes ----- Note that both input and output are **not** of type ``torch.Tensor`` - the conversion to and from ``torch.Tensor`` is made inside this function. Inputs will be converted to fp16 if ``amp`` is True. """ architecture.eval() # NumPy >= 1.24 warns about underflow during cast which is really insignificant if amp: with np.errstate(under='ignore'): inputs = tuple(np.asarray(x, dtype=np.float16) for x in inputs) with torch.no_grad(): with torch.cuda.amp.autocast(amp or torch.is_autocast_enabled()): results = architecture(*sequence_to_var(*inputs, device=architecture)) if callable(activations): activations = [activations] * len(results) for activation, result in zip_equal(activations, results): if activation is not None: result = activation(result) yield to_np(result) @np.deprecate def do_train_step(*inputs, lr, inputs2logits, optimizer, logits2loss): return train_step(*inputs, lr=lr, architecture=inputs2logits, criterion=logits2loss, optimizer=optimizer) @np.deprecate def do_inf_step(*inputs, inputs2logits, logits2pred): return inference_step(*inputs, architecture=inputs2logits, activation=logits2pred)
Markdown
UTF-8
5,300
2.546875
3
[]
no_license
### AVT Vimba与OpenCV环境配置 近来,由于项目需求,需要使用AVT的一款相机采集图像并进行相应的算法处理。环境的配置过程较为复杂,特此记录,以做备忘。也给有需要的小伙伴们一些key point的分享。 **搭建环境:Windows7 + Python2.7 + OpenCV3.0** ##### 1. Python2.7 由于平时的工作基本都是Mac或Linux平台,很少用到Windows,这次也把在Windows上面安装Python的过程做简单记录。 (1) 这里选择软件支持效果较好的Python2.7,[Python官网](https://www.python.org/downloads/)直接下载安装。 (2) 重量级的包管理器pip。[Pip官网](https://pypi.python.org/pypi/pip)下载二进制文件,解压到某个文件夹后,使用cmd进行安装。步骤是,cd到相应目录,输入`python setup.py install`。 ![安装pip](https://raw.githubusercontent.com/onlytjt/MarkdownSource/master/pic/Vimba_1.png) (3) 安装完毕后使用pip工具安装一些相当有用的lib,比如numpy,scipy,matplotlib等等。 ``` pip install numpy pip install scipy pip install matplotlib ``` ##### 2. OpenCV3.0 (1) 安装包在[OpenCV官网](http://opencv.org/)下载,网速原因,博主下载了好几次才成功。安装过程其实只是简单的解压缩。 (2) 由于使用Python API,进入OpenCV安装目录下`/build/python/2.7/cv2.pyd`。将cv2.pyd复制到Python安装目录下的`/Lib/site-packages/`。 至此就可以使用Python进行OpenCV的相关操作了。 ##### 3. AVT Vimba (1) [AVT官网](https://www.alliedvision.com/en/products/software.html)下载并安装。由于官方仅提供了C/C++的API,因此想使用Python的同学有几个选择:使用ctypes,或者使用pymba。 (2) 这里要感谢伟大的Github,给我们节约了无数的时间,也让我们能够学习到最先进的代码。pymba的Github地址,[https://github.com/morefigs/pymba]()。这里安装过程同pip,下载解压到某个文件夹后,使用cmd shell,cd到相应目录,输入`python setup.py install`。 ![安装pymba](https://raw.githubusercontent.com/onlytjt/MarkdownSource/master/pic/Vimba_2.png) (3) 这里要注意两点。一、pymba目前仅支持Vimba1.3的版本,因此下载更高版本的同学在后续使用过程中,可能会遇到各种Bug。二、在安装pymba之后,需要更改pymba默认索引的VimbaC.dll的路径。具体更改方法为找到`/pymba/vimbadll.py`将其中的Line13和Line16更改为自己VimbaC.dll的路径。我的如下: ``` vimbaC_path = r'D:\Program Files\Allied Vision\Vimba_1.4\VimbaC\Bin\VimbaC.dll' ``` 重新编译后,就可以尽情地在python中import了!哎~人生苦短,我用Python啊! 关于Vimba相关API的使用,建议查阅官方的Manual。关于cv2的使用,我后续还会持续更新,迫不及待的小伙伴,可以先自行Google。 最后,把我初步的代码附上,我尽可能地将注释写详细~ ```python # 实现功能:驱动AVT相机,实时显示图像 # 时间:2015.11.17 import cv2 import numpy as np import time from pymba import * class CameraInterface: def __init__(self): self.vimba = 0 self.camera = 0 self.cameraIds = 0 self.frame0 = 0 self.frame1 = 0 self.moreUsefulImgData = 0 def openCamera(self): self.vimba = Vimba() self.vimba.startup() print "The Vimba lib version is:", self.vimba.getVersion(), ", and vimba run successfully!" system = self.vimba.getSystem() # list available cameras (after enabling discovery for GigE cameras) system.runFeatureCommand("GeVDiscoveryAllOnce") time.sleep(0.2) self.cameraIds = self.vimba.getCameraIds() print "Available cameras", self.cameraIds self.camera = self.vimba.getCamera(self.cameraIds[0]) self.camera.openCamera() def setCameraFeature(self): # show camera default features and set some features #cameraFeatureNames = camera.getFeatureNames() #print cameraFeatureName print self.camera.AcquisitionMode self.camera.AcquisitionMode = 'SingleFrame' # announce memory for frame self.frame0 = self.camera.getFrame() self.frame1 = self.camera.getFrame() self.frame0.announceFrame() def captureFrame(self): self.camera.startCapture() self.frame0.queueFrameCapture() self.camera.runFeatureCommand('AcquisitionStart') self.camera.runFeatureCommand('AcquisitionStop') self.frame0.waitFrameCapture() imgData = self.frame0.getBufferByteData() self.moreUsefulImgData = np.ndarray(buffer = self.frame0.getBufferByteData(), dtype = np.uint8, shape = (self.frame0.height, self.frame0.width, 1)) self.camera.endCapture() def showImage(self): cv2.imshow("Show Image", self.moreUsefulImgData) def endShow(self): cv2.destroyAllWindows() self.vimba.shutdown() def main(): ins = CameraInterface() ins.openCamera() ins.setCameraFeature() while True: ins.captureFrame() ins.showImage() if cv2.waitKey(1) == 27: # press esc to quit break ins.endShow() if __name__ == "__main__": main() ``` *** **By tjt** **2015.11.17**
Java
UTF-8
523
3.234375
3
[]
no_license
package com.sam.design_patterns.interpreter; import org.apache.commons.lang3.StringUtils; public class NumberExpression implements Expression { private Integer number = 0; NumberExpression(int number) { this.number=number; } NumberExpression(String stringNumber) { if(!StringUtils.isEmpty(stringNumber)) { this.number=Integer.parseInt(stringNumber); } } @Override public int interpret() { return this.number; } @Override public String toString() { return this.number.toString(); } }
PHP
UTF-8
1,378
2.6875
3
[]
no_license
<?php namespace App; /** * @author * Web Design Enterprise * Website: www.webdesignenterprise.com * E-mail: info@webdesignenterprise.com * * @copyright * This work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/legalcode * * Be aware, violating this license agreement could result in the prosecution and punishment of the infractor. * * @copyright 2002- date('Y') Web Design Enterprise Corp. All rights reserved. */ class Log { private static $_log_file; public function __construct($msg) { self::$_log_file = $_SERVER['DOCUMENT_ROOT']._SITE_PATH.'/logs.log'; if (!file_exists(self::$_log_file)) { self::_create_log(); } if (filesize(self::$_log_file) > 20 * 1024 * 1024) { $new_file_name = '/logs.'.date('Y-m-d-H-i-s').'.log'; rename(self::$_log_file, $_SERVER['DOCUMENT_ROOT']._SITE_PATH.'/'.$new_file_name); self::_create_log(); } $log = "[".date('D M j H:i:s Y')."] [client ".$_SERVER["REMOTE_ADDR"]."] ".$msg."\n"; error_log($log, 3, self::$_log_file); } private static function _create_log() { touch(self::$_log_file); chmod(self::$_log_file, 0666); } }
JavaScript
UTF-8
1,511
3.03125
3
[]
no_license
function tab() { //Tabs let tab = document.getElementsByClassName('info-header-tab'), tabContent = document.getElementsByClassName('info-tabcontent'), info = document.getElementsByClassName('info-header')[0]; /*Скрываем контент (если а=0, то весь; если а=1, то всё, кроме 1-ой статьи (используется при первом запуске))*/ function hideTabContent(a) { for(i = a; i < tabContent.length; i++) { tabContent[i].classList.remove('show'); tabContent[i].classList.add('hide'); } }; //При первом запуске скрываем все вкладки, кроме первой hideTabContent(1); //Скрываем все табы и показываем только тот, по которому кликнули function showtabContent(b) { if(tabContent[b].classList.contains('hide')) { hideTabContent(0); tabContent[b].classList.remove('hide'); tabContent[b].classList.add('show'); } } /*Ждём клика по вкладкам. Слушаем родителя вкладки и перебираем массив со вкладками в поиске той, по которой кликнули*/ info.addEventListener('click', (event) => { let target = event.target; if(target.className == 'info-header-tab') { for(i = 0; i < tab.length; i++) { if(target == tab[i]) { showtabContent(i); break; } } }; }); }; module.exports = tab;
C
UTF-8
1,171
2.65625
3
[]
no_license
#include "pitch_pid.h" PID_CONFIG pitchPIDConfig; PID_STATUS pitchPIDStatus; float pitchPIDErrorIntegral; float pitchPIDLastError; float pitchPIDTarget; float lastTimeUpdate; void PITCH_PID_START(PID_CONFIG config){ pitchPIDConfig = config; pitchPIDStatus.error = 0.0f; pitchPIDStatus.errorIntegral = 0.0f; pitchPIDStatus.errorChange = 0.0f; pitchPIDLastError = 0.0f; pitchPIDErrorIntegral = 0.0f; pitchPIDTarget = 0.0f; lastTimeUpdate = 0.0f; } void PITCH_PID_SETPOINT(float setpoint){ pitchPIDTarget = setpoint; } void PITCH_PID_UPDATE(float source, float time) { float timeStep = time - lastTimeUpdate; float error = pitchPIDTarget - source; pitchPIDErrorIntegral += error; float derivativeError = (error - pitchPIDLastError); pitchPIDStatus.error = error; pitchPIDStatus.errorChange = derivativeError; pitchPIDStatus.errorIntegral = pitchPIDErrorIntegral; pitchPIDLastError = error; lastTimeUpdate = time; } void PITCH_PID_UPDATE_CONFIG(PID_CONFIG config){ pitchPIDConfig = config; } float PITCH_PID_GET_OUTPUT(){ return BASE_PID_GET_OUTPUT(pitchPIDStatus, pitchPIDConfig); }
Rust
UTF-8
2,950
2.78125
3
[ "MIT" ]
permissive
use std::io::Read; use std::io::Write; use std::net::SocketAddr; use std::net::{TcpListener, TcpStream}; use std::str::FromStr; use std::thread; extern crate chrono; use chrono::prelude::*; use ntp; pub fn run_server_udp(addr: &str, is_verbose: bool) { use std::mem::size_of; use std::net::UdpSocket; let socket = UdpSocket::bind(addr).expect("Could not bind to UDP socket"); println!("Starting NTP server on {}", addr); loop { let mut buffer = [0u8; size_of::<ntp::NTPHeader>()]; match socket.recv_from(&mut buffer) { Ok((n, addr)) => { let mut packet = ntp::NTPHeader::decode(n, &buffer).expect("Could not decode"); packet.receive_timestamp = ntp::NTPTimestamp::from_datetime(&Utc::now()); packet.transmit_timestamp = ntp::NTPTimestamp::from_datetime(&Utc::now()); packet.stratum = 8; let msg = packet.encode().expect("Could not encode"); socket.send_to(&msg, addr).expect("Could not send"); if is_verbose { println!("Received datagram from {}:\n{:#?}", addr, packet); } } Err(e) => { println!("Failed to receive: {}", e); } } } } #[allow(dead_code)] pub fn run_server_tcp(addr: &str, is_verbose: bool) { println!("Starting tcp server on {}", addr); let addr: SocketAddr = SocketAddr::from_str(addr).expect("Invalid address"); let listener = TcpListener::bind(addr).unwrap(); for stream in listener.incoming() { match stream { Ok(stream) => { thread::spawn(move || { handle_client(stream, is_verbose); }); } Err(_) => { println!("Error"); } } } } fn handle_client(mut stream: TcpStream, is_verbose: bool) { let source = stream .peer_addr() .map(|addr| format!("{}", addr)) .unwrap_or(String::from("unknown")); if is_verbose { println!("Received connection from {}", source); } loop { let mut read = [0u8; 10000]; match stream.read(&mut read) { Ok(n) => { if n == 0 { // connection was closed break; } let mut input = ntp::NTPHeader::decode(n, &read).expect("Could not decode NTP package"); input.transmit_timestamp = ntp::NTPTimestamp::from_datetime(&Utc::now()); let message = input.encode().expect("Could not encode NTP package"); stream .write_all(&message) .expect("Could not write response"); } Err(err) => { panic!("Failed to read client stream from {}. {}", source, err); } } } }
Java
UTF-8
12,052
1.976563
2
[]
no_license
package com.example.kevinhan.forgetaboutit; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.UUID; import androidx.appcompat.app.AppCompatActivity; public class SettingsActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { static final UUID myID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); static final String macAddress = "00:14:03:06:7E:E8"; Button toHome; Button toSchedule; Button connBt; TextView btStatus; BluetoothAdapter btAdapter; BluetoothDevice btDevice; BluetoothSocket btSocket; ConnectedThread thread = null; InputStream is; OutputStream os; Schedule schedule; Button getTag; TextView tag; String input = ""; int inputIdx = 0; Button confItem; EditText itemName; Item item; Event event; EditText eventName; EditText eventTime; Spinner events; Spinner daysOfWeek; int dayWeek = 6; boolean createEvent = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); Intent intent = getIntent(); schedule = intent.getParcelableExtra("EXTRA_SCHEDULE"); // Button to navigate to home toHome = (Button)findViewById(R.id.toHome); toHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openHome(); } }); // Button to navigate to schedule toSchedule = (Button) findViewById(R.id.toSchedule); toSchedule.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openSchedule(); } }); // Initialize text and button for Bluetooth btStatus = (TextView) findViewById(R.id.statusBt); // Bluetooth connBt = (Button) findViewById(R.id.connectBt); connBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { btStatus.setText("Status: Connecting"); // Set up adapter and enable bluetooth btAdapter = BluetoothAdapter.getDefaultAdapter(); // Error message if(btAdapter == null){ Context context = getApplicationContext(); CharSequence txt = "Device does not support bluetooth"; Toast toast = Toast.makeText(context, txt, Toast.LENGTH_LONG); toast.show(); return; } if(!btAdapter.isEnabled()) { Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, 0); } // Set up device and password btDevice = btAdapter.getRemoteDevice(macAddress); String pin = "1234"; btDevice.setPin(pin.getBytes()); btDevice.createBond(); // Attempt to connect try { btSocket = btDevice.createRfcommSocketToServiceRecord(myID); } catch (Exception e) {} while( !btSocket.isConnected() ){ try{ btSocket.connect(); } catch(Exception e){ Context context = getApplicationContext(); CharSequence txt = "Failed to connect, retrying"; Toast toast = Toast.makeText(context, txt, Toast.LENGTH_LONG); toast.show(); } } btStatus.setText("Status: Connected"); } }); // Set up text and tag receiving button getTag = (Button) findViewById(R.id.getSetup); tag = (TextView) findViewById(R.id.displayTag); // Scan for tag getTag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(btSocket == null || !btSocket.isConnected()){ return; } try{ // Prompt arduino for input os = btSocket.getOutputStream(); os.write(1); // Attempt to read input in separate thread if(thread == null) { thread = new ConnectedThread(btSocket); } else { thread.cancel(); thread = new ConnectedThread(btSocket); } } catch(Exception e){ Context context = getApplicationContext(); CharSequence txt = "Failed to send input"; Toast toast = Toast.makeText(context, txt, Toast.LENGTH_LONG); toast.show(); } } }); itemName = (EditText) findViewById(R.id.itemName); events = (Spinner) findViewById(R.id.chooseEvent); confItem = (Button) findViewById(R.id.confirmItem); daysOfWeek = (Spinner) findViewById(R.id.daySelect); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.DaysOfWeek, android.R.layout.simple_spinner_dropdown_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); daysOfWeek.setAdapter(adapter); daysOfWeek.setOnItemSelectedListener(this); setUpEventSpinner(); confItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(input.length() == 0){ return; } String name = itemName.getText().toString(); item = new Item(input, name); if(createEvent){ eventName = (EditText) findViewById(R.id.eventName); eventTime = (EditText) findViewById(R.id.eventTime); String n = eventName.getText().toString(); int t = Integer.parseInt(eventTime.getText().toString()); event = new Event(t, n); createEvent = false; schedule.addEvent(dayWeek, event); setUpEventSpinner(); } schedule.addItem(event, item); } }); } /** * Helper method to navigate to home */ public void openHome(){ Intent intent = new Intent(this, MainActivity.class); intent.putExtra("EXTRA_SCHEDULE", schedule); try { btSocket.close(); } catch (Exception e){} startActivity(intent); } /** * Helper method to navigate to schedule */ public void openSchedule(){ Intent intent = new Intent(this, ScheduleActivity.class); intent.putExtra("EXTRA_SCHEDULE", schedule); try { btSocket.close(); } catch (Exception e){} startActivity(intent); } public void setUpEventSpinner(){ ArrayList<CharSequence> displayEvents = new ArrayList<CharSequence>(); if(schedule.getEvents().size() > 0) { for (Event e : schedule.getEvents()) { if(e != null) displayEvents.add(e.getName()); System.out.println(displayEvents.get(0)); } } displayEvents.add("New"); ArrayAdapter<CharSequence> adapter2 = new ArrayAdapter<CharSequence>(SettingsActivity.this, android.R.layout.simple_spinner_dropdown_item, displayEvents); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); events.setAdapter(adapter2); events.setOnItemSelectedListener(this); } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if(parent.getId() == R.id.daySelect){ String text = parent.getItemAtPosition(pos).toString(); switch(text){ case "Sunday": dayWeek = 0; break; case "Monday": dayWeek = 1; break; case "Tuesday": dayWeek = 2; break; case "Wednesday": dayWeek = 3; break; case "Thursday": dayWeek = 4; break; case "Friday": dayWeek = 5; break; case "Saturday": dayWeek = 6; break; } } else if(parent.getId() == R.id.chooseEvent){ if(parent.getItemAtPosition(pos).toString().equals("New")){ createEvent = true; } else { for(Event e : schedule.getEvents()){ if( e.getName().equals(parent.getItemAtPosition(pos).toString()) ){ event = e; } } } } } public void onNothingSelected(AdapterView<?> parent) { return; } /** * Thread to read input */ private class ConnectedThread extends Thread { BluetoothSocket bts; InputStream is; public ConnectedThread(BluetoothSocket b) { // Set up input stream bts = b; InputStream tmp = null; try { tmp = bts.getInputStream(); } catch (Exception e) { Context context = getApplicationContext(); CharSequence txt = "Failed to connect istream"; Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT); toast.show(); } is = tmp; start(); } public void run() { String tmp = ""; Long tStart = System.currentTimeMillis(); Long tEnd = System.currentTimeMillis(); while ((tEnd - tStart) < 2000) { try { // Read character by character char a = (char) is.read(); while (a != '\n') { tmp = tmp + a; a = (char) is.read(); } // Stop reading on newline, generate string final String string = new String(tmp.getBytes(), "UTF-8"); // Store string to inputs input = string; tag.setText("Tag ID: " + input); tmp = ""; if(input.length() > 0){ break; } } catch (Exception e) { break; } } cancel(); } public void cancel(){ try{ is.close(); btSocket.close(); } catch(Exception e){} } } }
Markdown
UTF-8
5,990
2.703125
3
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
# PHP Transmission API [![Build Status](https://travis-ci.org/transmission-php/transmission-php.png)](https://travis-ci.org/transmission-php/transmission-php) This library provides an interface to the [Transmission](http://transmissionbt.com) bit-torrent downloader. It provides means to get and remove torrents from the downloader as well as adding new torrents to the download queue. ## Installation Installation with [Composer](https://getcomposer.org): ``` composer require transmission-php/transmission-php ``` ## Usage Using the library is as easy as installing it: ```php <?php use Transmission\Transmission; $transmission = new Transmission(); // Getting all the torrents currently in the download queue $torrents = $transmission->all(); // Getting a specific torrent from the download queue $torrent = $transmission->get(1); // (you can also get a torrent by the hash of the torrent) $torrent = $transmission->get(/* torrent hash */); // Adding a torrent to the download queue $torrent = $transmission->add(/* path to torrent */); // Removing a torrent from the download queue $torrent = $transmission->get(1); $transmission->remove($torrent); // Or if you want to delete all local data too $transmission->remove($torrent, true); // You can also get the Trackers that the torrent currently uses // These are instances of the Transmission\Model\Tracker class $trackers = $torrent->getTrackers(); // You can also get the Trackers statistics and info that the torrent currently has // These are instances of the Transmission\Model\trackerStats class $trackerStats = $torrent->getTrackerStats(); // To get the start date/time of the torrent in UNIX Timestamp format $startTime = $torrent -> getStartDate(); // To get the number of peers connected $connectedPeers = $torrent -> getPeersConnected(); // Getting the files downloaded by the torrent are available too // These are instances of Transmission\Model\File $files = $torrent->getFiles(); // You can start, stop, verify the torrent and ask the tracker for // more peers to connect to $transmission->stop($torrent); $transmission->start($torrent); $transmission->start($torrent, true); // Pass true if you want to start the torrent immediatly $transmission->verify($torrent); $transmission->reannounce($torrent); ``` To find out which information is contained by the torrent, check [`Transmission\Model\Torrent`](https://github.com/transmission-php/transmission-php/tree/master/lib/Transmission/Model/Torrent.php). By default, the library will try to connect to `localhost:9091`. If you want to connect to another host or post you can pass those to the constructor of the `Transmission` class: ```php <?php use Transmission\Transmission; $transmission = new Transmission('example.com', 33); $torrents = $transmission->all(); $torrent = $transmission->get(1); $torrent = $transmission->add(/* path to torrent */); // When you already have a torrent, you don't have to pass the client again $torrent->delete(); ``` It is also possible to pass the torrent data directly instead of using a file but the metadata must be base64-encoded: ```php <?php $torrent = $transmission->add(/* base64-encoded metainfo */, true); ``` If the Transmission server is secured with a username and password you can authenticate using the `Client` class: ```php <?php use Transmission\Client; use Transmission\Transmission; $client = new Client(); $client->authenticate('username', 'password'); $transmission = new Transmission(); $transmission->setClient($client); ``` Additionally, you can control the actual Transmission setting. This means you can modify the global download limit or change the download directory: ```php <?php use Transmission\Transmission; $transmission = new Transmission(); $session = $transmission->getSession(); $session->setDownloadDir('/home/foo/downloads/complete'); $session->setIncompleteDir('/home/foo/downloads/incomplete'); $session->setIncompleteDirEnabled(true); $session->save(); ``` ## Testing Testing is done using [PHPUnit](https://github.com/sebastianbergmann/phpunit). To test the application, you have to install the dependencies using Composer before running the tests: ```bash $ composer phpunit ``` ## Original author This projet is a fork from https://github.com/kleiram/transmission-php/ ## License This library is licensed under the BSD 2-clause license. Copyright (c) 2014, Ramon Kleiss <ramonkleiss@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project.
Java
UTF-8
1,164
2.3125
2
[]
no_license
package com.redsun.social.dao.mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import com.redsun.social.entities.FileSharing; @Component public class FileSharingMapper implements RowMapper<FileSharing> { @Autowired private FileSharing fileSharing; public FileSharing mapRow(ResultSet rs, int rowNum) throws SQLException { fileSharing = new FileSharing(); fileSharing.setId(rs.getInt("id")); fileSharing.setClientId(rs.getInt("client_id")); fileSharing.setName(rs.getString("name")); fileSharing.setCreatedBy(rs.getString("created_by")); fileSharing.setCreatedDate(rs.getString("created_date")); fileSharing.setDescription(rs.getString("description")); fileSharing.setFilePath(rs.getString("file_path")); fileSharing.setProjectId(rs.getInt("project_id")); fileSharing.setGroupId(rs.getInt("group_id")); fileSharing.setScopes(rs.getInt("scopes")); fileSharing.setTitle(rs.getString("title")); return fileSharing; } }
C#
UTF-8
489
2.9375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Eticaret.Entities.Concrete { public class Cart { public Cart() { CartLines = new List<CartLine>(); //hiçbir ürün yokken null hatası almamak için. } public List<CartLine>CartLines { get; set; } public decimal Total { get { return CartLines.Sum(c => c.Product.UnitPrice * c.Quantity); } } } }
Python
UTF-8
501
2.65625
3
[ "MIT" ]
permissive
import requests import json base_url = "https://jobs.github.com/positions.json" #Extracting results from multiple pages results = [] for index in range(10): response = requests.get(base_url, params= {"description":"python", "location":"new york","page": index+1}) print(response.url) # print(response.json()) if len(response.json()) == 0: break results.extend(response.json()) print(len(results)) data = response.json() data = json.dumps(data, indent=4)
Markdown
UTF-8
2,096
3.359375
3
[]
no_license
--- title: "Engineering careers at graze" author: andy-worsley image: src: /content/images/2017/11/Engineering_Role_Rainbow.png alt: Engineering Role Rainbow tags: [ careers ] --- Graze is a great place to develop as a professional. We're big on giving people responsibility and seeing how far they can go with it. Coupled with support through one-to-one meetings with your manager or mentor, this generally works pretty well. But as we grew, people started to tell us that sometimes it was difficult to see where or how they could progress next. And not every manager was totally clear either! So we thought it'd be a good idea to write down the things we value and try to show what we think progression looks like. To do this many organisations use a career ladder or matrix, detailing the behaviours and skills you need to do to reach the next level. Having spent some time in the corporate world, I was initially wary of this approach: I've seen how generic and vague those documents can be. But they can be done well, as demonstrated by a popular example in the tech community - [Rent the Runway's Software Development Ladder](http://dresscode.renttherunway.com/blog/ladder "Rent The Runway's Software Development Ladder"). We took heavy inspiration from this, and came up with a version specific to graze. ![Engineering Role Rainbow](/content/images/2017/11/Engineering_Role_Rainbow.png) *See larger [PDF here](/content/images/2017/11/Engineering_Role_Rainbow.pdf "PDF here")* Things we like about it are: it's a set of guidelines about the kinds of contributions people can make, not a prescriptive list; it's a 'living' document on Google Drive that people are free to contribute to, and we can update as the company changes; the sections and behaviours can be used to easily create personal development plans; and it (hopefully) shows that you can be just as successful as an individual contributor than a manager. Finally, to jazz it up a little we gave it some colour and called it the "Role Rainbow". After all, it shows a wide spectrum of areas that people contribute in!
Ruby
UTF-8
732
3.21875
3
[]
no_license
class CookbookView def display(recipes, marmiton = false) if marmiton puts "Looking on Marmiton..." else puts "Cookbook recipes:" end recipes.each_with_index do |recipe, index| mark = recipe.tested ? "[X]" : "[ ]" puts "#{mark unless marmiton} #{index + 1} - #{recipe.name} - #{recipe.cooking_time}min - #{recipe.difficulty}" end end def ask_user_for_index(action) puts "Which one do you want to #{action} ?" print "> " return gets.chomp.to_i - 1 end def ask_user_for(element) puts "#{element} for the new recipe ?" print "> " return gets.chomp end def search puts "What do you want to search ?" print "> " return gets.chomp end end
Ruby
UTF-8
1,818
2.6875
3
[]
no_license
class Gemfile < ActiveRecord::Base has_many :gem_uses has_many :gem_instances, through: :gem_use has_many :votes belongs_to :user validate :validate_source validates :name, presence: true after_save :extract_gem_uses GEM_NAME = 0 GEM_VERSION = 1 def extract_gem_uses included_gems = extract_gem_names_and_versions GemUse.where(gemfile: self).destroy_all included_gems.each do |included_gem| gem_instance = create_gem_instance(included_gem[GEM_NAME]) create_gem_use(gem_instance, included_gem[GEM_VERSION].nil? ? 'highest' : included_gem[GEM_VERSION]) end end def create_gem_use(gem_instance, version) gem_use = GemUse.new(gemfile: self, gem_instance: gem_instance, version: version) if !gem_use.save raise ActiveRecord::RecordInvalid.new(self) self.errors.add(:source, 'cannot be saved') end end def create_gem_instance(gem_name) gem_instance = GemInstance.find_by(name: gem_name) if gem_instance.nil? gem_instance = GemInstance.new(name: gem_name) if !gem_instance.save raise ActiveRecord::RecordInvalid.new(self) self.errors.add(:source, 'cannot be saved') end end return gem_instance end def extract_gem_names_and_versions self.source.gsub(/#.*$/,'').scan(gem_name_and_version_regex) end def gem_name_and_version_regex /gem\s*'(.*?)'(?:,\s*('.*'))?/ end def validate_source if !(self.source =~ gem_name_and_version_regex) self.errors.add(:source, "does not contain any gems.") end end def up_votes Vote.where(gemfile: self).where(vote: true).count end def down_votes Vote.where(gemfile: self).where(vote: false).count end def total_votes up_votes - down_votes end end
Java
UTF-8
904
1.929688
2
[]
no_license
package com.privilege.service.resource.template; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlType; import java.util.HashSet; import java.util.Set; /** */ @XmlType public class Parameters { private Set<Parameter> includes = new HashSet<Parameter>(); private Set<Parameter> excludes = new HashSet<Parameter>(); @XmlElementWrapper(name = "includes") @XmlElement(name = "include") public Set<Parameter> getIncludes() { return includes; } public void setIncludes(Set<Parameter> includes) { this.includes = includes; } @XmlElementWrapper(name = "excludes") @XmlElement(name = "exclude") public Set<Parameter> getExcludes() { return excludes; } public void setExcludes(Set<Parameter> excludes) { this.excludes = excludes; } }
Python
UTF-8
286
2.78125
3
[]
no_license
#Importamos los modulos necesarios from reportlab.pdfgen import canvas doc = canvas.Canvas("Hola Mundo.pdf") #Inseratmos la imagen en el documento doc.drawImage("https://udemy-images.udemy.com/course/750x422/433798_1de9_4.jpg", -50, 500) #Guardamos el documento doc.save()