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
|
---|---|---|---|---|---|---|---|
Swift
|
UTF-8
| 6,479 | 2.8125 | 3 |
[] |
no_license
|
//
// EOINInstanceVariableParser.swift
// CreateJsonSwiftObjects
//
// Created by Eoin Norris on 06/01/2015.
// Copyright (c) 2015 Eoin Norris. All rights reserved.
//
import Cocoa
public class myObject:NSObject {
override init(){
super.init()
}
init(jsonDictionary:NSDictionary) {
super.init()
}
}
public class JSONParser{
func convertNSArrayToArrayOfType<T>(inArray:NSArray)->[T]{
var array = [T]()
for potentialStr in inArray{
if let str = potentialStr as? T{
array.append(str)
}
}
return array
}
func convertNSArrayOfDictionariesToArraysOfObjects(inArray:NSArray)->[myObject]{
var objectArray:[myObject] = []
for probableDict in inArray{
if let dict: NSDictionary = probableDict as? NSDictionary{
var thisFriend = myObject(jsonDictionary: dict)
objectArray.append(thisFriend)
}
}
return objectArray
}
}
class EOINInstanceVariableParser: EoinJSONSuper {
let initCreator:EOINInitMethodCreator = EOINInitMethodCreator()
func isString(value:AnyObject, keyStr:String)->(name:String?,isString:Bool){
var result:String? = nil
var resultBool:Bool = false
let possibleValueStr:NSString? = value as? NSString
if let valueStr = possibleValueStr{
result = "\tvar " + keyStr + ": String?\n"
resultBool = true
}
return (result,resultBool)
}
func nsNumber2Type(number:NSNumber)->String{
var result:String = ""
let charStr:UnsafePointer<Int8> = number.objCType
let typeStrPossible = String(UTF8String: charStr);
if let typeStr = typeStrPossible{
switch (typeStr){
case "i":
result = "Int?"
case "f":
result = "Float?"
case "c":
result = "Bool?"
case "d":
result = "Double?"
default:
result = "Int?"
}
}
return result
}
func isNumber(value:AnyObject, keyStr:String)->(name:String?,isNumber:Bool){
var result:String? = nil
var resultBool:Bool = false
let possibleValueInt:NSNumber? = value as? NSNumber
if let valueInt = possibleValueInt{
let realType = nsNumber2Type(valueInt)
result = "\tvar " + keyStr + ": \(realType)\n"
resultBool = true
}
return (result,resultBool)
}
func isArray(value:AnyObject, keyStr:String)->(name:String?,isArray:Bool,elementType:EOINParamaterType){
var result:String? = nil
var resultBool:Bool = false
var (varStr,type) = ("",EOINParamaterType())
let possibleValueArray:NSArray? = value as? NSArray
if let valueArray = possibleValueArray{
var count = valueArray.count
var arrayType = ""
if count>0 {
var item:AnyObject = valueArray[0]
(varStr,type) = getInstanceVariableType(item, keyStr: keyStr)
arrayType = varStr
arrayType = cleanUpTypeForParamaterization(arrayType)
}
if (arrayType.isEmpty==false){
result = "\tvar " + keyStr + ": Array<" + arrayType + ">?\n"
} else {
result = "\tvar " + keyStr + ": Array?\n"
}
resultBool = true
}
return (result,resultBool,type)
}
let prefix = "MyClass"
func getObjectName(value:AnyObject, keyStr:String)->(name:String?,isDict:Bool){
var result:String? = nil
var resultBool:Bool = false
var name = keyStr
//todo move into utility
name = name.firstCharacterUpperCase()
if name.hasSuffix("s"){
name = name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"
}
var typeStr = "\(prefix)\(name)"
// JSON Objects are dicts
let possibleValueDictionary:NSDictionary? = value as? NSDictionary
if let valueDict = possibleValueDictionary{
resultBool = true
result = "\tvar " + name + ": \(typeStr)\n"
}
return (result,resultBool)
}
typealias instanceResultType = (name:String, type:EOINParamaterType)
func getInstanceVariableType(value:AnyObject, keyStr:String)->(instanceResultType) {
var paramType = EOINParamaterType()
var elementType = EOINParamaterType()
var (valueStr, isValidStr) = isString(value, keyStr: keyStr)
if isValidStr{
paramType.paramaterName = keyStr;
paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!)
paramType.paramType = ParamamterType.Simple
return (valueStr!,paramType)
}
(valueStr, isValidStr) = isNumber(value, keyStr: keyStr)
if isValidStr{
paramType.paramaterName = keyStr;
paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!);
paramType.paramType = ParamamterType.Simple
return (valueStr!,paramType)
}
(valueStr, isValidStr,elementType) = isArray(value, keyStr: keyStr)
if isValidStr{
paramType.paramaterName = keyStr;
paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!);
switch(elementType.paramType){
case .Simple:
paramType.paramType = ParamamterType.ArrayOfInBuilts
case .Object:
paramType.paramType = ParamamterType.ArrayOfCustomItems
default:
paramType.paramType = ParamamterType.ArrayOfInBuilts
}
return (valueStr!,paramType)
}
(valueStr, isValidStr) = getObjectName(value, keyStr: keyStr)
if isValidStr{
paramType.paramaterName = keyStr;
paramType.paramaterTypeStr = cleanUpTypeForParamaterization(valueStr!);
paramType.paramType = ParamamterType.Object
return (valueStr!,paramType)
}
return ("\n",paramType)
}
}
|
C++
|
UTF-8
| 12,315 | 3.296875 | 3 |
[
"MIT"
] |
permissive
|
/*
Next player is o.
states are represented by long long.
0:empty, 1:o, 2:x
ox-
o-o
--x
is
011000_010001_000010
you can change size by boardSize.
Run
c++ -std=c++17 -O3 reachable_state.cpp
./a.out
*/
#include <iostream>
#include <unordered_map>
#include <vector>
#include <time.h>
#include <bitset>
// 0: empty, 1: o, 2: x
// i=0; bottom
// j=0; right
using namespace std;
typedef long long ll;
typedef unordered_map<ll, int> stateMap; // element is 1. no meaning
const int boardSize = 4;
vector< vector<ll> > cellNumbers; // it is used to get a cell number.
vector<ll> rowNumbers; // it is used to get a row numbers.
// use to check win
vector<ll> xWinMasks; // check row, column and diagonal line
vector<ll> oWinMasks;
vector<ll> eWinMasks;
// TODO: remove this. it should be save to storage. if 5 by 5 not enough memory.
vector<stateMap> allStateSet;
bool contains(stateMap *base, ll state){
return base->find(state) != base->end();
}
int moveLeft(int rowState, int i){
// move the piece(index) to left
// rowState is one row state
// index 0 is right
int newRow = 0;
// add cell from right
for(int j=0;j<boardSize-1;j++){
if (j<i){
newRow += int(cellNumbers[0][j]) & rowState; // same as base row state
}else{
newRow += (int(cellNumbers[0][j+1]) & rowState) >> 2; // 1 bit shift to right
}
}
newRow += 2 << (boardSize-1)*2; // the left is x (2). turn is always x(because the turn already changed)
return newRow;
}
int moveRight(int rowState, int i){
// move the piece(index) to right
// rowState is one row state
// index 0 is right
int newRow = 0;
// add cell from left
for(int j=boardSize-1;j>0;j--){
if (j>i){
newRow += int(cellNumbers[0][j]) & rowState; // same as base row state
}else{
newRow += (int(cellNumbers[0][j-1]) & rowState) << 2; // 1 bit shift to left
}
}
newRow += 2; // the right is x.
return newRow;
}
ll getCellNumber(int row, int column, ll state){
return cellNumbers[row][column] & state;
}
int getShiftedCellNumber(int row, int column, ll state){
ll cellNumber = getCellNumber(row, column, state);
return int(cellNumber >> (row*boardSize + column)*2);
}
ll swapPlayer(ll state){
ll newState = 0ll;
int n;
for(int i=boardSize-1;i>=0;i--){
for(int j=boardSize-1;j>=0;j--){
newState = newState << 2;
n = getShiftedCellNumber(i, j, state);
// swap 1 and 2 (o and x)
if (n == 1){
newState += 2ll;
}else if (n == 2){
newState += 1ll;
}
}
}
return newState;
}
ll reverseState(ll state){
// return reverse (mirror) state
ll newState = 0ll;
for(int i=boardSize-1;i>=0;i--){
for(int j=boardSize-1;j>=0;j--){
newState = newState << 2;
newState += ll(getShiftedCellNumber(i, boardSize - j - 1, state));
}
}
return newState;
}
ll rotatedState(ll state){
// {1, 2, 3,
// 4, 5, 6
// 7, 8, 9}
// to
// {3, 6, 9,
// 2, 5, 8
// 1, 4, 7}
ll newState = 0;
for(int i=boardSize-1;i>=0;i--){
for(int j=boardSize-1;j>=0;j--){
newState = newState << 2;
newState += ll(getShiftedCellNumber(j, boardSize - i - 1, state));
}
}
return newState;
}
ll symmetricState(ll state){
// return the minimum state of all symmetric states
ll rState = reverseState(state);
ll minState = min(state, rState);
vector<ll> searchingStates = {state, rState};
for(ll s: searchingStates){
for(int i=0;i<3;i++){
s = rotatedState(s);
minState = min(minState, s);
}
}
return minState;
}
void printState(ll state){
cout << "print state" << endl;
cout << bitset<boardSize*boardSize*2>(state) << endl;
int n;
for(int i=0;i<boardSize;i++){
for(int j=0;j<boardSize;j++){
n = getShiftedCellNumber(i, j, state);
if(n==0){
cout << "-";
}else if (n==1){
cout << "o";
}else if (n==2){
cout << "x";
}else if (n==3){
cout << "e";
}
}
cout << endl;
}
cout << endl;
}
void init(){
// initialize cellNumbers
vector< vector<ll> > cells(boardSize, vector<ll>(boardSize));
for(int i=0;i<boardSize;i++){
for(int j=0;j<boardSize;j++){
cells[i][j] = 3ll << (i * boardSize + j)*2;
}
}
cellNumbers = cells;
// initialize rowNumbers
vector<ll> rows(boardSize);
// create base number: 1111111111 (binary number)
ll baseNumber = 3ll;
for(int i=0;i<boardSize-1;i++){
baseNumber = (baseNumber<<2) + 3ll;
}
for(int i=0;i<boardSize;i++){
rows[i] = baseNumber << i*boardSize*2;
}
rowNumbers = rows;
// make masks to check win
ll oWin = 0ll;
ll xWin = 0ll;
ll eWin = 0ll;
// diagonal
for(int i=0;i<boardSize;i++){
oWin += 1ll << (i*boardSize+i)*2;
xWin += 2ll << (i*boardSize+i)*2;
eWin += 3ll << (i*boardSize+i)*2;
}
oWinMasks.push_back(oWin);
xWinMasks.push_back(xWin);
eWinMasks.push_back(eWin);
oWinMasks.push_back(reverseState(oWin));
xWinMasks.push_back(reverseState(xWin));
eWinMasks.push_back(reverseState(eWin));
// row
oWin = 1ll;
xWin = 2ll;
eWin = 3ll;
for(int i=0;i<boardSize-1;i++){
oWin = oWin << 2;
xWin = xWin << 2;
eWin = eWin << 2;
oWin += 1ll;
xWin += 2ll;
eWin += 3ll;
}
for(int i=0;i<boardSize;i++){
oWinMasks.push_back(oWin<<(2*i*boardSize));
xWinMasks.push_back(xWin<<(2*i*boardSize));
eWinMasks.push_back(eWin<<(2*i*boardSize));
}
// column
oWin = 1ll;
xWin = 2ll;
eWin = 3ll;
for(int i=0;i<boardSize-1;i++){
oWin = oWin << 2*boardSize;
xWin = xWin << 2*boardSize;
eWin = eWin << 2*boardSize;
oWin += 1ll;
xWin += 2ll;
eWin += 3ll;
}
for(int i=0;i<boardSize;i++){
oWinMasks.push_back(oWin<<(i*2));
xWinMasks.push_back(xWin<<(i*2));
eWinMasks.push_back(eWin<<(i*2));
}
}
int isWin(ll state){
// return 0:not decided, 1:win, -1:lose
// turn is o;
// if there is line of x, lose
// else if there is line of o, win
for(int i=0;i<eWinMasks.size();i++){
if ((state & eWinMasks.at(i)) == xWinMasks.at(i)){
return -1;
}
}
for(int i=0;i<eWinMasks.size();i++){
if ((state & eWinMasks.at(i)) == oWinMasks.at(i)){
return 1;
}
}
return 0;
}
stateMap *createNextStates(ll presentState, bool chooseEmpty){
// if chooseEmpty, increase o number. choose e. turn is o.
// else, the number of o, x, e are same. choose o. turn is o.
// before creating states, swap turn
presentState = swapPlayer(presentState);
auto *nextStates = new stateMap;
// if this state is end of the game (there is line) no next states.
// TODO: save the information of win??
if (isWin(presentState)!=0){
return nextStates;
}
int movingRow, newRow;
ll newState;
// choose only switch row, then rotate and switch row again.
// search present state and rotated state.
vector<ll> searchingStates = {presentState, rotatedState(presentState)};
for(ll state : searchingStates){
for(int i=0;i<boardSize;i++){
for(int j=0;j<boardSize;j++){
if(0<i && i<boardSize-1 && 0<j && j<boardSize-1){
// not edge
continue;
}
if (chooseEmpty && getShiftedCellNumber(i, j, state)!=0){
// need to choose empty but the cell is not empty.
continue;
}
if (!chooseEmpty && getShiftedCellNumber(i, j, state)!=2){
// need to choose x but the cell is not x. turn is already changed.
continue;
}
// TODO: refactor. move right and move left are similar. make it simple.
if(j!=boardSize-1){
// move to left
movingRow = int((state & rowNumbers[i]) >> 2*i*boardSize);
newRow = moveLeft(movingRow, j);
newState = (state & ~rowNumbers[i]) | (ll(newRow) << 2*i*boardSize);
newState = symmetricState(newState); // select minimum state in symmetric states.
// add to nextStates
if (nextStates->find(newState) == nextStates->end()){
(*nextStates)[newState] = 1;
}
}
if(j!=0){
// move to right
movingRow = int((state & rowNumbers[i]) >> 2*i*boardSize);
newRow = moveRight(movingRow, j);
newState = (state & ~rowNumbers[i]) | (ll(newRow) << 2*i*boardSize);
newState = symmetricState(newState); // select minimum state in symmetric states.
// add to nextStates
if (nextStates->find(newState) == nextStates->end()){
(*nextStates)[newState] = 1;
}
}
}
}
}
return nextStates;
}
stateMap *createSaveStateSet(stateMap *initialStates){
// create state set from initial states and save them to storage
// return next initial state map pointer
stateMap *createdStates = initialStates;
auto *nextInitialStates = new stateMap; // next state has 2 types. #o and #x
auto *presentStates = new stateMap;
while (createdStates != nullptr && !createdStates->empty()){
// create new states which is reachable from createdState
// save present state
auto *newStates = new stateMap;
for(auto stateItr = createdStates->begin(); stateItr != createdStates->end(); ++stateItr){
// save
(*presentStates)[stateItr->first] = 1;
// create reachable states
// choose empty. add to nextInitialStates
auto nextStates = createNextStates(stateItr->first, true);
for(auto itr=nextStates->begin();itr!=nextStates->end();itr++){
if(nextInitialStates->find(itr->first) == nextInitialStates->end()){
(*nextInitialStates)[itr->first] = 1;
}
}
// choose circle. add to newStates
nextStates = createNextStates(stateItr->first, false);
for(auto itr=nextStates->begin();itr!=nextStates->end();itr++){
if(!contains(newStates, itr->first) && !contains(presentStates, itr->first) && !contains(createdStates, itr->first)){
(*newStates)[itr->first] = 1;
}
}
}
delete createdStates;
createdStates = newStates;
}
// TODO: save present states to strage
allStateSet.push_back(*presentStates);
delete presentStates;
return nextInitialStates;
}
stateMap *createInitialStates(){
int initialState = 0;
auto *initialStates = new stateMap;
(*initialStates)[initialState] = initialState;
return initialStates;
}
int createTree(){
// return 0 if success
// save results to storage.
stateMap *initialStates = createInitialStates();
int counter = 0;
while (initialStates != nullptr && !initialStates->empty()){
// repeat until initialStates is null
initialStates = createSaveStateSet(initialStates);
// TODO: it should be divided into 2 types (the numebr of o and x)
cout << ++counter << endl;
}
return 0;
}
int main(){
clock_t start = clock();
init();
createTree();
clock_t end = clock();
cout << "end : " << (double)(end - start)/ CLOCKS_PER_SEC << " sec" << endl;
// count the number of states
int sum = 0;
for(auto sm: allStateSet){
cout << sm.size() << endl;
sum += sm.size();
}
cout << sum << endl;
}
|
Java
|
UTF-8
| 1,072 | 2.40625 | 2 |
[] |
no_license
|
package com.owen.codeframework.http;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
/**
* REST็ฝ็ปๆฅๅฃ่ฏทๆฑ็ฑป
*
* Created by Owen on 2015/11/3.
*/
public class RESTClient {
private static AsyncHttpClient sClient = new AsyncHttpClient();
static {
sClient.addHeader("Accept", "application/json");
sClient.setTimeout(20*1000);
}
/**
* HTTP-GET
*/
private static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
sClient.get(url, params, responseHandler);
}
/**
* HTTP-POST
*/
private static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
sClient.post(url, params, responseHandler);
}
/**
* HTTP-DELETE
*/
private static void delete(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
sClient.delete(url, params, responseHandler);
}
}
|
C++
|
UTF-8
| 1,084 | 2.75 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
#define INPUT_SIZE 101
struct nodo{ vector<char> out; vector<char> in; bool visited = false; bool inqueue = false; };
unordered_map<char, nodo> adj;
bool checkNode(char c){
if(adj[c].visited)
return false;
for(auto x : adj[c].in)
if(!adj[x].visited)
return false;
return true;
}
int main(){
freopen("C:\\Users\\Laurens\\Documents\\School\\Jaar 2\\Kwartiel 2\\Datastructures\\AoC2018\\Day7\\input7.txt", "r", stdin);
for(int i = 0; i < INPUT_SIZE; i++){
char da, a;
scanf("Step %c must be finished before step %c can begin.\n", &da, &a);
adj[da].out.push_back(a);
adj[a].in.push_back(da);
}
string ans = "";
while(ans.size() != adj.size()){
char next = ('Z'+1);
for(auto x : adj){
if(checkNode(x.first))
next = min(next, x.first);
}
ans += next;
adj[next].visited = true;
}
cout << ans << endl;
return 0;
}
|
C#
|
UTF-8
| 981 | 3.578125 | 4 |
[] |
no_license
|
๏ปฟusing System;
namespace ch5_1
{
class Program
{
static void Main(string[] args)
{
int num = int.Parse(Console.ReadLine());
int max = -1000000, min= 1000000;
int[] array = new int[num];
string str = Console.ReadLine();
string[] str_unit = str.Split(' ');
int[] unit = new int[num];
for(int i = 0; i< num; i++)
{
unit[i] = int.Parse(str_unit[i]);
}
for(int i = 0; i < num; i++)
{
array[i] = unit[i];
}
for (int i = 0; i < num; i++)
{
if (min > array[i])
{
min = array[i];
}
if (max < array[i])
{
max = array[i];
}
}
Console.WriteLine(min + " " + max);
}
}
}
|
C
|
UTF-8
| 6,834 | 3.203125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
//djikstra implementation inspired by https://www.geeksforgeeks.org/c-program-for-dijkstras-shortest-path-algorithm-greedy-algo-7/
// and https://www.geeksforgeeks.org/printing-paths-dijkstras-shortest-path-algorithm/?ref=lbp
struct stop {
char location[300];
};
#define GRAPHSIZE 7667
#define stoplim 7668
struct stop stops[stoplim];
int next_field ( FILE *csv , int which);
int matrix[GRAPHSIZE][GRAPHSIZE];
void init(int array[][GRAPHSIZE])
{
int i,j;
for(i = 0; i < GRAPHSIZE; i++)
for(j = 0; j < GRAPHSIZE; j++)
array[i][j] = 0;
}
void addEdge(int source, int dest ,int weight)
{
matrix[source][dest] = weight; // fills array with two way edge given values
matrix[dest][source] = weight;
}
int printSolution(int dist[], int n,int source, int destination)
{
printf("%d -> %d\n", source, destination);
printf("Total\n%s -> %s = %d\n", stops[source].location , stops[destination].location, dist[destination]);
}
int minDistance(int dist[], bool permanent[])
{
int min = INT_MAX;
int min_index;
for (int i = 0; i < GRAPHSIZE; i++)
if (permanent[i] == false && dist[i] <= min) {
min = dist[i];
min_index = i;
}
return min_index;
}
void printroute(int used[],int destination){
int i = used[destination];
int j = destination;
if(i == -1){
return;
}
printroute(used, i);
printf("\n%s -> %s = %d", stops[i].location, stops[j].location, matrix[j][i]);
//printf("%d ", destination);
}
//https://www.geeksforgeeks.org/c-program-for-dijkstras-shortest-path-algorithm-greedy-algo-7/
void dijkstra(int matrix[GRAPHSIZE][GRAPHSIZE], int source, int destination)
{
int used[GRAPHSIZE];
int dist[GRAPHSIZE]; // The output array.
bool permanent[GRAPHSIZE]; // permanent[i] will be true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
for (int i = 0; i < GRAPHSIZE; i++) {// Initialize all distances as INFINITE and permanent[] as false
dist[i] = INT_MAX;
permanent[i] = false;
used[source] = -1;
}
dist[source] = 0; // Distance of source vertex from itself is always 0
used[source] = -1;
// Find shortest path for all vertices
for (int count = 0; count < GRAPHSIZE - 1; count++) {
int u = minDistance(dist, permanent); //start with min
permanent[u] = true; // Mark the picked vertex as processed
for (int v = 0; v < GRAPHSIZE; v++) // Update dist value of the adjacent vertices of the picked vertex.
// Update dist[v] only if is not in permanent, there is an edge from
// u to v,
if ((!permanent[v] && matrix[u][v]) && (dist[u] != INT_MAX)
&& (dist[u] + matrix[u][v] < dist[v])){ // total weight of path from src to v through u must be smaller than current value of dist[v]
dist[v] = dist[u] + matrix[u][v];
used[v] = u;
}
}
// print the constructed distance array
printroute(used, destination);
printSolution(dist, GRAPHSIZE,source, destination);
}
int main(){
init(matrix);
FILE *csv;
csv = (FILE *)malloc(sizeof(FILE));
int n = 0;
char duplicate[100] = {};
csv = fopen("vertices.csv", "r");
while(n != 2){
n = next_field(csv,0);
if (n == 1){
// printf("\n\n");
}
if (n == 3){
// printf("\n");
}
if (n == 2);
//printf("\n\n\n");
}
fclose(csv);
FILE *csv2;
csv2 = (FILE *)malloc(sizeof(FILE));
n = 0;
csv2 = fopen("edges.csv", "r");
while(n != 2){
n = next_field(csv2,1);
if (n == 1){
//printf("\n\n");
}
if (n == 3){
//printf("\n");
}
}
fclose(csv2);
dijkstra(matrix,300, 253);
char input1[10];
char input2[10];
printf("\n enter two stop nos\n");
gets( input1);
gets( input2);
int in1 = atoi(input1);
int in2 = atoi(input2);
dijkstra(matrix, in1,in2);
printf("\n code over");
return 0;
}
void stores(int no, char buffer[], int data){ //stores in struct from csv
if (no != 0){ // ignores headings
switch (data)
{
case (1):
for (int i = 0; i < 300; i++){
stops[no].location[i] = buffer[i];
}
break;
default :
break;
}
}
}
void storesedge(int no, char buffer[], int data){
static int from;
static int to;
int weight;
//printf("\ndata = %d , no = %d", data, no);
if (no != 0){ // ignores headings
//printf("I'm in to stroreedge");
switch (data)
{
case (0):
from = atoi(buffer);
break;
case (1):
to = atoi(buffer);
break;
case (2):
weight = atoi(buffer);
addEdge(from, to, weight);
}
}
}
int next_field ( FILE *csv , int which){ // reads from csv into buffer
char buffer[300] = {0} ;
bool quote = false;
char c;
static int no = 0; //4 data points 0-3
static int data = 0;
int n = 0;
while(true){
c = fgetc(csv);
if (c == '"') quote = !quote;
else if (c == EOF){
//printf("%s", buffer);
if (which == 0){
stores( no, buffer, data);
data = 0;
no = 0;
}
else {
storesedge(no,buffer,data);
printf("\nand for that reason,I'm out\n");
}
return 2;
}
else if ((c == ',') && (quote == false)){
//printf("%s", buffer);
if (which == 0){
stores( no, buffer, data);
}
else {
storesedge(no,buffer,data);
}
data++;
return 3;
}
else if (c == '\n'){
//printf("%s", buffer);
if (which == 0){
stores(no, buffer, data);
}
else {
storesedge(no,buffer,data);
}
no++;
data = 0;
return 1;
}
else {
buffer[n] = c;
n++;
}
}
}
|
C++
|
UTF-8
| 2,093 | 2.84375 | 3 |
[] |
no_license
|
#include <SDL2/SDL.h>
# define FPS 60
# define WIDTH 1300
# define HEIGHT 1000
# define MUL 80
double f(const double &x)
{
return (sqrt(x));
}
double draw_zero_pow()
{
return (1. / 2);
}
double draw_first_pow(const double &x)
{
return (x + 1. / 8);
}
void draw_lines(SDL_Renderer *renderer)
{
for (int y = 0; y < HEIGHT; y += 1)
{
SDL_RenderDrawPoint(renderer, WIDTH / 2, y);
}
for (int x = 0; x < WIDTH; ++x)
{
SDL_RenderDrawPoint(renderer, x, HEIGHT / 2);
}
}
void draw_plots(SDL_Renderer *renderer)
{
SDL_SetRenderDrawColor(renderer, 169, 169, 169, 0);
draw_lines(renderer);
for (double x = 0; x <= 10; x += 0.0001)
{
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 0);
SDL_RenderDrawPoint(renderer, WIDTH / 2 + x * MUL, HEIGHT / 2 - f(x) * MUL + 1);
SDL_SetRenderDrawColor(renderer, 255, 255, 51, 0);
SDL_RenderDrawPoint(renderer, WIDTH / 2 + x * MUL, HEIGHT / 2 - draw_zero_pow() * MUL + 1);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 0);
SDL_RenderDrawPoint(renderer, WIDTH / 2 + x * MUL, HEIGHT / 2 - draw_first_pow(x) * MUL + 1);
}
}
int main()
{
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event event;
Uint32 start;
const int a = 0;
const int b = 1;
SDL_CreateWindowAndRenderer(1300, 1000, 0, &window, &renderer);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
while (true)
{
SDL_RenderClear(renderer);
if (SDL_PollEvent(&event) && (event.type == SDL_QUIT || event.key.keysym.sym == SDLK_ESCAPE))
break;
start = SDL_GetTicks();
draw_plots(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderPresent(renderer);
SDL_UpdateWindowSurface(window);
if (1000 / FPS > SDL_GetTicks() - start)
{
SDL_Delay(1000 / FPS - (SDL_GetTicks() - start));
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return (0);
}
|
Java
|
UTF-8
| 509 | 2.046875 | 2 |
[] |
no_license
|
package com.sample.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by jayati on 18/11/17.
*/
@RestController
public class SampleController {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
|
Python
|
UTF-8
| 379 | 3.25 | 3 |
[] |
no_license
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
fi = None
se = head
while se:
t = se.next
se.next = fi
fi = se
se = t
return fi
|
Java
|
UTF-8
| 4,892 | 1.804688 | 2 |
[] |
no_license
|
package com.ca.arcflash.ui.client.homepage.navigation;
import com.ca.arcflash.ui.client.UIContext;
import com.ca.arcflash.ui.client.coldstandby.ColdStandbyManager;
import com.ca.arcflash.ui.client.coldstandby.ColdStandbyTaskPanel;
import com.ca.arcflash.ui.client.common.AppType;
import com.ca.arcflash.ui.client.homepage.SocialNetworkingPanel;
import com.ca.arcflash.ui.client.homepage.SupportPanel;
import com.ca.arcflash.ui.client.homepage.TaskPanel;
import com.ca.arcflash.ui.client.vsphere.homepage.VSphereTaskPanel;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.widget.CollapsePanel;
import com.extjs.gxt.ui.client.widget.ComponentHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
public class NavigationCollapsePanel extends CollapsePanel
{
private LayoutContainer bodyContainer;
private BorderLayoutData parentData;
private AppType appType = AppType.D2D;
protected static ContentPanel contentPanel;
public NavigationCollapsePanel(ContentPanel panel, BorderLayoutData data)
{
super(panel, data);
parentData = data;
createBodyContainer();
}
public NavigationCollapsePanel(ContentPanel panel, BorderLayoutData data,AppType appType)
{
super(panel, data);
parentData = data;
this.appType = appType;
createBodyContainer();
}
protected void createBodyContainer()
{
// a layout container for the Navigation buttons
bodyContainer = new LayoutContainer();
TableLayout tl = new TableLayout(1);
tl.setWidth("100%");
tl.setCellHorizontalAlign(HorizontalAlignment.CENTER);
tl.setCellPadding(0);
bodyContainer.setLayout(tl);
TableData td = new TableData();
td.setHeight("50px");
// tasks
NavigationButtonItem naviButtonItem = new NavigationButtonItem(AbstractImagePrototype.create(UIContext.IconBundle.tasks_backup()), getTaskPanel(), parentData);
bodyContainer.add(naviButtonItem,td);
// support
if(UIContext.customizedModel == null || UIContext.customizedModel.getShowSupportHeader()){
naviButtonItem = new NavigationButtonItem(AbstractImagePrototype.create(UIContext.IconBundle.googleGroup()), new SupportPanel(appType), parentData);
bodyContainer.add(naviButtonItem,td);
}
if(UIContext.customizedModel == null || UIContext.customizedModel.getShowSocialNetworkHeader()) {
// social NW
if (UIContext.serverVersionInfo.isShowSocialNW() != null && UIContext.serverVersionInfo.isShowSocialNW())
{
naviButtonItem = new NavigationButtonItem(AbstractImagePrototype.create(UIContext.IconBundle.userCenter()), new SocialNetworkingPanel(appType), parentData);
bodyContainer.add(naviButtonItem,td);
}
}
//testMenuBar();
}
@Override
protected void onRender(Element target, int index)
{
super.onRender(target, index);
// the header is OK by the above super.onRender(), below is to prepare the body
bwrap = el().createChild("<div class=" + bwrapStyle + "></div>");
Element bw = bwrap.dom;
body = fly(bw).createChild("<div class=" + bodStyle + "></div>");
// remove the background-color and borders from body
body.setStyleAttribute("background-color", "transparent");
body.setBorders(false);
// render the layout container
bodyContainer.render(body.dom, 0);
bodyContainer.layout();
}
@Override
protected void doAttachChildren()
{
super.doAttachChildren();
ComponentHelper.doAttach(bodyContainer);
}
@Override
protected void doDetachChildren()
{
super.doDetachChildren();
ComponentHelper.doDetach(bodyContainer);
}
@Override
public void onComponentEvent(ComponentEvent ce)
{
// TODO Auto-generated method stub
//super.onComponentEvent(ce);
}
protected ContentPanel getTaskPanel(){
switch(appType){
case D2D:
contentPanel = new TaskPanel(true);
break;
case VSPHERE:
contentPanel = new VSphereTaskPanel();
break;
case VCM:
if(contentPanel == null || !(contentPanel instanceof ColdStandbyTaskPanel)) {
contentPanel = new ColdStandbyTaskPanel(true);
ColdStandbyTaskPanel taskPanel = ColdStandbyManager.getInstance().getTaskPanel();
if(taskPanel != null) {
((ColdStandbyTaskPanel)contentPanel).getContainerActivityLog()
.setEnabled(taskPanel.getContainerActivityLog().isEnabled());
((ColdStandbyTaskPanel)contentPanel).getContainerSetting()
.setEnabled(taskPanel.getContainerSetting().isEnabled());
}
}
break;
default:
contentPanel = new TaskPanel(true);
}
return contentPanel;
}
}
|
Java
|
UTF-8
| 3,324 | 2.59375 | 3 |
[] |
no_license
|
package com.robert.springmvcwebapp;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
/**
* Programmatic configuration of the instead of web.xml
*/
public class Bootstrap implements WebApplicationInitializer {
/**
* Listener Initialized first to load rootSpringContext. RootContext should contain business objects
* or data access objects. ServletContext are cannot access beans from other ServletContext. ServletContext should
* contains beans specific to the Servlet such as controllers
*
* @param container the servlet context for this webapplication
* @throws ServletException
*/
@Override
public void onStartup(ServletContext container) throws ServletException {
/**
* If you plan to map the DispatcherServlet to the application root, make sure you account for static resources
* such as HTML pages, CSS and JavaScript files, and images. Some online tutorials demonstrate how to set up
* Spring Framework to serve static resources, but doing so is not necessary and does not perform well. When
* any Servlet is mapped to the application root (without an asterisk), more-specific URL patterns always
* override it. So permitting your Servlet container to serve static resources is as simple as adding mappings
* for those resources to the Servlet named default (which all containers provide automatically). This can be
* accomplished in the deployment descriptor like so:
*/
container.getServletRegistration("default").addMapping( "/resources/*", "*.css", "*.js", "*.png", "*.gif", "*.jpg");
/**
* Register rootContext
* The root application context should hold services, repositories, and other pieces of business logic, whereas
* the DispatcherServletโs application context should contain web controllers
*/
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootContextConfiguration.class);
container.addListener(new ContextLoaderListener(rootContext));
//Register servletContext and Create Dispatcher servlet
AnnotationConfigWebApplicationContext servletContext = new AnnotationConfigWebApplicationContext();
servletContext.register(ServletContextConfiguration.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("springDispatcher", new DispatcherServlet(servletContext));
dispatcher.setLoadOnStartup(1);
/**
* The lone forward slash without an asterisk is sufficient to get the Servlet to respond to all URLs in your
* application and while still enabling the Servlet containerโs JSP mechanism to handle JSP requests A trailing
* asterisk causes the Servlet container to send even internal JSP requests to that Servlet, which is not desirable
*/
dispatcher.addMapping("/");
}
}
|
Java
|
UTF-8
| 1,041 | 3.453125 | 3 |
[] |
no_license
|
package clocks.base;
/**
*
* @author S.Lavruhin
*
*/
public class Point implements Comparable<Point>{
private final double precession = 0.0001;
public final double x;
public final double y;
/**
*
* @param x
* @param y
*/
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
*
* @param p
*/
public Point(final Point p) {
this(p.x, p.y);
}
/**
* Wrapper to initialize a Point with double values.
*
* @param x
* @param y
* @return
*/
public static java.awt.Point toUtilPoint(double x, double y) {
return new java.awt.Point((int)Math.round(x), (int)Math.round(y));
}
@Override
public String toString() {
return String.format("x=%.2f, y=%.2f", x, y );
}
@Override
public int compareTo(Point p) {
double deltaX = Math.abs(x - p.x),
deltaY = Math.abs(y - p.y);
return deltaX > precession ? (x > p.x ? 1 : -1) : deltaY > precession ? (y > p.y ? 1 : -1) : 0;
}
}
|
JavaScript
|
UTF-8
| 2,125 | 2.6875 | 3 |
[] |
no_license
|
// This file needed to be run on node 0.12 in order to make sure that library runs on 0.12
var crypto = require('crypto');
var Estimator = require('../index');
var FeeRate = require('../build/FeeRate');
// For test we will assume that 4 transactions can be added to mempool on each iterration block and 3 can be mined
function generateRandomMempoolData(len, height) {
var mempool = {};
for (var i = 0; i < len; i++) {
mempool[crypto.createHash('sha256').update((Date.now() + Math.random()).toString()).digest('hex')] = {
size: 23818,
fee: (Math.random() * (0.00047646 - 0.00023823)) + 0.00023823,
// fee: 0.00023823,
modifiedfee: 0.00023823,
time: 1510165507,
height: height,
startingpriority: 15191056856720.27,
currentpriority: 15191056856720.27,
descendantcount: 1,
descendantsize: 23818,
descendantfees: 23823,
depends: [
],
};
}
return mempool;
}
function transformMempoolData(rawmempooldata) {
var hashes = Object.keys(rawmempooldata);
var arr = [];
for (var i = 0; i < hashes.length; i++) {
rawmempooldata[hashes[i]].hash = hashes[i];
arr.push(rawmempooldata[hashes[i]]);
}
return arr;
}
function generateBlock(mempooldata, prevBlockHeight, transactionsToInclude) {
mempooldata.sort(function (a, b){return b.fee - a.fee});
var txToIncludeInBlock = mempooldata.splice(0, transactionsToInclude);
return {
height: prevBlockHeight + 1,
tx: txToIncludeInBlock.map(function (tx) {return tx.hash}),
};
}
var estimator = new Estimator();
var wholePool = [];
for (var i = 1; i < 11; i++) {
var newBlock = generateBlock(wholePool, i - 1, 10);
var newMempoolData = generateRandomMempoolData(11, i);
wholePool = wholePool.concat(transformMempoolData(newMempoolData));
estimator.processBlock(newBlock.height, newBlock.tx);
estimator.processNewMempoolTransactions(newMempoolData);
}
var fees = [];
for (var i = 1; i < 7; i++) {
fees.push(estimator.estimateSmartFee(i));
}
if (fees[0] instanceof FeeRate) {
console.log('0.12 test pass');
} else {
console.log('0.12 test not pass');
}
|
Java
|
UTF-8
| 1,068 | 2.8125 | 3 |
[] |
no_license
|
package com.artpro.service;
import com.artpro.model.CargoTransport;
//ะะปั ะณััะทะพะฒะพะณะพ ัะฐะทัะฐะฑะพัะฐัั ะผะตัะพะด ะบะพัะพััะน ะฟัะพะฒะตัะธั ะผะพะถะฝะพ ะปะธ ะทะฐะณััะทะธัั ะฒ
//ะฝะตะณะพ xxx ะณััะทะฐ
//ะะตัะพะด ะดะพะปะถะตะฝ ะฟัะพะฒะตัััั ะตัะปะธ ััะพ ะบะพะป-ะฒะพ ะณััะทะฐ ะฟะพะผะตัะฐะตััั ะฒ ะณััะทะพะฒะธะบ ัะพ
//ะฒัะฒะพะดะธั ะฒ ะบะพะฝัะพะปั โะััะทะพะฒะธะบ ะทะฐะณััะถะตะฝโ, ะตัะปะธ ะบะพะป-ะฒะพ ะณััะทะฐ ะบะพัะพัะพะต ะฝัะถะฝะพ
//ะทะฐะณััะทะธัั ะฑะพะปััะต ัะตะผ ัะพ ะบะพัะพัะพะต ะผะพะถะตั ะฒะปะตะทัั ะฒ ะฝะฐั ะณััะทะพะฒะธะบ ัะพ ะฒัะฒะพะดะธะผ
//โะะฐะผ ะฝัะถะตะฝ ะณััะทะพะฒะธะบ ะฟะพะฑะพะปััะต โ.
public class CargoTransportService {
public void calculationCargoTransportService(CargoTransport cargoTransport, double cargo) {
if (cargo <= cargoTransport.getLoadCapacity()) {
System.out.println("ะััะทะพะฒะธะบ ะทะฐะณััะถะตะฝ");
} else {
System.out.println("ะะฐะผ ะฝัะถะตะฝ ะณััะทะพะฒะธะบ ะฟะพะฑะพะปััะต");
}
}
}
|
Java
|
UTF-8
| 1,245 | 2.3125 | 2 |
[] |
no_license
|
package fr.insa.soa.ExchangeSemester.services;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.xml.bind.DatatypeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import fr.insa.soa.ExchangeSemester.dao.UserRepository;
import fr.insa.soa.ExchangeSemester.model.User;
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public boolean saveUser(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
if (userRepository.findByLogin(user.getLogin()) == null) {
// login not found in the db, can save
byte[] byteChaine = user.getPassword().getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(byteChaine);
String myHash = DatatypeConverter.printHexBinary(hash).toLowerCase();
user.setPassword(myHash);
userRepository.save(user);
return true;
}
else {
// login already used, cannot save
return false;
}
}
}
|
Java
|
UTF-8
| 870 | 2.34375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.david.calendaralarm.data.pojo;
import org.joda.time.DateTime;
public class Item {
private String title;
private String summary;
private DateTime currentDate;
private DateTime executionDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public DateTime getCurrentDate() {
return currentDate;
}
public void setCurrentDate(DateTime currentDate) {
this.currentDate = currentDate;
}
public DateTime getExecutionDate() {
return executionDate;
}
public void setExecutionDate(DateTime executionDate) {
this.executionDate = executionDate;
}
}
|
C++
|
UTF-8
| 488 | 2.9375 | 3 |
[] |
no_license
|
#include "Polymorph.hpp"
Polymorph::Polymorph() : ASpell("Polymorph", "turned into a critter") {};
Polymorph::~Polymorph() {};
Polymorph::Polymorph(Polymorph const & src) : ASpell("Polymorph", "turned into a critter") {
(void)src;
};
Polymorph & Polymorph::operator = (Polymorph const & src) {
if (this != &src) {
this->_name = src._name;
this->_effects = src._effects;
}
return (*this);
};
ASpell * Polymorph::clone() {
return (new Polymorph);
};
|
Java
|
UTF-8
| 203 | 2.890625 | 3 |
[] |
no_license
|
package Day18;
class Number implements Expression {
private final int value;
public Number(int value) {
this.value = value;
}
@Override
public long evaluate() {
return value;
}
}
|
C++
|
UTF-8
| 2,173 | 3.609375 | 4 |
[] |
no_license
|
#include<iostream>
#include<queue>
#include<map>
#include<list>
#define null 0
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(){}
Node(int data){
this->data=data;
left=right=null;
}
};
class Object{
public:
Node *node;
int distance;
Object(){}
Object(Node *node,int diatance){
this->node=node;
this->distance = diatance;
}
};
void verticalOrderTraversal(Node *root){
if(root==null){
return ;
}
else{
map<int,list<int> > m;
queue<Object> q;
Object o(root,0);
q.push(o);// or use q.push(Object(root,0));
while(!q.empty()){
Object o = q.front();
q.pop();
m[o.distance].push_back(o.node->data);
if(o.node->left!=null){
// Object l(o.node->left,o.distance-1);
q.push(Object(o.node->left,o.distance-1)); //or use q.push(l);
}
if(o.node->right!=null){
// Object r(o.node->right,o.distance+1);
q.push( Object(o.node->right,o.distance+1)); // or use q.push(r);
}
}
for(auto it:m){
cout <<"["<< it.first<<"]->"; // remove this line if you do not want keys on output.
for(auto element:it.second){
cout <<element<<" ";
}
cout<<"\n";
}
}
}
int main(){
Node * root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right= new Node(5);
root->right->left= new Node(6);
root->right->left->left= new Node(10);
root->right->right= new Node(7);
root->right->right->left = new Node(8);
root->right->right->right = new Node(9);
cout <<"\nThe vertical order of tree \n";
verticalOrderTraversal(root);
/*
The vertical order of tree
keys->values
[-2]->4
[-1]->2 10
[0]->1 5 6
[1]->3 8
[2]->7
[3]->9
*/
}
|
PHP
|
UTF-8
| 2,372 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Arkade\RetailDirections;
use Carbon\Carbon;
use Illuminate\Support\Fluent;
use Illuminate\Support\Collection;
class GiftVoucherFinaliseRequest extends Fluent
{
protected $giftVoucherReference;
protected $giftVoucherSchemaCode;
protected $pin;
protected $statusInd;
/**
* Customer constructor.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
/**
* @return mixed
*/
public function getGiftVoucherReference()
{
return $this->giftVoucherReference;
}
/**
* @param mixed $giftVoucherReference
*/
public function setGiftVoucherReference($giftVoucherReference)
{
$this->giftVoucherReference = $giftVoucherReference;
return $this;
}
/**
* @return mixed
*/
public function getGiftVoucherSchemaCode()
{
return $this->giftVoucherSchemaCode;
}
/**
* @param mixed $giftVoucherSchemaCode
*/
public function setGiftVoucherSchemaCode($giftVoucherSchemaCode)
{
$this->giftVoucherSchemaCode = $giftVoucherSchemaCode;
return $this;
}
/**
* @return mixed
*/
public function getPin()
{
return $this->pin;
}
/**
* @param mixed $pin
*/
public function setPin($pin)
{
$this->pin = $pin;
return $this;
}
/**
* @return mixed
*/
public function getStatusInd()
{
return $this->statusInd;
}
/**
* @param mixed $statusInd
*/
public function setStatusInd($statusInd)
{
$this->statusInd = $statusInd;
return $this;
}
public static function fromXml(
\SimpleXMLElement $xml
) {
$giftVoucherRequest = new static;
$giftVoucherRequest->setGiftVoucherReference((string) $xml->giftvoucher_reference);
$giftVoucherRequest->setGiftVoucherSchemaCode((string) $xml->giftvoucherscheme_code);
$giftVoucherRequest->setStatusInd((string) $xml->status_ind);
$giftVoucherRequest->setPin((string) $xml->pin);
foreach ($xml->children() as $key => $value) {
$giftVoucherRequest->{$key} = (string) $value;
}
return $giftVoucherRequest;
}
}
|
Java
|
UTF-8
| 19,399 | 1.890625 | 2 |
[] |
no_license
|
package com.yunda.jx.jxgc.workplanmanage.manager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import com.yunda.common.BusinessException;
import com.yunda.frame.common.Constants;
import com.yunda.frame.common.JXBaseManager;
import com.yunda.frame.common.Page;
import com.yunda.frame.common.SearchEntity;
import com.yunda.frame.util.CommonUtil;
import com.yunda.frame.util.StringUtil;
import com.yunda.frame.util.sqlmap.SqlMapUtil;
import com.yunda.jx.jxgc.producttaskmanage.entity.WorkCard;
import com.yunda.jx.jxgc.producttaskmanage.entity.Worker;
import com.yunda.jx.jxgc.producttaskmanage.manager.WorkerManager;
import com.yunda.jx.jxgc.producttaskmanage.qualitychek.entity.QCResult;
import com.yunda.jx.jxgc.producttaskmanage.qualitychek.manager.QCResultManager;
import com.yunda.jx.jxgc.workplanmanage.entity.JobProcessNode;
/**
* <li>ๆ ้ข: ๆบ่ฝฆๆฃไฟฎๆดๅค็ฎก็ไฟกๆฏ็ณป็ป
* <li>่ฏดๆ: ไฝไธๅทฅๅๆฅ่ฏขไธๅก็ฑป
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-4-29
* <li>ไฟฎๆนไบบ:
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* <li>็ๆ: Copyright (c) 2008 ่ฟ่พพ็งๆๅ
ฌๅธ
* @author ไฟกๆฏ็ณป็ปไบไธ้จๆฃไฟฎๆดๅค็ณป็ป้กน็ฎ็ป
* @version 1.0
*/
@Service(value = "workCardQueryManager")
public class WorkCardQueryManager extends JXBaseManager<WorkCard, WorkCard> {
@Resource
private WorkerManager workerManager;
@Resource
private QCResultManager qCResultManager;
/**
* <li>่ฏดๆ๏ผ่ทๅๆต็จ่็นๅ
ณ่็ไฝไธๅทฅๅๅ้กตๅ่กจ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-4-29
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param searchEntity ๆฅ่ฏขๅฎไฝ
* @return ๆต็จ่็นๅ
ณ่็ไฝไธๅทฅๅๅ้กตๅ่กจ
* @throws BusinessException
*/
public Page<WorkCardQueryBean> getWorkCardListByNode(SearchEntity<WorkCard> searchEntity) throws BusinessException {
WorkCard entity = searchEntity.getEntity();
// ๆฅ่ฏขๆกไปถ - ่ฝฆๅ
if (StringUtil.isNullOrBlank(entity.getNodeCaseIDX()))
return new Page<WorkCardQueryBean>();
String sql = SqlMapUtil.getSql("jxgc-workcardquery:getWorkCardListByNode")
.replace("#nodeIDX#", entity.getNodeCaseIDX());
StringBuilder sb = new StringBuilder(sql);
// ๆฅ่ฏขๆกไปถ - ไฝไธๅ็งฐ
if (!StringUtil.isNullOrBlank(entity.getWorkCardName())) {
sb.append(" AND A.WORK_CARD_NAME LIKE '%").append(entity.getWorkCardName()).append("%'");
}
AbstractEntityPersister meta = (AbstractEntityPersister) getDaoUtils().getSessionFactory().getClassMetadata(WorkCardQueryBean.class);
String sortString = "";
Order[] orders = searchEntity.getOrders();
if (orders != null && orders.length > 0) {
for (Order order : orders) {
String[] orderStrings = StringUtil.tokenizer(order.toString(), " ");
if (orderStrings == null || orderStrings.length != 2)
continue;
if (orderStrings[0].equals("workCardCode") ||
orderStrings[0].equals("workCardName") ||
orderStrings[0].equals("status")) {
sortString = CommonUtil.buildOrderSql("A.", meta, orderStrings);
}
}
sb.append(sortString);
} else {
sb.append(" ORDER BY A.WORK_CARD_CODE ASC");
}
sql = sb.toString();
StringBuilder totalSql = new StringBuilder("SELECT COUNT(*) AS ROWCOUNT FROM (").append(sql).append(Constants.BRACKET_R);
Page<WorkCardQueryBean> page = this.acquirePageList(totalSql.toString(), sql, searchEntity.getStart(), searchEntity.getLimit(), false);
//ๅๅคๆผๆฅไฝไธไบบๅๅงๅ
for (WorkCardQueryBean w : page.getList()) {
StringBuffer stringBuffer = new StringBuffer(300);
//ๅฆๆworkerไธบ็ฉบ่ฏดๆๅทฅๅไธบๅค็ไธญ๏ผๅค็ไบบ้่ฟไฝไธๅทฅๅidๅๆฅpjgc_worker่กจ็workerไบบๅ
if (StringUtil.isNullOrBlank(w.getWorker())) {
Worker worker = new Worker();
worker.setWorkCardIDX(w.getIdx());
//้่ฟworCardIDXๆฅ่ฏขๅฏนๅบ็workไฟกๆฏ๏ผ็จ,ๅๅฒ
List<Worker> list = workerManager.findList(worker);
int listSize = list.size();
for (int i = 0; i < listSize; i++) {
Worker wo = list.get(i);
if (i == listSize - 1) {
}else {
stringBuffer.append(wo.getWorkerName()).append(",");
}
}
//ๅฆๆๆฏๅค็ๅฎๆ็๏ผ็ดๆฅๅworkerๅญๆฎตไธญ็ๅผๅณๅฏ
}else{
stringBuffer.append(w.getWorker());
}
w.setWorker(stringBuffer.toString());
}
return page;
}
/**
* <li>่ฏดๆ๏ผๅบไบsqlๆฅ่ฏข่ฏญๅฅ็ๅ้กตๆฅ่ฏข
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-1-28
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param totalSql ๆฅ่ฏขๆป่ฎฐๅฝๆฐ็sql่ฏญๅฅ
* @param sql ๆฅ่ฏข่ฏญๅฅ
* @param start ๅผๅง่ก
* @param limit ๆฏ้กต่ฎฐๅฝๆฐ
* @param isQueryCacheEnabled ๆฏๅฆๅฏ็จๆฅ่ฏข็ผๅญ
* @return Page<ZbglJYRdpBean> ๅ้กตๆฅ่ฏขๅ่กจ
* @throws BusinessException
*/
@SuppressWarnings("unchecked")
public Page<WorkCardQueryBean> acquirePageList(String totalSql, String sql, int start, int limit, Boolean isQueryCacheEnabled)
throws BusinessException {
final int beginIdx = start < 0 ? 0 : start;
final int pageSize = limit < 0 ? Page.PAGE_SIZE : limit;
final String total_sql = totalSql;
final String fSql = sql;
final Boolean useCached = isQueryCacheEnabled;
HibernateTemplate template = this.daoUtils.getHibernateTemplate();
return (Page<WorkCardQueryBean>) template.execute(new HibernateCallback() {
public Page<WorkCardQueryBean> doInHibernate(Session s) {
SQLQuery query = null;
try {
query = s.createSQLQuery(total_sql);
query.addScalar("rowcount", Hibernate.INTEGER);
query.setCacheable(useCached); // ็ผๅญๅผๅ
ณ
int total = ((Integer) query.uniqueResult()).intValue();
query.setCacheable(false);
int begin = beginIdx > total ? total : beginIdx;
query = (SQLQuery) s.createSQLQuery(fSql).addEntity(WorkCardQueryBean.class).setFirstResult(begin).setMaxResults(pageSize);
query.setCacheable(useCached); // ็ผๅญๅผๅ
ณ
return new Page<WorkCardQueryBean>(total, query.list());
} catch (HibernateException e) {
throw e;
} finally {
if (query != null)
query.setCacheable(false);
}
}
});
}
/**
* <li>่ฏดๆ๏ผ่ทๅ่็นๅ
ณ่็ๅทฒๅฎๆ็ไฝไธๅทฅๅๆฐ้
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-22
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param nodeIDX ่็นIDX
* @return ่็นๅ
ณ่็ๅทฒๅฎๆ็ไฝไธๅทฅๅๆฐ้
*/
public int getCompleteWorkCardCountByNode(String nodeIDX) {
return CommonUtil.getListSize(getCompleteWorkCardByNode(nodeIDX));
}
/**
* <li>่ฏดๆ๏ผ่ทๅ่็นๅ
ณ่็ไฝไธๅทฅๅๆฐ้
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-22
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param nodeIDX ่็นIDX
* @return ่็นๅ
ณ่็ไฝไธๅทฅๅๆฐ้
*/
public int getWorkCardCountByNode(String nodeIDX) {
return CommonUtil.getListSize(getWorkCardByNode(nodeIDX));
}
/**
* <li>่ฏดๆ๏ผ่ทๅ่็นๅ
ณ่็ๅทฒๅค็ๆๅทฒ็ปๆญข็ไฝไธๅทฅๅๅ่กจ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-22
* <li>ไฟฎๆนไบบ๏ผ ็จ้
* <li>ไฟฎๆนๆฅๆ๏ผ2015-6-4
* <li>ไฟฎๆนๅ
ๅฎน๏ผๅ ๅ
ฅ่ดจๆฃไธญ็ถๆ็ไฝไธๅทฅๅ
* @param nodeIDX ่็นIDX
* @return ่็นๅ
ณ่็ๅทฒๅค็ๆๅทฒ็ปๆญข็ไฝไธๅทฅๅๅ่กจ
*/
@SuppressWarnings("unchecked")
public List<WorkCard> getCompleteWorkCardByNode(String nodeIDX) {
Map paramMap = new HashMap<String, String>();
paramMap.put("nodeCaseIDX", nodeIDX);
StringBuilder status = new StringBuilder();
status.append("in'")
.append(WorkCard.STATUS_HANDLED)
.append("','")
.append(WorkCard.STATUS_TERMINATED)
.append("','")
.append(WorkCard.STATUS_FINISHED)
.append("'");
paramMap.put("status", status.toString());
return getWorkCardList(paramMap);
}
/**
* <li>่ฏดๆ๏ผ่ทๅ่็นๅ
ณ่็ไฝไธๅทฅๅๅ่กจ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-6
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param nodeIDX ่็นIDX
* @return ่็นๅ
ณ่็ไฝไธๅทฅๅๅ่กจ
*/
@SuppressWarnings("unchecked")
public List<WorkCard> getWorkCardByNode(String nodeIDX) {
Map paramMap = new HashMap<String, String>();
paramMap.put("nodeCaseIDX", nodeIDX);
return getWorkCardList(paramMap);
}
/**
* <li>่ฏดๆ๏ผ่ทๅไฝไธๅทฅๅๅ่กจ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-6
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param paramMap ๆฅ่ฏขๅๆฐmap key๏ผๅญๆฎตๅ value:ๅญๆฎตๅผ
* @return ไฝไธๅทฅๅๅ่กจ
*/
@SuppressWarnings("unchecked")
private List<WorkCard> getWorkCardList(Map paramMap) {
StringBuilder hql = new StringBuilder();
hql.append("from WorkCard where 1 = 1 ").append(CommonUtil.buildParamsHql(paramMap)).append(" and recordStatus = 0");
return daoUtils.find(hql.toString());
}
/**
* <li>่ฏดๆ๏ผๆ นๆฎๅทฅ่บ่็น่ทๅๅค็ไธญๅๅทฒๅค็็ไฝไธๅทฅๅๅ่กจ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2013-7-31
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param nodeCaseIDX ๆต็จ่็นID
* @param workPlanIDX ไฝไธ่ฎกๅIDX
* @return ๅค็ไธญๅๅทฒๅค็็ไฝไธๅทฅๅๅ่กจ
* @throws Exception
*/
@SuppressWarnings("all")
public List getOnGoingCardByNode(String nodeCaseIDX, String workPlanIDX) throws Exception{
String sql = SqlMapUtil.getSql("jxgc-workcardquery:getOnGoingCardByNode").replace("#nodeCaseIDX#", nodeCaseIDX)
.replace("#STATUS_HANDLING#", WorkCard.STATUS_HANDLING)
.replace("#STATUS_HANDLED#", WorkCard.STATUS_HANDLED)
.replace("#STATUS_FINISHED#", WorkCard.STATUS_FINISHED)
.replace("#tecProcessCaseIDX#", nodeCaseIDX)
.replace("#STATUS_GOING#", JobProcessNode.STATUS_GOING)
.replace("#STATUS_COMPLETE#", JobProcessNode.STATUS_COMPLETE)
.replace("#workPlanIDX#", workPlanIDX);
return daoUtils.executeSqlQuery(sql);
}
/**
* <li>่ฏดๆ๏ผ่ทๅ่็นไธๆ ๅทฅไฝๅ็ญ็ป็ๆชๅฎๆ็ไฝไธๅทฅๅๅ่กจ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-21
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param nodeIDX ่็นIDX
* @return ่็นไธๆ ๅทฅไฝๅ็ญ็ป็ๆชๅฎๆ็ไฝไธๅทฅๅๅ่กจ
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<WorkCard> getNoStationAndTeamListByNode(String nodeIDX) throws Exception {
String hql = SqlMapUtil.getSql("jxgc-workcardquery:getNoStationAndTeamListByNode")
.replace("#nodeIDXS#", CommonUtil.buildInSqlStr(nodeIDX))
.replace("#STATUS_HANDLING#", WorkCard.STATUS_HANDLING)
.replace("#STATUS_NEW#", WorkCard.STATUS_NEW)
.replace("#STATUS_OPEN#", WorkCard.STATUS_OPEN);
return daoUtils.find(hql);
}
/**
* <li>่ฏดๆ๏ผๆ นๆฎไฝไธๅทฅๅๅ่กจๆ้ ไฝไธๅทฅๅIDXไธบไปฅ,ๅทๅ้็sqlๅญ็ฌฆไธฒ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-4-28
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param list ไฝไธๅทฅๅๅ่กจ
* @return ไปฅ,ๅทๅ้็ไฝไธๅทฅๅIDX็sqlๅญ็ฌฆไธฒ
* @throws Exception
*/
public String buildSqlIDXStr(List<WorkCard> list) throws Exception {
return CommonUtil.buildInSqlStr(buildIDXBuilder(list).toString());
}
/**
* <li>่ฏดๆ๏ผๆ นๆฎไฝไธๅทฅๅๅ่กจๆ้ ไฝไธๅทฅๅIDXไธบไปฅ,ๅทๅ้็ๅญ็ฌฆไธฒ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-21
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param list ไฝไธๅทฅๅๅ่กจ
* @return ไปฅ,ๅทๅ้็ไฝไธๅทฅๅIDXๅญ็ฌฆไธฒ
* @throws Exception
*/
public StringBuilder buildIDXBuilder(List<WorkCard> list) throws Exception {
StringBuilder idxs = new StringBuilder();
for (WorkCard card : list) {
idxs.append(card.getIdx()).append(",");
}
idxs.deleteCharAt(idxs.length() - 1);
return idxs;
}
/**
* <li>่ฏดๆ๏ผๆ นๆฎไฝไธๅทฅๅๅ่กจๆ้ ไฝไธๅทฅๅIDXๆฐ็ป
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-5-21
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param list ไฝไธๅทฅๅๅ่กจ
* @return ไฝไธๅทฅๅIDXๆฐ็ป
*/
public String[] buildIDXArray(List<WorkCard> list) {
String[] ids = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
ids[i] = list.get(i).getIdx();
}
return ids;
}
/**
* <li>่ฏดๆ๏ผ่ทๅไฝไธๅทฅๅ็ๅ
ถไปๅค็ไบบๅ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-7-8
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param workCardIDX ไฝไธๅทฅๅIDX
* @param empid ๅฝๅไบบๅID
* @return ไฝไธไบบๅๅ่กจ
*/
public List<Worker> getOtherWorkerByWorkCard(String workCardIDX, String empid) {
return workerManager.getOtherWorkerByWorkCard(workCardIDX, empid);
}
/**
* <li>่ฏดๆ๏ผๆ นๆฎไฝไธๅทฅๅidx่ทๅ้่ฆๆๆดพ็่ดจ้ๆฃๆฅ้กนๅ่กจ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2014-11-24
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* @param workCardIDXS ไฝไธๅทฅๅidx,ๅคไธชidx็จ,ๅ้
* @return ้่ฆๆๆดพ็่ดจ้ๆฃๆฅ้กนๅ่กจ
* @throws Exception
*/
public List<QCResult> getIsAssignCheckItems(String workCardIDXS) throws Exception {
return qCResultManager.getIsAssignCheckItems(workCardIDXS);
}
/**
* <li>ๆ ้ข: ๆบ่ฝฆๆฃไฟฎๆดๅค็ฎก็ไฟกๆฏ็ณป็ป
* <li>่ฏดๆ: ไฝไธๅทฅๅๆฅ่ฏขๅฎไฝ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-4-29
* <li>ไฟฎๆนไบบ:
* <li>ไฟฎๆนๆฅๆ๏ผ
* <li>ไฟฎๆนๅ
ๅฎน๏ผ
* <li>็ๆ: Copyright (c) 2008 ่ฟ่พพ็งๆๅ
ฌๅธ
* @author ไฟกๆฏ็ณป็ปไบไธ้จๆฃไฟฎๆดๅค็ณป็ป้กน็ฎ็ป
* @version 1.0
*/
@Entity
private static class WorkCardQueryBean {
/* idxไธป้ฎ */
@Id
private String idx;
/* ไฝไธๅก็ผ็ */
private String workCardCode;
/* ไฝไธๅกๅ็งฐ */
private String workCardName;
/*่ดจ้ๆฃๆฅ*/
private String qcName;
/* ็ถๆ */
private String status;
/* ็ถๆ */
private String extensionClass;
/* ไฝไธไบบๅ */
private String worker;
/**
* <li>่ฏดๆ๏ผ้ป่ฎคๆ้ ๆนๆณ
* <li>ๅๅปบไบบ๏ผ็จ้
* <li>ๅๅปบๆฅๆ๏ผ2015-4-29
* <li>ไฟฎๆนไบบ๏ผ
* <li>ไฟฎๆนๆฅๆ๏ผ
*/
public WorkCardQueryBean() {
}
public String getWorker() {
return worker;
}
public void setWorker(String worker) {
this.worker = worker;
}
public String getIdx() {
return idx;
}
public void setIdx(String idx) {
this.idx = idx;
}
public String getQcName() {
return qcName;
}
public void setQcName(String qcName) {
this.qcName = qcName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getWorkCardCode() {
return workCardCode;
}
public void setWorkCardCode(String workCardCode) {
this.workCardCode = workCardCode;
}
public String getWorkCardName() {
return workCardName;
}
public void setWorkCardName(String workCardName) {
this.workCardName = workCardName;
}
public String getExtensionClass() {
return extensionClass;
}
public void setExtensionClass(String extensionClass) {
this.extensionClass = extensionClass;
}
}
}
|
JavaScript
|
UTF-8
| 2,228 | 2.640625 | 3 |
[] |
no_license
|
function createDot () {
let dot = document.createElement("div")
dot.style.position = "absolute"
dot.style.height = "10px"
dot.style.width = "10px"
dot.style.background = "#fff"
dot.style.boxSizing = "border-box"
dot.style.border = "1px solid #000"
return dot
}
function createOutline () {
let outline = document.createElement("div")
outline.classList.add("_outline")
outline.style.position = "absolute"
outline.style.zIndex = "1988"
outline.style.top = "0"
outline.style.left = "0"
outline.style.height = "100px"
outline.style.width = "100px"
outline.style.boxSizing = "border-box"
outline.style.border = "1px dotted #333"
outline.style.pointerEvents = "none"
let dot = createDot()
dot.style.left = "-5px"
dot.style.top = "-5px"
outline.appendChild(dot)
dot = createDot()
dot.style.left = "-5px"
dot.style.bottom = "-5px"
outline.appendChild(dot)
dot = createDot()
dot.style.right = "-5px"
dot.style.top = "-5px"
outline.appendChild(dot)
dot = createDot()
dot.style.right = "-5px"
dot.style.bottom = "-5px"
outline.appendChild(dot)
return outline
}
export default {
install (Vue) {
Vue.directive("highlight", {
unbind: function (el, binding) {
if (el.outline) {
el.outline.parentNode.removeChild(el.outline)
}
},
componentUpdated: function (el, binding) {
el._show = binding.value
if (!el.outline) {
el.outline = createOutline()
el.parentNode.appendChild(el.outline)
el._resize = function () {
el.outline.style.display = el._show ? "block" : "none"
el.outline.style.top = el.offsetTop + "px"
el.outline.style.left = el.offsetLeft + "px"
el.outline.style.width = el.offsetWidth + "px"
el.outline.style.height = el.offsetHeight + "px"
if (event) event.stopPropagation() // ้ปๆญขๅๆณก,้ฟๅ
ๅฝฑๅไธ็บง็ปไปถ
}
el.addEventListener("transitionend", el._resize)
el.addEventListener("load", el._resize)
}
if (binding.value) {
el._resize()
} else {
el.outline.style.display = "none"
}
}
})
}
}
|
C++
|
GB18030
| 544 | 3.875 | 4 |
[] |
no_license
|
//ศกฦณศพฮป1ยฑึต+1ยฑ0สผ16 = 10000๒ณคถ5 2= 0010ฮช2
#include <iostream>
using namespace std;
int length(int num)
{
int count = 0;
while(num)
{
count++;
num >>= 1;
}
return count;
}
int main()
{
int number;
cout << "" << endl;
while(cin >> number)
{
cout << "ฦณวฃ " << length(number) << endl;
cout << "" << endl;
}
return 0;
}
|
C#
|
UTF-8
| 1,715 | 2.609375 | 3 |
[] |
no_license
|
๏ปฟusing econoomic_planer_X.Market;
using System;
namespace econoomic_planer_X.ResourceSet
{
public class TradingResource : Resource, IComparable, IEquatable<TradingResource>
{
public Population Owner { get; set; }
public TradingResource() { }
public TradingResource(Population Owner, ResourceType resourceType, double Amount) : base(resourceType, Amount)
{
this.Owner = Owner;
}
public ExternatlTradingResource SplitExternal(double ratio, ExternalMarket destination, double localTravelTime)
{
double splitAmount = Amount * ratio;
Amount -= splitAmount;
return new ExternatlTradingResource(Owner, ResourceType, destination, splitAmount, localTravelTime);
}
public bool AffordTransport()
{
return Owner.AffordTransport();
}
public void Trade(double ratio, double price)
{
Owner.TradeGain(ratio * Amount * price);
Amount -= ratio * Amount;
}
public bool Empty()
{
return Amount <= 0;
}
public int CompareTo(TradingResource tr)
{
if (Owner.ID.CompareTo(tr.Owner.ID) == 0 && ResourceType.Id == tr.ResourceType.Id)
{
return 0;
}
return -1;
}
public int CompareTo(object obj)
{
return CompareTo((TradingResource)obj);
}
internal void Add(TradingResource su)
{
this.Amount += su.Amount;
}
public bool Equals(TradingResource other)
{
return CompareTo(other) == 0;
}
}
}
|
Python
|
UTF-8
| 601 | 3.671875 | 4 |
[] |
no_license
|
import numpy as np
import pandas as pd
# ์ฐ์ต ๋ฌธ์
# 1. ๋ชจ๋ ํ๊ณผ ์ด์ ๋ผ๋ฒจ์ ๊ฐ์ง๋ 5 x 5 ์ด์์ ํฌ๊ธฐ๋ฅผ ๊ฐ์ง๋ ๋ฐ์ดํฐํ๋ ์์ ๋ง๋ ๋ค.
df = pd.DataFrame(np.arange(10, 35).reshape(5, 5),
index=["a", "b", "c", "d", "e"],
columns=["A", "B", "C", "D","E"])
df
# 2. 10๊ฐ์ง ์ด์์ ๋ฐฉ๋ฒ์ผ๋ก ํน์ ํ ํ๊ณผ ์ด์ ์ ํํ๋ค.
df[:"a"]
df["A"]
df["a":"e"]
df.loc["a","A"]
df.loc["b":,"A"]
df.loc["a", :]
df.loc[["a","b"],["B","D"]]
df.iloc[0,1] # df.loc["a","A"] ์ ๊ฐ์
df.iloc[:2]
df.iloc[0, -2:]
df.iloc[2:3, 1:3]
|
Markdown
|
UTF-8
| 2,131 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
autoGrow jQuery plugin
======================
Auto resize input fields to fit content when user types.
Works both with jQuery and Zepto.js.
Usage
-----
To autoresize text field use:
```js
$('#myTextField').autoGrow({
comfortZone: 70 // default value
});
// or just
$('#myTextField').autoGrow(70);
```
When you update styles that change text size use:
```js
$('#myTextField').autoGrow();
```
You can also update comfort zone:
```js
$('#myTextField').autoGrow(newComfortZone);
```
To disable autogrowing:
```js
$('#myTextField').autoGrow('remove');
// or
$('#myTextField').autoGrow(false);
// or
$('#myTextField').autoGrow({remove: true});
```
Limiting width
--------------
To limit width use css properties `min-width` and `max-width`.
When `min-width` is set to `0px` (default browser value),
minimum width is limited to current width.
Animating
---------
If you wish smoothly resize textfields use following styles:
```css
#myTextField {
transition: width 100ms linear;
}
```
Do not forget to add vendor prefixes for transition.
License
-------
Copyright ยฉ 2012โ2013 Roman Kivalin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the โSoftwareโ),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED โAS ISโ, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
JavaScript
|
UTF-8
| 1,774 | 2.984375 | 3 |
[] |
no_license
|
const postsNode = document.getElementById('posts');
function show() {
fetch('/posts')
.then(response => response.json())
.then(posts => {
let html = '';
for (const post of posts) {
html += `
<h2>${post[1]} <sup>#${post[0]}</sup></h2>
<time class="badge badge-info">${new Date(post[3] * 1000)}</time>
<button class="btn btn-sm btn-outline-danger" onClick="deletePost(${post[0]})">Delete</button>
<article>${post[2]}</article>
`;
}
postsNode.innerHTML = html;
}).catch(error => {
console.log(error);
});
}
show();
function deletePost(id) {
fetch(`/posts/${id}`, {
method: 'DELETE'
}).then(function (_response) {
show();
}).catch(function (error) {
console.log(error);
})
}
const addPostForm = document.getElementById('add-post-form');
const controls = document.querySelectorAll('input, textarea');
const submitButton = document.querySelector('[type="submit"]');
const setSubmitEnabled = (doEnable) => {
if (doEnable) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', '');
};
};
addPostForm.addEventListener('submit', event => {
event.preventDefault();
setSubmitEnabled(false);
const data = {};
Array.from(controls).forEach(el => {
data[el.getAttribute('name')] = el.value;
});
fetch('/posts/create', {
method: 'POST',
body: JSON.stringify(data),
}).then(function (_response) {
addPostForm.reset();
setSubmitEnabled(true);
show();
}).catch(function (error) {
setSubmitEnabled(true);
console.log(error);
})
});
|
JavaScript
|
UTF-8
| 749 | 2.6875 | 3 |
[] |
no_license
|
(function () {
//instance in controller
var prod = new productnamespace.Product(1, " SampleProduct", 500, 'Product description');
// binding the object properties to the view
document.write(prod.prodId);
document.write(prod.prodName);
document.write(prod.prodPrice);
document.write(prod.prodDesc);
})(window.productnamespace, window.ns);
(function () {
//instance in controller
var corolla = new ns.Vehicle(111, "Toyota", "Hebbal Main Road");
// binding the object properties to the view
document.write("----------------Name Space two------------");
document.write(corolla.vId);
document.write(corolla.vName);
document.write(corolla.vAddress);
})(window.ns);
|
PHP
|
UTF-8
| 968 | 3.140625 | 3 |
[] |
no_license
|
<?php
require "Equacao2grau.php";
class EquacoesTest extends PHPUnit_Framework_TestCase
{
public function testConstruct(){
$eq2g = new Equacao2grau(1, 2, 3);
$this->assertEquals(1, $eq2g->a);
$this->assertEquals(2, $eq2g->b);
$this->assertEquals(3, $eq2g->c);
}
public function testSetDelta(){
$eq2g = new Equacao2grau(1, -4, 3);
$eq2g->setDelta();
$this->assertEquals(4, $eq2g->delta);
$eq2g = new Equacao2grau(2, -4, 2);
$eq2g->setDelta();
$this->assertEquals(0, $eq2g->delta);
}
public function testCalcular(){
$eq2g = new Equacao2grau(1, -4, 3);
$eq2g->calcular();
$this->assertEquals(3, $eq2g->raiz1);
$this->assertEquals(1, $eq2g->raiz2);
$eq2g = new Equacao2grau(2, -4, 2);
$eq2g->calcular();
$this->assertEquals(1, $eq2g->raiz1);
$this->assertEquals(1, $eq2g->raiz2);
}
}
?>
|
Python
|
UTF-8
| 1,353 | 2.59375 | 3 |
[] |
no_license
|
import requests
from yarl import URL
url = 'http://budget.gov.ru/epbs/registry/7710568760-BUDGETS/data'
payload = dict(
pageSize=2,
filterstatus='ACTIVE',
pageNum=1,
)
conversion = dict()
class ApiDataLoader:
"""
"""
def __init__(self, timeout=5) -> None:
self.timeout = timeout
self.session = requests.Session
def get_raw_data(self, url, payload):
"""
"""
with self.session() as session:
response = session.get(url, params=payload, timeout=self.timeout)
response.raise_for_status()
return response.json()
@staticmethod
def get_data(raw_data, key_field):
"""
"""
return raw_data[key_field]
@staticmethod
def convert_data(data, conversion):
"""
"""
new_data = []
for element in data:
for k, v in element.items():
k = conversion.get(k, k)
new_data.append({k: v})
return new_data
def get_data_from_api(self, url, payload, key_field='data', conversion=None):
"""
"""
url = URL(url)
raw_data = self.get_raw_data(url, payload)
data = self.get_data(raw_data, key_field)
if conversion is not None:
return self.convert_data(data, conversion)
return data
|
TypeScript
|
UTF-8
| 609 | 2.84375 | 3 |
[] |
no_license
|
import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
} from '@nestjs/common';
@Injectable()
export class ValidFilterPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
const theNYTimesOption = 'thenytimes';
const theGuardianOption = 'theguardian';
const isValid = value === theNYTimesOption || value === theGuardianOption;
if (!isValid && value) {
throw new BadRequestException(
`The param: ${metadata.data} can pass only ${theNYTimesOption} either ${theGuardianOption} `,
);
}
return value;
}
}
|
Python
|
UTF-8
| 475 | 3.390625 | 3 |
[] |
no_license
|
a, b = list(map(int, input().split()))
g1 = [["#" for i in range(100)] for i in range(20)]
g2 = [["." for i in range(100)] for i in range(20)]
a, b = a-1, b-1
j = 0
while a!=0:
for i in range(0, 100, 2):
g1[j][i] = "."
a -= 1
if a==0:
break
j += 2
j = 1
while b!=0:
for i in range(0, 100, 2):
g2[j][i] = "#"
b -= 1
if b==0:
break
j += 2
g1.extend(g2)
print(40, 100)
for ele in g1:
print("".join(ele))
|
Python
|
UTF-8
| 347 | 3.703125 | 4 |
[] |
no_license
|
def fibonacci(num):
if num == 1:
return 0
elif num == 2:
return 1
index = 2
def calc(first, second):
nonlocal index
index = index + 1
result = first + second
if index == num:
return result
return calc(second, result)
return calc(0, 1)
print(fibonacci(5))
|
C++
|
UTF-8
| 1,580 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
#include <iostream>
using namespace std;
#define BIGINT_SIZE (1000)
class BigInt {
private:
unsigned int _num[BIGINT_SIZE]{};
void carry_up() {
for (int i = 0; i < BIGINT_SIZE - 1; ++i) {
if (_num[i] >= 10) {
_num[i + 1] += _num[i] / 10;
_num[i] %= 10;
}
}
}
public:
BigInt() {
for (unsigned int &i : _num) {
i = 0;
}
}
void add(int num) {
_num[0] += num;
carry_up();
}
string to_string() {
int i = BIGINT_SIZE - 1;
for (; i >= 0; --i) {
if (_num[i] != 0) break;
}
if (i < 0) {
return "0";
}
string ret;
while (i >= 0) {
ret += ::to_string(_num[i]);
i--;
}
return ret;
}
};
int main() {
string s, t;
cin >> s >> t;
BigInt count;
int prev_pos = -1;
for (char c : t) {
if (++prev_pos >= s.length()) {
prev_pos = 0;
count.add(s.length());
}
int pos_from_prev_pos = s.find(c, prev_pos);
if (pos_from_prev_pos != string::npos) {
prev_pos = pos_from_prev_pos;
continue;
}
count.add(s.length());
int pos_from_top = s.find(c);
if (pos_from_top == string::npos) {
cout << "-1" << endl;
return 0;
}
prev_pos = pos_from_top;
}
count.add(prev_pos + 1);
string answer = count.to_string();
cout << answer << endl;
}
|
Java
|
UTF-8
| 272 | 1.710938 | 2 |
[] |
no_license
|
/**
* @autor Chekmarev Andrey
* 3rd year, 7th group
* @version 1.0
* Main class
*/
public class Main {
public static void main(String[] args) throws Exception {
InjectTest injectTest = new Injector().inject(new InjectTest());
injectTest.doSmth();
}
}
|
C#
|
UTF-8
| 551 | 2.765625 | 3 |
[] |
no_license
|
๏ปฟusing UnityEngine;
namespace Game
{
/// <summary>
/// ECS Component that contains the properties required for the ECS Systems that handles gravity to work properly.
/// </summary>
public class GravityForce : MonoBehaviour
{
[Tooltip("The gravity force to apply to this GameObject")]
[SerializeField]
private float gravityForceFactor = 1.0f;
public float GravityForceFactor
{
get => gravityForceFactor;
private set => gravityForceFactor = value;
}
}
}
|
Go
|
UTF-8
| 193 | 2.84375 | 3 |
[] |
no_license
|
//ๅ
จ้่ฏปๆไปถ
package main
import (
"io/ioutil"
)
func main() {
data, err := ioutil.ReadFile("t0001.go")
if err != nil {
println(err.Error())
} else {
println(string(data))
}
}
|
C++
|
UTF-8
| 1,660 | 2.609375 | 3 |
[] |
no_license
|
#include "Project.h"
using namespace simplesql::operators;
Project::Project(const std::vector<ExpressionBase *>& _projectList, OperatorBase* _child)
: OperatorBase(_Project), child(children[0]) {
child = _child;
projectList.assign(_projectList.begin(), _projectList.end());
children[1] = nullptr;
}
Project::~Project() {
for (size_t i = 0; i < projectList.size(); i++)
delete projectList[i];
if (child != nullptr)
delete child;
}
bool Project::equalTo(OperatorBase* that) const {
Project* _that = (Project*)that;
if (that == nullptr) return false;
if (that->type != _Project) return false;
for (size_t i = 0; i < projectList.size(); i++)
if(!projectList[i]->equalTo(_that->projectList[i]))
return false;
return child->equalTo(_that->child);
}
bool Project::open() {
// maybe assert `resolved` here.
return child->open();
}
bool Project::close() {
return child->close();
}
std::string Project::projectString() const {
std::string result;
for (auto iter : projectList)
result += iter->toString() + ",";
return result;
}
NextResult Project::next() {
NextResult nextResult = child->next();
if (nextResult.row == nullptr)
return NextResult(nullptr);
MemoryPool* mp = nextResult.mp;
size_t listLen = projectList.size();
AnyValue** results = (AnyValue**)mp->allocate(listLen * sizeof(AnyValue*));
for (size_t i = 0; i < listLen; i++)
results[i] = projectList[i]->eval(nextResult.row, mp);
Row* newRow = Row::create(results, listLen, mp);
return NextResult(newRow, mp);
}
|
C++
|
UTF-8
| 1,026 | 3.265625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.length();
int m = word2.length();
vector<vector<int> > f;
f.resize(n + 1);
for (int i = 0; i <= n; i++) {
f[i].resize(m + 1);
}
for (int i = 0; i <= n; i++) {
f[i][0] = i;
}
for (int j = 0; j <= m; j++) {
f[0][j] = j;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
int val = std::min(f[i-1][j-1], std::min(f[i-1][j], f[i][j-1])) + 1;
if (i < j) {
val = std::min(f[i][i] + j-i, val);
}
if (i > j) {
val = std::min(f[j][j] + i-j, val);
}
if (word1[i-1] == word2[j-1]) {
val = std::min(f[i-1][j-1], val);
}
f[i][j] = val;
}
}
return f[n][m];
}
};
int main(int argc, char* argv[]) {
Solution s;
int distance = s.minDistance("sea", "ate");
cout << distance << endl;
return 0;
}
|
C++
|
UTF-8
| 676 | 2.796875 | 3 |
[] |
no_license
|
#include "subsystems/Drivetrain.h"
double boundValue(const double value, const double bound){
/**
* Bounds value to range [-bound,bound]
* If value is outside boundary, return appropriate boundry. Otherwise, return value.
*/
if(value < (-1.0 * bound)) return -1.0 * bound;
if(value > bound) return bound;
return value;
}
Drivetrain::Drivetrain() {
//Set encoder and spark parameters here
}
void Drivetrain::Drive(const double left,const double right){
double bounded_left=boundValue(left,1.0);
double bounded_right=boundValue(right,1.0);
FLMotor->Set(bounded_left);
BLMotor->Set(bounded_left);
FRMotor->Set(bounded_right);
BRMotor->Set(bounded_right);
}
|
C++
|
UTF-8
| 1,539 | 3.25 | 3 |
[] |
no_license
|
#include "Color.h"
#include <SDL.h>
const SDL_PixelFormat* Color::kFormat =
SDL_AllocFormat(SDL_PIXELFORMAT_ARGB8888);
Color Color::GetAlphaBlend(const Color& source, const Color& destination) {
float sourceAlpha = static_cast<float>(source.alpha()) / 255.0f;
float destinationAlpha = 1.0f - sourceAlpha;
uint8_t r = static_cast<uint8_t>(source.red() * sourceAlpha +
destination.red() * destinationAlpha);
uint8_t g = static_cast<uint8_t>(source.green() * sourceAlpha +
destination.green() * destinationAlpha);
uint8_t b = static_cast<uint8_t>(source.blue() * sourceAlpha +
destination.blue() * destinationAlpha);
uint8_t a = 255;
return Color(r, g, b, a);
}
Color::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
value_ = SDL_MapRGBA(kFormat, r, g, b, a);
}
uint8_t Color::red() const { return GetChannel(Channel::kRed); }
uint8_t Color::green() const { return GetChannel(Channel::kGreen); }
uint8_t Color::blue() const { return GetChannel(Channel::kBlue); }
uint8_t Color::alpha() const { return GetChannel(Channel::kAlpha); }
uint8_t Color::GetChannel(Channel channel) const {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
SDL_GetRGBA(value_, kFormat, &r, &g, &b, &a);
switch (channel) {
case Channel::kRed:
return r;
case Channel::kGreen:
return g;
case Channel::kBlue:
return b;
case Channel::kAlpha:
return a;
default:
return 0;
}
}
|
Swift
|
UTF-8
| 3,171 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
//
// Copyright ยฉ 2018 Frallware. All rights reserved.
//
import UIKit
import Frallware
final class PageView: UIView {
let firstView = UIView()
let secondView = UIView()
private lazy var pan = UIPanGestureRecognizer(target: self, action: #selector(didPan))
var pageChangeAction: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
addGestureRecognizer(pan)
[firstView, secondView].forEach { view in
view.clipsToBounds = true
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: centerXAnchor),
view.centerYAnchor.constraint(equalTo: centerYAnchor),
view.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, multiplier: 1.0),
view.heightAnchor.constraint(lessThanOrEqualTo: heightAnchor, multiplier: 1.0),
])
}
secondView.isHidden = true
}
@objc private func didPan(_ pan: UIPanGestureRecognizer) {
let shortestSideLength = min(firstView.bounds.width, firstView.bounds.height)
let largestCornerRadius = shortestSideLength / 2
let translation = pan.translation(in: self)
let transform = CGAffineTransform(translationX: translation.x, y: translation.y)
let translationDistance = sqrt(translation.x * translation.x + translation.y * translation.y)
switch pan.state {
case .began, .possible:
break
case .changed:
firstView.layer.cornerRadius = min(1.5 * translationDistance, largestCornerRadius)
firstView.transform = transform
case .ended, .cancelled, .failed:
performTransition(withVelocity: pan.velocity(in: self))
}
}
private func performTransition(withVelocity velocity: CGPoint) {
let diff = 0.4 * velocity
// let firstViewEndPoint = center + diff
// let secondViewStartPoint = center - diff
let velocityParam = CGVector(dx: velocity.x, dy: velocity.y).normalized()
let parameters = UISpringTimingParameters(dampingRatio: 1.0, initialVelocity: velocityParam)
let animator = UIViewPropertyAnimator(duration: 0.3, timingParameters: parameters)
secondView.isHidden = false
secondView.transform = CGAffineTransform(translationX: -diff.x, y: -diff.y)
pan.isEnabled = false
animator.addAnimations {
self.firstView.layer.cornerRadius = 0
self.firstView.transform = CGAffineTransform(translationX: diff.x, y: diff.y)
self.secondView.transform = .identity
}
animator.addCompletion { position in
self.firstView.transform = .identity
self.secondView.isHidden = true
self.pan.isEnabled = true
self.pageChangeAction?()
}
animator.startAnimation()
}
}
|
SQL
|
UTF-8
| 1,874 | 3.34375 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.9.5
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jul 04, 2021 at 01:00 PM
-- Server version: 5.7.24
-- PHP Version: 7.4.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `hr-digital`
--
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`ID` int(4) NOT NULL,
`PRODUCT_ID` int(6) NOT NULL,
`PRODUCT_NAME` varchar(100) CHARACTER SET utf8mb4 NOT NULL,
`PRODUCT_PRICE` int(7) NOT NULL,
`PRODUCT_ARTICLE` varchar(20) CHARACTER SET utf8mb4 NOT NULL,
`PRODUCT_QUANTITY` int(7) NOT NULL,
`DATE_CREATE` date NOT NULL,
`VISABLE` char(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`ID`, `PRODUCT_ID`, `PRODUCT_NAME`, `PRODUCT_PRICE`, `PRODUCT_ARTICLE`, `PRODUCT_QUANTITY`, `DATE_CREATE`, `VISABLE`) VALUES
(1, 1, 'ะััะพ', 223, '1V234', 11, '2021-07-03', 'YES'),
(2, 2, 'ะะพะปะพะบะพ', 150, '1B234', 34, '2021-07-04', 'YES');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`ID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `ID` int(4) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Markdown
|
UTF-8
| 4,422 | 2.78125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Contributing to Browsersync
We'd love for you to contribute to Browsersync and help make it even better than it is
today! Here are the guidelines we'd like you to follow:
- [Question or Problem?](#question)
- [Issues and Bugs](#issue)
- [Tips for a creating a great issue report](#tips)
- [Feature Requests](#feature)
- [Pull Requests](#pull)
- [Coding Rules](#rules)
- [Thank you](#thanks)
## <a name="question"></a> Got a Question or Problem?
If you have questions about how to *use* Browsersync, or about your particular setup, please
ask on [Stack Overflow](http://stackoverflow.com/). We're trying to keep the Issues thread
for actual bugs with code & implementation.
## <a name="issue"></a> Found an Issue?
On that note, if you think you *have* found a bug in Browsersync, please report
it via [Github Issues](https://github.com/BrowserSync/browser-sync/issues).
## <a name="tips"></a> Tips for a creating a great issue report
Whilst we do try to look at each and every issue as soon as possible, there are certain
aspects about your report that will determine how quickly/deeply we'll delve into it. A great
issue will contain at least the following:
* Operating System + Version
* Use case for Browsersync - are you using the built-in server, proxying your own server, or just using the snippet mode?
* Example configuration - show us your full `gulpfile.js`, `Gruntfile.js`, `bs-config.js` or any other code related to how you're using
Browsersync. If we have to respond to your very first issue report with "please provide information about how you're using Browsersync"
then it's very likely to fall to the bottom of the heap. Help us out by providing as much detail as possible!
* Provide a reduced test case. "Browsersync is not working with my app" is far less helpful than "Here's a example project showing the problem".
An example project might contain a single `index.html` file with some JS/CSS from CDNs & a short description of the issue. If we
can just pull a repo/gist and see the problem for ourselves, your issue will jump straight to the top of the stack.
* Screencast or GIF - not always appropriate, but can be very helpful where possible. (non-issue related gifs are always welcome, we'll often
respond with something from giphy :p)
## <a name="feature"></a> Want a Feature?
You can request a new feature by submitting an issue to our [Github Issues](https://github.com/BrowserSync/browser-sync/issues) page.
Prefix the title of your issue with "Feature Request:".
## <a name="docs"></a> Want a Doc Fix?
Head over to the [Browsersync Website Repo](https://github.com/BrowserSync/browsersync.github.io) & submit issues there.
## <a name="pull"></a> Submitting a Pull Request
Pull requests should always be branched off the main **Master** branch. (There's no guarantee that what lives on the develop
branch will ever make it back to master, I do a **lot** of experimentation).
**Never** commit directly to the master branch, instead create a new branch and submit a PR. This applies to users who have write access also.
**Note:** If your first PR is merged, you'll get write access to all Browsersync repos.
## <a name="rules"></a> Coding Advice
To ensure consistency throughout the source code, keep these rules in mind as you are working.
* If you're not sure how to provide tests for a feature or bug fix, you should still submit it and we'll help you complete the PR in one of the following ways:
* we can advise you how to go about it
* we can write the test, and then explain them to you.
* This project has a [.editorconfig](.editorconfig) file to help with code style; go to [EditorConfig.org](http://editorconfig.org) and download the plugin for your IDE.
* Don't introduce any extra 3rd party libraries unless you're creating a brand new feature that requires it.
* Try to keep your code simple and readable.
* Improve my code! Browsersync has a lot of moving parts and I don't pretend to be skilled in any particular area.
If *you* have particular experience though, then feel free to rip my code apart and tell me a better way to do something - I'll be extremely grateful (as will the growing number of users!).
## <a name="thanks"></a> Thank you!
If you contribute to Browsersync, or any other Open Source project, you're awesome! This project has been vastly improved
by community input & contributions and we look forward to continuing that trend.
|
Markdown
|
UTF-8
| 5,611 | 3.15625 | 3 |
[] |
no_license
|
---
title: "Sanity checks"
categories: sre opinion
---
In my line of work I've dealt with a lot of automated data pipelines that feed
into production systems.
Validating the output of these pipelines in an automated manner is frequently
difficult. Suppose you had a different data source you could validate against.
If you could reliably tell whether your pipeline was producing invalid data
using this data source, why not directly incorporate this data into your
pipeline? Alternatively, if the data source isn't reliable enough to do so,
chances are you'll need a human to come look at the diffs either way.
Another option is to simulate the production system under the new data, using
historical or current load. This is often prohibitively expensive and a large
maintenance burden, and usually impossible for data that rolls out at a high
cadence (sometimes this is unavoidable). It can work well in select scenarios,
however. This assumes you have good monitoring in place with a high degree of
coverage.
If your production system tolerates data version skew between instances, you can
get around validation by simply canarying the data to a small fraction of your
production instances. While this should prevent global outages, depending on the
nature of the service it might allow frequent smaller outages that eat into your
SLO. Proper semantic canarying might also be infeasible for data that rolls out
at a high cadence, but it's still worth the effort to catch crashes and other
immediately apparent problems.
The simplest and least expensive way to validate pipeline output is by sanity
checking the data before rolling it out. In my experience, simple absolute
checks like making sure the output (or input) is not empty will go a long way in
preventing outages. For more complex pipelines, performing these checks at every
stage can be very effective.
Absolute sanity checks may quickly become dated if the data experiences natural
growth. In this case, it is common to compare the new data against the data
currently in production (which is assumed to be valid). If the new data differs
from the old by some threshold, the new data is considered to be invalid and the
pipeline stalls. This works well when the data is difficult to validate at face
value, even by a human.
Usually it's difficult to determine what this threshold should be when you're
writing the check. I think most people just pick something that looks
reasonable, instead of doing a thorough analysis. I've heard people imply these
kinds of checks may as well be removed, given the arbitrariness of the
threshold. I've never really understood this argument. Often, it's really
difficult to do any kind of meaningful analysis. Data changes over time, and
it's likely that any analysis will quickly be dated. Surely having a (loose)
relative check is better than not having one at all?
Relative sanity checks have the problem of being noisy. In my experience only a
small fraction of alerts based on relative checks expose actual problems. But
this small fraction also prevents serious outages. Over time, well-tuned
thresholds can reduce the amount of noise, but it's hard to make it go away
entirely. This noise in itself can cause outages; I've seen two main classes of
this, both caused by humans.
The first is in a poorly automated system, where engineers frequently need to
inspect failing relative checks. This tends to cause fatigue. A failing relative
check due to a serious issue might be hidden beneath many other failing checks,
or masked by the fact that the failure is usually benign. If the usual response
is to simply let the data through, it's hard to blame the engineer when this
inevitably causes an outage. This usually indicates a problem with the pipeline.
If a check fails often, either relax/remove it or fix the underlying issue.
The second is when a sanity check fails, and the engineer has correctly
determined that the failure is benign. The engineer reruns the pipeline with
sanity checks disabled, at which point a different bug or data problem manifests
itself and causes a serious outage when the data rolls out to production.
This is solved by making it easy for an engineer to rerun the pipeline with
selectively relaxed thresholds. Risk can be further minimized by making sure
the pipeline is hermetic and deterministic. A properly hermetic pipeline also
makes it much easier to debug issues after a failure.
You could make a case for rolling out the output that failed the benign sanity
check rather than rerunning the pipeline, but this requires extra logic to hold
on to the data until a human is able to look at it and roll it out. If this code
path is not very well tested, it could also cause an outage. This is especially
the case if it is not executed very often. Additionally, if the pipeline has
been stalled for a while, a large enough delta may have accumulated that the
next run fails as well. In this case, being able to selectively relax thresholds
is crucial anyway, meaning the extra complexity required to push after failing a
check is usually not worth it.
Pipelines that are stalled too long are often problematic when they rely on
relative checks for validation. If the data is not easily sanity checked by a
human, you can be left completely blind to whether or not the data makes sense.
The longer the pipeline remains stalled the larger the delta and the worse the
problem becomes. The easiest way to deal with this is by making sure it doesn't
happen in the first place. Otherwise, having a good monitoring and canarying
story is often the only way out.
|
Python
|
UTF-8
| 2,444 | 3.578125 | 4 |
[] |
no_license
|
"""
- Reduce prices to peaks and troughs:
highs: [3, 4, 6, 7]
lows: [1, 2, 4, 5]
- Iterate all 2-part slicing on highs-lows pair.
for split in range(0, length-of-lows):
use D&C to calculate max profit of left part
use max(highs[s:]) - lows[s] to calculate max profit of right part
profit-of-one-split = profit of left + profit of right
final result is the maximum of all profit-of-one-split
"""
from typing import List
class Solution:
def __init__(self):
self.prices = None
self.highs = []
self.lows = []
self.subs = {} # { "4-7": (5, 2, 9) }, val (max profit, min, max)
def reduce(self, prices):
for idx, p in enumerate(prices):
if idx == 0:
if p < prices[idx + 1]:
self.lows.append(p)
elif idx == len(prices) - 1:
if prices[idx - 1] < p:
self.highs.append(p)
else:
if prices[idx - 1] >= p < prices[idx + 1]:
self.lows.append(p)
elif prices[idx - 1] < p >= prices[idx + 1]:
self.highs.append(p)
def maxWithOneTradeOnHl(self, s: int, e: int):
if s < 0 or e < 0:
raise ValueError
if e - s == 1:
h, l = self.highs[s], self.lows[s]
return h - l, l, h
key = f"{s}-{e}"
if key in self.subs:
return self.subs[key]
half = (e - s) // 2 + s
l_profit, l_min, l_max = self.maxWithOneTradeOnHl(s, half)
r_profit, r_min, r_max = self.maxWithOneTradeOnHl(half, e)
cross_profit = max(r_max - l_min, 0)
max_profit = max(l_profit, r_profit, cross_profit)
r = (max_profit, min(l_min, r_min), max(l_max, r_max))
self.subs[key] = r
return r
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
self.reduce(prices)
assert len(self.lows) == len(self.highs)
p_len = len(self.lows)
if p_len < 1:
return 0
elif p_len == 1:
return self.highs[0] - self.lows[0]
result = 0
for split in range(len(self.lows)):
l_profit = self.maxWithOneTradeOnHl(0, split)[0] if split > 0 else 0
r_profit = max(0, max(self.highs[split:]) - self.lows[split])
result = max(result, l_profit + r_profit)
return result
|
Java
|
UTF-8
| 6,312 | 2.40625 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.kk.AutoFillSystem.Windows;
import com.kk.AutoFillSystem.utility.PriceEstimation;
import static com.kk.AutoFillSystem.utility.Tools.closeWindow;
import static com.kk.AutoFillSystem.utility.Tools.showAlert;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
/**
* FXML Controller class
*
* @author Yi
*/
public class SetCostTemplateWindowController implements Initializable {
private MainWindowController mainWindow;
private PriceEstimation pe = PriceEstimation.getInstance();
private double currencyRate;
private double discount;
private double initfee;
private double extrafee;
private int boxweight;
private double vipDiscount;
private int shipCnt;
@FXML
private TextField textFieldRate;
@FXML
private TextField textFieldInitFee;
@FXML
private TextField textFieldExtraFee;
@FXML
private TextField textFieldDiscount;
@FXML
private TextField textFieldVIPDiscount;
@FXML
private TextField textFieldShipCount;
@FXML
private TextField textFieldBoxWeight;
@FXML
private Button btnSave;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// init values
discount = pe.getDiscount();
textFieldDiscount.setText("" + discount*100);
textFieldDiscount.requestFocus();
textFieldDiscount.textProperty().addListener((observable, oldValue, newValue) -> {
try {
discount = Double.parseDouble(newValue)/100;
} catch (NumberFormatException e) {
showAlert("Error", "Invalid Format :", "Discount has to be a number !", Alert.AlertType.ERROR);
textFieldDiscount.setText(oldValue);
}
});
currencyRate = pe.getCurrencyRatio();
textFieldRate.setText(""+ currencyRate);
textFieldRate.textProperty().addListener((observable, oldValue, newValue) -> {
try {
currencyRate = Double.parseDouble(newValue);
} catch (NumberFormatException e) {
showAlert("Error", "Invalid Format :", "Currency rate has to be a number !", Alert.AlertType.ERROR);
textFieldRate.setText(oldValue);
}
});
initfee = pe.getInitalShipFee();
textFieldInitFee.setText(""+ initfee);
textFieldInitFee.textProperty().addListener((observable, oldValue, newValue) -> {
try {
initfee = Double.parseDouble(newValue);
} catch (NumberFormatException e) {
showAlert("Error", "Invalid Format :", "Shipping initial fee has to be a number !", Alert.AlertType.ERROR);
textFieldInitFee.setText(oldValue);
}
});
extrafee = pe.getExtraShipFee();
textFieldExtraFee.setText(""+ extrafee);
textFieldExtraFee.textProperty().addListener((observable, oldValue, newValue) -> {
try {
extrafee = Double.parseDouble(newValue);
} catch (NumberFormatException e) {
showAlert("Error", "Invalid Format :", "Shipping extra fee has to be a number !", Alert.AlertType.ERROR);
textFieldExtraFee.setText(oldValue);
}
});
vipDiscount = pe.getVipDiscount();
textFieldVIPDiscount.setText("" + vipDiscount *100);
textFieldVIPDiscount.textProperty().addListener((observable, oldValue, newValue) -> {
try {
vipDiscount = Double.parseDouble(newValue) / 100;
} catch (NumberFormatException e) {
showAlert("Error", "Invalid Format :", "VIP discount has to be a number !", Alert.AlertType.ERROR);
textFieldVIPDiscount.setText(oldValue);
}
});
shipCnt = pe.getCount();
textFieldShipCount.setText(""+ shipCnt);
textFieldShipCount.textProperty().addListener((observable, oldValue, newValue) -> {
try {
shipCnt = Integer.parseInt(newValue);
} catch (NumberFormatException e) {
showAlert("Error", "Invalid Format :", "Ship count has to be a number !", Alert.AlertType.ERROR);
textFieldShipCount.setText(oldValue);
}
});
boxweight = pe.getExtraBoxWeight();
textFieldBoxWeight.setText("" + boxweight);
textFieldBoxWeight.textProperty().addListener((observable, oldValue, newValue) -> {
try {
boxweight = Integer.parseInt(newValue);
} catch (NumberFormatException e) {
showAlert("Error", "Invalid Format :", "Box weight has to be a number !", Alert.AlertType.ERROR);
textFieldBoxWeight.setText(oldValue);
}
});
//save button
btnSave.setOnAction(e->save(e));
}
private void save(ActionEvent e){
pe.setCount(shipCnt);
pe.setCurrencyRatio(currencyRate);
pe.setDiscount(discount);
pe.setExtraBoxWeight(boxweight);
pe.setExtraShipFee(extrafee);
pe.setInitalShipFee(initfee);
pe.setVipDiscount(vipDiscount);
showAlert("Success", "New Settings Saved :", "The new set of parameters has been save successfully !", Alert.AlertType.INFORMATION);
}
//getters and setters
public MainWindowController getMainWindow() {
return mainWindow;
}
public void setMainWindow(MainWindowController mainWindow) {
this.mainWindow = mainWindow;
}
}
|
C++
|
UTF-8
| 1,248 | 3.515625 | 4 |
[] |
no_license
|
/**
* @file node.cpp
*/
#include "node.hpp"
#include <cstring>
#include <iostream>
Node::Node() {
this->is_final = false;
for (unsigned int i = 0; i < 27; i++) {
this->tab[i] = nullptr;
}
}
Node::~Node() {
Node * temp = this;
for(unsigned int i = 0; i < 27; i++) {
delete temp->tab[i];
temp->tab[i] = nullptr;
}
}
Node* Node::getNode(const unsigned short int & i) const {
if (i < 27)
return tab[i];
if (i == static_cast<unsigned int>('+'))
return tab[26];
if (i - 'A' < 26)
return tab[i - 'A'];
return nullptr;
}
bool Node::isFinal() const {
return is_final;
}
Node* Node::addNode(const bool & b) {
Node * ptr = new Node();
ptr->is_final = b;
for (unsigned int i = 0 ; i < 27; i++) {
ptr->tab[i] = nullptr;
}
return ptr;
}
void Node::addNode(const std::string & s) {
unsigned int i = 0, size = s.size();
unsigned short int c;
Node * tmp = this;
for (i = 0; i < size; i++) {
if (s[i] == '+') //il s'agit d'un '+'
c = 26;
else // il s'agit d'une lettre
c = s[i] - 'A';
if (tmp->tab[c] == nullptr) //le chemin vers cette case n'existe pas encore
tmp->tab[c] = addNode( (i == size - 1) );
tmp = tmp->tab[c];
}
}
|
C++
|
UTF-8
| 1,404 | 2.953125 | 3 |
[] |
no_license
|
#pragma once
#include <algorithm>
#include <initializer_list>
class MojNizInt {
public:
MojNizInt() : c_{1}, n_{0}, p_{new int[1]} {};
MojNizInt(std::initializer_list<int> a) : c_{a.size()}, n_{a.size()}, p_{new int[n_]} {std::copy(std::begin(a), std::end(a), p_);}
MojNizInt(const MojNizInt&); //copy konstruktor
MojNizInt(MojNizInt&& drugi); //move-copy konstruktor
MojNizInt& operator=(const MojNizInt&); //copy jednako
MojNizInt& operator=(MojNizInt&&);
~MojNizInt() {delete[] p_;}; //destruktor
size_t size() const {return n_;}
size_t capacity() const {return c_;}
int at(const int& i) const;
int& at(const int& i); //ovo je potrebno kako bi se moglo promijeniti vrijednost sa at
int& operator[](const size_t& i) const {return p_[i];};
//MojNizInt operator*(int&&); //ovo slobodno ignorisi
MojNizInt& operator*=(const int& i) {for(size_t j =0; j<n_; j++) p_[j]*=i; return *this;};
MojNizInt& operator+=(const MojNizInt&);
MojNizInt operator++(int); //postfix++ il ti ga sufix
MojNizInt& operator++(); //++prefix
void push_back(const int&);
void pop_back() {n_-=1;};
int& front();
int& back();
private:
size_t c_;
size_t n_;
int* p_;
};
MojNizInt operator*(MojNizInt, const int&);
MojNizInt operator*(const int&, MojNizInt);
MojNizInt operator+(MojNizInt, const MojNizInt& drugi);
|
C++
|
UTF-8
| 411 | 2.875 | 3 |
[] |
no_license
|
#include "LogLevel.h"
std::string ToString(LogLevel level) {
switch (level) {
case LogLevel::TRACE:
return "TRACE";
case LogLevel::INFO:
return "INFO";
case LogLevel::WARN:
return "WARN";
case LogLevel::ERROR:
return "ERROR";
case LogLevel::SEVERE:
return "SEVERE";
default:
assert(false);
return "UNKNOWN_LOG_LEVEL";
}
}
|
C#
|
UTF-8
| 693 | 2.53125 | 3 |
[] |
no_license
|
๏ปฟ
using System.ComponentModel.DataAnnotations.Schema;
namespace UrbanDictionary.DataAccess.Entities
{
/// <summary>
/// Implement the many-to-many relationship with <see cref="Entities.User"/> and its saved <see cref="Entities.Word"/>.
/// </summary>
public class UserSavedWord
{
/// <summary>
/// Id of specific <see cref="User"/>
/// </summary>
public string UserId { get; set; }
public User User { get; set; }
/// <summary>
/// <see cref="User"/>s saved <see cref="Entities.Word"/> Id.
/// </summary>
public long SavedWordId { get; set; }
public Word SavedWord { get; set; }
}
}
|
Markdown
|
UTF-8
| 1,963 | 3.046875 | 3 |
[] |
no_license
|
# MC_WS17-18_2.PNG
**NOte**: a)-c) are multiple choice. d)-f) are questions to be answered with plain text.
a) Q: What is the main advantage of having a convex loss function?
A: They are relatively easy to optimize.
**Note**: Because there exists only one minimum which is per definition the global minimum.
b) Q: The k-means algorithm is an example of which of the following?
A: Unsupervised learning
**Note**: k-means is a clustering algorithm
c) Q: he gradient of a function f points in the direction of ____ of f.
A: steepest ascent
d) Q: What is the aim of supervised machine learning?
A: To train a classifier f with/on a given set of inputs and their respective labels (values in Regression) in order to accurately predict the labels of yet unseen datapoints.
e) Q: Describe the phenomena of โoverfittingโ and give an example of a technique one can employ to avoid it.
A: In overfitting, a too complex classifier that fits the training(!) data too well and that does therefore not accurately predict yet unseen data. The classifier does not "generalize" well to new data.
f) Q: Describe how the random forest algorithm works. You may assume that it is known how decision trees work.
A: From the training data select a random sample with replacements (note, if the original dataset has n datapoints, the sample has n datapoins as well).
(This, with the below described averaging/majority-vote is called bagging.)
Grow a decision tree on the dataset, but to determine each split of internal nodes a random subset of features (m<d) is selected and the optimal split is determined among those m features.
(This can be called feature-bagging and distinguishes the random forest from just plain bagging.)
Using the above procedure, arbitrarily many (users choice) decision trees are built which form the random forest.
The prediction of the random forest is then done using e.g. majority-vote for classification or averaging for regression.
|
Java
|
UTF-8
| 8,117 | 1.757813 | 2 |
[
"Artistic-1.0",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"EPL-1.0",
"CPL-1.0",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"LGPL-3.0-only",
"ECL-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-jdom",
"LicenseRef-scancode-freemarker",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
/**
* Copyright 2005-2015 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kim.api.identity.type;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.kim.api.identity.address.EntityAddress;
import org.kuali.rice.kim.api.identity.email.EntityEmail;
import org.kuali.rice.kim.api.identity.phone.EntityPhone;
import org.w3c.dom.Element;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
import java.util.Collection;
@XmlRootElement(name = EntityTypeContactInfoDefault.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = EntityTypeContactInfoDefault.Constants.TYPE_NAME, propOrder = {
EntityTypeContactInfoDefault.Elements.ENTITY_TYPE_CODE,
EntityTypeContactInfoDefault.Elements.DEFAULT_ADDRESS,
EntityTypeContactInfoDefault.Elements.DEFAULT_EMAIL_ADDRESS,
EntityTypeContactInfoDefault.Elements.DEFAULT_PHONE_NUMBER,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class EntityTypeContactInfoDefault extends AbstractDataTransferObject
{
@XmlElement(name = Elements.ENTITY_TYPE_CODE, required = true)
private final String entityTypeCode;
@XmlElement(name = Elements.DEFAULT_ADDRESS, required = false)
private final EntityAddress defaultAddress;
@XmlElement(name = Elements.DEFAULT_EMAIL_ADDRESS, required = false)
private final EntityEmail defaultEmailAddress;
@XmlElement(name = Elements.DEFAULT_PHONE_NUMBER, required = false)
private final EntityPhone defaultPhoneNumber;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Private constructor used only by JAXB.
*/
private EntityTypeContactInfoDefault() {
this.entityTypeCode = null;
this.defaultAddress = null;
this.defaultEmailAddress = null;
this.defaultPhoneNumber = null;
}
public EntityTypeContactInfoDefault(String entityTypeCode, EntityAddress defaultAddress,
EntityEmail defaultEmailAddress, EntityPhone defaultPhoneNumber) {
this.entityTypeCode = entityTypeCode;
this.defaultAddress = defaultAddress;
this.defaultEmailAddress = defaultEmailAddress;
this.defaultPhoneNumber = defaultPhoneNumber;
}
public EntityTypeContactInfoDefault(Builder builder) {
this.entityTypeCode = builder.getEntityTypeCode();
this.defaultAddress = builder.getDefaultAddress() == null ? null : builder.getDefaultAddress().build();
this.defaultEmailAddress = builder.getDefaultEmailAddress() == null ? null : builder.getDefaultEmailAddress().build();
this.defaultPhoneNumber = builder.getDefaultPhoneNumber() == null ? null : builder.getDefaultPhoneNumber().build();
}
public String getEntityTypeCode() {
return this.entityTypeCode;
}
public EntityAddress getDefaultAddress() {
return this.defaultAddress;
}
public EntityEmail getDefaultEmailAddress() {
return this.defaultEmailAddress;
}
public EntityPhone getDefaultPhoneNumber() {
return this.defaultPhoneNumber;
}
public final static class Builder
implements Serializable, ModelBuilder
{
private String entityTypeCode;
private EntityAddress.Builder defaultAddress;
private EntityEmail.Builder defaultEmailAddress;
private EntityPhone.Builder defaultPhoneNumber;
private Builder() { }
public static Builder create() {
return new Builder();
}
public static Builder create(EntityTypeContactInfoDefault immutable) {
if (immutable == null) {
throw new IllegalArgumentException("EntityTypeDataDefault is null");
}
Builder builder = new Builder();
builder.setEntityTypeCode(immutable.entityTypeCode);
if (immutable.getDefaultAddress() != null) {
builder.setDefaultAddress(EntityAddress.Builder.create(immutable.getDefaultAddress()));
}
if (immutable.getDefaultEmailAddress() != null) {
builder.setDefaultEmailAddress(EntityEmail.Builder.create(immutable.getDefaultEmailAddress()));
}
if (immutable.getDefaultPhoneNumber() != null) {
builder.setDefaultPhoneNumber(EntityPhone.Builder.create(immutable.getDefaultPhoneNumber()));
}
return builder;
}
public static Builder create(EntityTypeContactInfoContract contract) {
if (contract == null) {
throw new IllegalArgumentException("contract is null");
}
Builder builder = new Builder();
builder.setEntityTypeCode(contract.getEntityTypeCode());
if (contract.getDefaultAddress() != null) {
builder.setDefaultAddress(EntityAddress.Builder.create(contract.getDefaultAddress()));
}
if (contract.getDefaultEmailAddress() != null) {
builder.setDefaultEmailAddress(EntityEmail.Builder.create(contract.getDefaultEmailAddress()));
}
if (contract.getDefaultPhoneNumber() != null) {
builder.setDefaultPhoneNumber(EntityPhone.Builder.create(contract.getDefaultPhoneNumber()));
}
return builder;
}
public EntityTypeContactInfoDefault build() {
return new EntityTypeContactInfoDefault(this);
}
public String getEntityTypeCode() {
return entityTypeCode;
}
public void setEntityTypeCode(String entityTypeCode) {
this.entityTypeCode = entityTypeCode;
}
public EntityAddress.Builder getDefaultAddress() {
return defaultAddress;
}
public void setDefaultAddress(EntityAddress.Builder defaultAddress) {
this.defaultAddress = defaultAddress;
}
public EntityEmail.Builder getDefaultEmailAddress() {
return defaultEmailAddress;
}
public void setDefaultEmailAddress(EntityEmail.Builder defaultEmailAddress) {
this.defaultEmailAddress = defaultEmailAddress;
}
public EntityPhone.Builder getDefaultPhoneNumber() {
return defaultPhoneNumber;
}
public void setDefaultPhoneNumber(EntityPhone.Builder defaultPhoneNumber) {
this.defaultPhoneNumber = defaultPhoneNumber;
}
}
/**
* Defines some internal constants used on this class.
*
*/
static class Constants {
final static String ROOT_ELEMENT_NAME = "entityTypeDataDefault";
final static String TYPE_NAME = "EntityTypeDataDefaultType";
}
/**
* A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
*
*/
static class Elements {
final static String ENTITY_TYPE_CODE = "entityTypeCode";
final static String DEFAULT_ADDRESS = "defaultAddress";
final static String DEFAULT_EMAIL_ADDRESS = "defaultEmailAddress";
final static String DEFAULT_PHONE_NUMBER = "defaultPhoneNumber";
}
}
|
Shell
|
UTF-8
| 3,279 | 3.65625 | 4 |
[
"MIT"
] |
permissive
|
flei_docker_get_compose_project_name() {
flei_get_clean_project_name
}
flei_get_docker_compose_path() {
flei_require @flei/common-paths
flei_require @flei/get-flei-image
local FLEI_IMAGE
FLEI_IMAGE="$(flei_get_flei_image)"
local DOCKER_COMPOSE_PATH_BASE
DOCKER_COMPOSE_PATH_BASE="$(flei_resolve_path "${1}" "/docker/" "${BASH_SOURCE[1]}" ".docker-compose")"
local DOCKER_COMPOSE_PATH_YML="${DOCKER_COMPOSE_PATH_BASE}.yml"
local DOCKER_COMPOSE_PATH_JS="${DOCKER_COMPOSE_PATH_BASE}.js"
local DOCKER_COMPOSE_PATH_GENERATED="${DOCKER_COMPOSE_PATH_BASE}.js.yml"
if [ -f "${DOCKER_COMPOSE_PATH_JS}" ]; then
local PROJECT_ROOT
PROJECT_ROOT="$(flei_project_root)"
local PROJECT_ROOT_IN_DOCKER="/opt/flei-project-root"
local DOCKER_COMPOSE_RELATIVE_TO_PROJECT_ROOT="${DOCKER_COMPOSE_PATH_JS#"${PROJECT_ROOT}/"}"
local DOCKER_COMPOSE_PATH_IN_DOCKER="${PROJECT_ROOT_IN_DOCKER}/${DOCKER_COMPOSE_RELATIVE_TO_PROJECT_ROOT}"
docker run --rm -i -u "${RUN_UID}:${RUN_GID}" \
-v "${PROJECT_ROOT}:${PROJECT_ROOT_IN_DOCKER}" \
"${FLEI_IMAGE}" \
flei generate-docker-compose-config-from-js "${DOCKER_COMPOSE_PATH_IN_DOCKER}"
echo "${DOCKER_COMPOSE_PATH_GENERATED}"
exit 0
fi
echo "${DOCKER_COMPOSE_PATH_YML}"
}
flei_docker() {
flei_require @flei/resolve-path
flei_require @flei/common-paths
flei_require @flei/get-project-name
flei_require @flei/get-flei-image
local FLEI_IMAGE
FLEI_IMAGE="$(flei_get_flei_image)"
export RUN_UID
RUN_UID="$(id -u)"
export RUN_GID
RUN_GID="$(id -g)"
export FLEI_PROJECT_ROOT
FLEI_PROJECT_ROOT="$(flei_project_root)"
local DOCKER_COMPOSE_PATH
DOCKER_COMPOSE_PATH="$(flei_get_docker_compose_path "${@}")"
export COMPOSE_PROJECT_NAME
COMPOSE_PROJECT_NAME="$(flei_docker_get_compose_project_name)"
local DOCKER_COMPOSE_CONFIG
DOCKER_COMPOSE_CONFIG=$(docker-compose -f "${DOCKER_COMPOSE_PATH}" config)
local VOLUMES
VOLUMES="$(echo "${DOCKER_COMPOSE_CONFIG}" | docker run --rm -i -u "${RUN_UID}:${RUN_GID}" \
"${FLEI_IMAGE}" \
flei get-volumes-from-docker-compose-config)"
flei_docker_fix_volume_owner "${VOLUMES}"
set +o errexit
docker-compose -f "${DOCKER_COMPOSE_PATH}" run --rm "${@:2}"
DOCKER_EXIT_CODE=$?
set -o errexit
docker-compose -f "${DOCKER_COMPOSE_PATH}" down
if [ ${DOCKER_EXIT_CODE} -ne 0 ]; then
exit ${DOCKER_EXIT_CODE}
fi
}
function flei_docker_fix_volume_owner_generate_service_volumes() {
for var in "$@"; do
echo " - ${var}:/opt/flei-fix-volume-owner/${var}"
done
}
function flei_docker_fix_volume_owner_generate_volume_configuration() {
for var in "$@"; do
echo " ${var}:"
done
}
flei_docker_fix_volume_owner() {
flei_require @flei/get-flei-image
local FLEI_IMAGE
FLEI_IMAGE="$(flei_get_flei_image)"
DOCKER_COMPOSE="
services:
fix-volume-owner:
image: ${FLEI_IMAGE}
volumes:
$(flei_docker_fix_volume_owner_generate_service_volumes "${@}")
command: |
sh -c \"chown ${RUN_UID}:${RUN_GID} /opt/flei-fix-volume-owner/*\"
volumes:
$(flei_docker_fix_volume_owner_generate_volume_configuration "${@}")
"
echo "${DOCKER_COMPOSE}" | docker-compose -f - run --rm fix-volume-owner
echo "${DOCKER_COMPOSE}" | docker-compose -f - down
}
|
Python
|
UTF-8
| 745 | 2.5625 | 3 |
[] |
no_license
|
# preprocessor directives
import fresh_tomatoes
import media
# Movie objects
bladerunner = media.Movie(
"Blade Runner",
"https://www.youtube.com/watch?v=4lW0F1sccqk"
)
mad_max = media.Movie(
"Mad Max: Fury Road",
"https://www.youtube.com/watch?v=hEJnMQG9ev8"
)
point_break = media.Movie(
"Point Break",
"https://www.youtube.com/watch?v=0hd49bnStgU"
)
brazil = media.Movie(
"Brazil",
"https://www.youtube.com/watch?v=4Wh2b1eZFUM"
)
isteve = media.Movie(
"iSteve",
"https://www.youtube.com/watch?v=0FChm-Ayj7g"
)
# an array of Movie objects
movies = [bladerunner, point_break, mad_max, brazil, isteve]
# calling fresh_tomatoes() to create page
fresh_tomatoes.open_movies_page(movies)
|
Java
|
WINDOWS-1250
| 3,881 | 2.109375 | 2 |
[] |
no_license
|
package com.luxsoft.siipap.cxc.swing.cobranza;
import org.apache.log4j.Logger;
import com.luxsoft.siipap.cxc.catalogos.ComentarioDeRevisionForm;
import com.luxsoft.siipap.ventas.domain.VentaACredito;
import com.luxsoft.siipap.ventas.managers.VentasManager;
/**
* Soporte adicional para la funcionalidad de RevisionView
*
* @author Ruben Cancino
*
*/
public class RevisionSupport {
private Logger logger=Logger.getLogger(getClass());
private VentasManager manager;
public RevisionSupport(){
}
public void actualizarComentarios(final VentaACredito v){
final ComentarioDeRevisionForm form=new ComentarioDeRevisionForm(v);
form.open();
if(!form.hasBeenCanceled()){
getManager().actualizarVenta(v.getVenta());
getManager().refresh(v.getVenta());
}
}
/**
* Prepara una lista de notas de credito para descuento que se requieren para facturas en especifico para las
* cuales se autoriza su impresion para mandar a revision
*
* @param ventas
* @return
public void generarNotasPorAnticipado(final EventList<Venta> ventasTodas,final Date fecha){
final EventList<Venta> ventas=filtrar(ventasTodas);
final Comparator<NotasDeCreditoDet> c=GlazedLists.beanPropertyComparator(NotasDeCreditoDet.class, "clave");
final SortedList<NotasDeCreditoDet> dets=new SortedList<NotasDeCreditoDet>(new BasicEventList<NotasDeCreditoDet>(),c);
for(Venta v:ventas){
if(v.getCliente().getCredito().isNotaAnticipada()){
NotasDeCreditoDet det=NotasUtils.getNotaDet(v);
dets.add(det);
}
}
final GroupingList<NotasDeCreditoDet> grupos=new GroupingList<NotasDeCreditoDet>(dets,c);
final List<NotaDeCredito> res=new ArrayList<NotaDeCredito>();
for(int i=0;i<grupos.size();i++){
final List<NotasDeCreditoDet> partidas=grupos.get(i);
NotasUtils.ordenarPorFactura(partidas);
final List<NotaDeCredito> notas=NotasUtils.getNotasFromDetalles(partidas);
for(NotaDeCredito nota:notas){
NotasUtils.configurarParaDescuento(nota);
}
res.addAll(notas);
}
NotasUtils.aplicarProvision(res);
NotasUtils.actualizarFecha(res, fecha);
if(logger.isDebugEnabled()){
logger.debug("Notas generadas: "+res.size());
}
NotasPorAnticipado dialog=new NotasPorAnticipado(res);
dialog.open();
if(!dialog.hasBeenCanceled()){
salvarNotas(res);
MessageUtils.showMessage("Verifique que en el panel de control de windows la\n impresora seleccionada sea la correcta", "Impresin de Notas");
imprimirNotas(res);
}
}
public void salvarNotas(final List<NotaDeCredito> notas){
ServiceLocator.getNotasManager().salvarNotasCre(notas);
for(NotaDeCredito nota:notas){
for(NotasDeCreditoDet det:nota.getPartidas()){
//Actualizamos la provision de la venta
getManager().aplicarProvision(det.getFactura());
}
}
}
public void imprimirNotas(final List<NotaDeCredito> notas){
for(NotaDeCredito nota:notas){
final Map<String, Object> params=new HashMap<String, Object>();
params.put("NOTA_ID", nota.getId());
params.put("IMPORTE_LETRA", ImporteALetra.aLetra(nota.getTotalAsMoneda()));
ReportUtils.printReport("reportes/"+CXCReportes.NotaDeCredito.name()+".jasper"
, params, false);
}
}
private EventList<Venta> filtrar(final EventList<Venta> ventas){
final Matcher<Venta> matcher=new Matcher<Venta>(){
public boolean matches(Venta item) {
return ((item.getSaldo().doubleValue()>0) && (item.getProvision()!=null) && (!item.getProvision().isAplicado())
);
}
};
final FilterList<Venta> filtro=new FilterList<Venta>(ventas,matcher);
return filtro;
}
*/
public VentasManager getManager() {
return manager;
}
public void setManager(VentasManager manager) {
this.manager = manager;
}
}
|
C++
|
UTF-8
| 3,485 | 2.59375 | 3 |
[] |
no_license
|
#include "stdafx.h"
using namespace std;
using namespace nb;
int main()
{
PackageManager packageManager;
packageManager.initFromFolder( "./data/debug_packageManager" );
const std::list<Package>& pkgsByName = packageManager.getLoadedPackages();
const Package* newPackage = packageManager.getPackageByName( "NewPackage" );
const Package* testpackage = packageManager.getPackageByName( "Testpackage" );
const MetaFile* npm1 = packageManager.getMetaFileById( "NewPackage:mario1" );
const MetaFile* npm2 = packageManager.getMetaFileById( "NewPackage:mario2" );
const MetaFile* nptf = packageManager.getMetaFileById( "NewPackage:textfile" );
const MetaFile* npmt = packageManager.getMetaFileById( "NewPackage:textures:myTexture" );
const MetaFile* tpm1 = packageManager.getMetaFileById( "Testpackage:mario1" );
const MetaFile* tpm2 = packageManager.getMetaFileById( "Testpackage:mario2" );
const MetaFile* tpm3 = packageManager.getMetaFileById( "Testpackage:mario3" );
const MetaFile* tptf = packageManager.getMetaFileById( "Testpackage:textfile" );
//
cout << "-- Package names:" << endl;
cout << newPackage->getName() << endl;
cout << testpackage->getName() << endl;
//
const MetaFile* _npm1 = newPackage->getMetaFileById( "mario1" );
const MetaFile* _npm2 = newPackage->getMetaFileById( "mario2" );
const MetaFile* _nptf = newPackage->getMetaFileById( "textfile" );
const MetaFile* _npmt = newPackage->getMetaFileById( "textures:myTexture" );
const MetaFile* _tpm1 = testpackage->getMetaFileById( "mario1" );
const MetaFile* _tpm2 = testpackage->getMetaFileById( "mario2" );
const MetaFile* _tpm3 = testpackage->getMetaFileById( "mario3" );
const MetaFile* _tptf = testpackage->getMetaFileById( "textfile" );
cout << boolalpha;
cout << "-- Compare MetaFiles:" << endl;
cout << (npm1 == _npm1) << endl;
cout << (npm2 == _npm2) << endl;
cout << (nptf == _nptf) << endl;
cout << (npmt == _npmt) << endl;
cout << (tpm1 == _tpm1) << endl;
cout << (tpm2 == _tpm2) << endl;
cout << (tpm3 == _tpm3) << endl;
cout << (tptf == _tptf) << endl;
//
cout << "-- Local ID, Global ID, Connected Filepath:" << endl;
cout << npm1->getId() << endl;
cout << newPackage->convertLocalToGlobalId( npm1->getId() ) << endl;
cout << npm1->getConnectedFilePath() << endl;
cout << npm2->getId() << endl;
cout << newPackage->convertLocalToGlobalId( npm2->getId() ) << endl;
cout << npm2->getConnectedFilePath() << endl;
cout << nptf->getId() << endl;
cout << newPackage->convertLocalToGlobalId( nptf->getId() ) << endl;
cout << nptf->getConnectedFilePath() << endl;
cout << npmt->getId() << endl;
cout << newPackage->convertLocalToGlobalId( npmt->getId() ) << endl;
cout << npmt->getConnectedFilePath() << endl;
cout << tpm1->getId() << endl;
cout << testpackage->convertLocalToGlobalId( tpm1->getId() ) << endl;
cout << tpm1->getConnectedFilePath() << endl;
cout << tpm2->getId() << endl;
cout << testpackage->convertLocalToGlobalId( tpm2->getId() ) << endl;
cout << tpm2->getConnectedFilePath() << endl;
cout << tpm3->getId() << endl;
cout << testpackage->convertLocalToGlobalId( tpm3->getId() ) << endl;
cout << tpm3->getConnectedFilePath() << endl;
cout << tptf->getId() << endl;
cout << testpackage->convertLocalToGlobalId( tptf->getId() ) << endl;
cout << tptf->getConnectedFilePath() << endl;
cout << "-----------------" << endl;
cout << "NewBitPackageManagerTest complete" << endl;
system( "pause" );
packageManager.save();
}
|
PHP
|
UTF-8
| 2,210 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: Chelsea
* Date: 3/1/2015
* Time: 3:44 PM
*/
namespace App\Impl\Reponsitory\Product;
use App\Http\Requests\ProductFormRequest;
use App\Impl\Service\Cache\CacheInteface;
use App\Products;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class EloquentProducts implements ProductInterface {
protected $products;
protected $cache;
public function __construct(Products $products, CacheInteface $cache){
$this->products = $products;
$this->cache = $cache;
}
public function all()
{
$key = md5('products');
if($this->cache->has($key)) {
return $this->cache->get($key);
}
$this->cache->put($key, $this->products->all(), 10);
return $this->products->all();
}
public function delete($id)
{
$this->products->destroy($id);
}
public function save(ProductFormRequest $request)
{
if(!$request->has('id')) {
$products = new Products();
} else {
$products = $this->products->findOrFail($request->input('id'));
}
$products->product_name = $request->get('product_name');
$products->description = $request->get('description');
$image = $request->file('img');
$fileName = $image->getClientOriginalName();
$path = public_path('img/'.$fileName);
//Image::make($image->getRealPath())->resize(200, 200)->save($path);
Image::make($image->getRealPath())->resize(200, 200)->save($path);
$products->img = 'img/'.$fileName;
$products->quanlity = $request->get('quanlity');
$products->price = $request->get('price');
$this->cache->deleteCaCheFile(md5('products'));
return $products->save();
}
public function find($id)
{
$key = md5('findProduct');
if($this->cache->has($key)) {
return $this->cache->get($key);
}
$products = $this->products->findOrFail($id);
$this->cache->put($key, $products, 10);
return $products;
}
}
|
Python
|
UTF-8
| 729 | 3.90625 | 4 |
[] |
no_license
|
class Parent:
parent_attr = 100
def __init__(self):
print("่ฐ็จ็ถ็ฑปๆ้ ๅฝๆฐ")
def parent_method(self):
print("่ฐ็จ็ถ็ฑปๆนๆณ")
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("็ถ็ฑปๅฑๆง :", Parent.parentAttr)
class Child(Parent):
def __init__(self):
print("่ฐ็จๅญ็ฑปๆ้ ๅฝๆฐ")
def child_method(self):
print("่ฐ็จๅญ็ฑปๆนๆณ")
c = Child() # ๅฎไพๅๅญ็ฑป
c.child_method() # ่ฐ็จๅญ็ฑป็ๆนๆณ
c.parent_method() # ่ฐ็จ็ถ็ฑปๆนๆณ
c.setAttr(200) # ๅๆฌก่ฐ็จ็ถ็ฑป็ๆนๆณ - ่ฎพ็ฝฎๅฑๆงๅผ
c.getAttr() # ๅๆฌก่ฐ็จ็ถ็ฑป็ๆนๆณ - ่ทๅๅฑๆงๅผ
|
C#
|
UTF-8
| 19,099 | 2.578125 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.ObjectModel;
namespace StokerStocks
{
static class BancoDados
{
/// <summary>
/// Carrega os ativos da carteira
/// </summary>
/// <returns></returns>
public static ObservableCollection<Ativo> CarregarAtivos()
{
ObservableCollection<Ativo> temp = new ObservableCollection<Ativo>();
return temp;
}
public static ObservableCollection<Ordem> CarregarOrdens(string Ticket)
{
return new ObservableCollection<Ordem>()
{
new Ordem(){ Date = new DateTime(2016, 09, 12), Operaรงรฃo = Operaรงรตes.Compra, Quantidade = 27, ValorUnitรกrio = 55.5m },
new Ordem(){ Date = new DateTime(2016, 10, 04), Operaรงรฃo = Operaรงรตes.Compra, Quantidade = 10, ValorUnitรกrio = 57.6m },
new Ordem(){ Date = new DateTime(2016, 10, 19), Operaรงรฃo = Operaรงรตes.Compra, Quantidade = 3, ValorUnitรกrio = 61.3m },
new Ordem(){ Date = new DateTime(2017, 02, 06), Operaรงรฃo = Operaรงรตes.Venda, Quantidade = 2, ValorUnitรกrio = 80.5m },
new Ordem(){ Date = new DateTime(2017, 03, 08), Operaรงรฃo = Operaรงรตes.Compra, Quantidade = 10, ValorUnitรกrio = 81.1m },
new Ordem(){ Date = new DateTime(2017, 03, 15), Operaรงรฃo = Operaรงรตes.Venda, Quantidade = 38, ValorUnitรกrio = 81.5m },
new Ordem(){ Date = new DateTime(2019, 06, 25), Operaรงรฃo = Operaรงรตes.Venda, Quantidade = 10, ValorUnitรกrio = 88.9m },
};
}
/// <summary>
/// Carrega o historico de cotaรงรตes para um periodo de tempo limitado
/// </summary>
/// <param name="Inicio"></param>
/// <param name="Final"></param>
/// <returns></returns>
public static ObservableCollection<Cotacao> CarregarCotacoes(DateTime Inicio, DateTime Final)
{
ObservableCollection<Cotacao> DB = new ObservableCollection<Cotacao>()
{
new Cotacao() { Data = new DateTime(2019,7,19), Abertura=88.90m, Maxima=89.00m, Minima=87.07m, Fechamento=87.18m },
new Cotacao() { Data = new DateTime(2019,6,28), Abertura=88.97m, Maxima=88.97m, Minima=86.30m, Fechamento=88.03m },
new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m },
new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m },
new Cotacao() { Data = new DateTime(2019,4,30), Abertura=85.95m, Maxima=88.9m, Minima=84m, Fechamento=88.2m },
new Cotacao() { Data = new DateTime(2019,3,29), Abertura=80.89m, Maxima=88m, Minima=79.5m, Fechamento=86m },
new Cotacao() { Data = new DateTime(2019,2,128), Abertura=80.94m, Maxima=82.79m, Minima=78.75m, Fechamento=81m },
new Cotacao() { Data = new DateTime(2019,1,31), Abertura=75.24m, Maxima=81.99m, Minima=74.8m, Fechamento=80.5m },
new Cotacao() { Data = new DateTime(2018,12,28), Abertura=74.79m, Maxima=77.99m, Minima=72.26m, Fechamento=75.26m },
new Cotacao() { Data = new DateTime(2018,11,30), Abertura=73.9m, Maxima=75.2m, Minima=72.02m, Fechamento=74.95m },
new Cotacao() { Data = new DateTime(2018,10,31), Abertura=72.75m, Maxima=75m, Minima=70m, Fechamento=74.86m },
new Cotacao() { Data = new DateTime(2018,9,28), Abertura=72.48m, Maxima=73.27m, Minima=71.16m, Fechamento=72.75m },
new Cotacao() { Data = new DateTime(2018,8,31), Abertura=74m, Maxima=74.59m, Minima=71m, Fechamento=72.71m },
new Cotacao() { Data = new DateTime(2018,7,31), Abertura=72.2m, Maxima=74.95m, Minima=70.99m, Fechamento=74.39m },
new Cotacao() { Data = new DateTime(2018,6,29), Abertura=71.99m, Maxima=72.89m, Minima=69.13m, Fechamento=72.2m },
new Cotacao() { Data = new DateTime(2018,5,30), Abertura=79.2m, Maxima=79.2m, Minima=67.16m, Fechamento=73m },
new Cotacao() { Data = new DateTime(2018,4,30), Abertura=77.6m, Maxima=80m, Minima=76.81m, Fechamento=79m },
new Cotacao() { Data = new DateTime(2018,3,29), Abertura=77.6m, Maxima=80m, Minima=74.4m, Fechamento=79.95m },
new Cotacao() { Data = new DateTime(2018,2,28), Abertura=79m, Maxima=80.2m, Minima=74.5m, Fechamento=77.5m },
new Cotacao() { Data = new DateTime(2018,1,31), Abertura=74.51m, Maxima=80m, Minima=74.05m, Fechamento=79.05m },
new Cotacao() { Data = new DateTime(2017,12,29), Abertura=74.4m, Maxima=75m, Minima=72.03m, Fechamento=74.37m },
new Cotacao() { Data = new DateTime(2017,11,30), Abertura=74.49m, Maxima=75.74m, Minima=71.2m, Fechamento=75m },
new Cotacao() { Data = new DateTime(2017,10,31), Abertura=73.3m, Maxima=76m, Minima=71.2m, Fechamento=74.5m },
new Cotacao() { Data = new DateTime(2017,9,29), Abertura=72.59m, Maxima=73.4m, Minima=70.11m, Fechamento=73.36m },
new Cotacao() { Data = new DateTime(2017,8,31), Abertura=68.7m, Maxima=73m, Minima=68.7m, Fechamento=72.6m },
new Cotacao() { Data = new DateTime(2017,7,31), Abertura=70.11m, Maxima=73.48m, Minima=68.9m, Fechamento=68.9m },
new Cotacao() { Data = new DateTime(2017,6,30), Abertura=70m, Maxima=74.85m, Minima=68.5m, Fechamento=72m },
new Cotacao() { Data = new DateTime(2017,5,31), Abertura=71.77m, Maxima=74m, Minima=67m, Fechamento=71.35m },
new Cotacao() { Data = new DateTime(2017,4,28), Abertura=72.5m, Maxima=74.99m, Minima=67m, Fechamento=72.3m },
new Cotacao() { Data = new DateTime(2017,3,31), Abertura=63.67m, Maxima=75m, Minima=63.65m, Fechamento=71.5m },
new Cotacao() { Data = new DateTime(2017,2,24), Abertura=63m, Maxima=64.95m, Minima=62.5m, Fechamento=64m },
new Cotacao() { Data = new DateTime(2017,1,31), Abertura=60.26m, Maxima=63.63m, Minima=58.36m, Fechamento=63.4m },
new Cotacao() { Data = new DateTime(2016,12,29), Abertura=58m, Maxima=60.8m, Minima=55.3m, Fechamento=60.8m },
new Cotacao() { Data = new DateTime(2016,11,30), Abertura=61m, Maxima=62m, Minima=53.01m, Fechamento=58m },
new Cotacao() { Data = new DateTime(2016,10,31), Abertura=59m, Maxima=63.95m, Minima=55.51m, Fechamento=61m },
new Cotacao() { Data = new DateTime(2016,9,30), Abertura=60m, Maxima=60m, Minima=54.2m, Fechamento=59.85m },
new Cotacao() { Data = new DateTime(2016,8,31), Abertura=74.99m, Maxima=80m, Minima=57.3m, Fechamento=59.12m },
new Cotacao() { Data = new DateTime(2016,7,29), Abertura=69.69m, Maxima=79.49m, Minima=68m, Fechamento=75.8m },
new Cotacao() { Data = new DateTime(2016,6,30), Abertura=69.75m, Maxima=69.99m, Minima=67.8m, Fechamento=69.7m },
new Cotacao() { Data = new DateTime(2016,5,31), Abertura=67m, Maxima=69.99m, Minima=64m, Fechamento=69.19m },
new Cotacao() { Data = new DateTime(2016,4,29), Abertura=68.48m, Maxima=69m, Minima=65.1m, Fechamento=68.4m },
new Cotacao() { Data = new DateTime(2016,3,31), Abertura=54.02m, Maxima=69.89m, Minima=53.1m, Fechamento=67.99m },
new Cotacao() { Data = new DateTime(2016,2,29), Abertura=56.01m, Maxima=56.49m, Minima=51.62m, Fechamento=55.33m },
new Cotacao() { Data = new DateTime(2016,1,29), Abertura=60.42m, Maxima=60.42m, Minima=55m, Fechamento=56.5m },
new Cotacao() { Data = new DateTime(2015,12,30), Abertura=64.49m, Maxima=64.49m, Minima=58.57m, Fechamento=61.3m },
new Cotacao() { Data = new DateTime(2015,11,30), Abertura=64.98m, Maxima=64.98m, Minima=62m, Fechamento=64.5m },
new Cotacao() { Data = new DateTime(2015,10,30), Abertura=63.96m, Maxima=65m, Minima=61.61m, Fechamento=65m },
new Cotacao() { Data = new DateTime(2015,9,30), Abertura=68m, Maxima=68.45m, Minima=62.5m, Fechamento=64.88m },
new Cotacao() { Data = new DateTime(2015,8,31), Abertura=70.11m, Maxima=70.11m, Minima=65.22m, Fechamento=69m },
new Cotacao() { Data = new DateTime(2015,7,31), Abertura=70.34m, Maxima=70.5m, Minima=69.31m, Fechamento=70.5m },
new Cotacao() { Data = new DateTime(2015,6,30), Abertura=70.25m, Maxima=71m, Minima=69.13m, Fechamento=70.7m },
new Cotacao() { Data = new DateTime(2015,5,29), Abertura=70.1m, Maxima=71.97m, Minima=68m, Fechamento=70.69m },
new Cotacao() { Data = new DateTime(2015,4,30), Abertura=70.75m, Maxima=72.49m, Minima=68.83m, Fechamento=72.29m },
new Cotacao() { Data = new DateTime(2015,3,31), Abertura=70.53m, Maxima=71.48m, Minima=68.01m, Fechamento=70m },
new Cotacao() { Data = new DateTime(2015,2,27), Abertura=73.44m, Maxima=73.44m, Minima=71m, Fechamento=71m },
new Cotacao() { Data = new DateTime(2015,1,30), Abertura=74.98m, Maxima=74.99m, Minima=71m, Fechamento=73.47m },
new Cotacao() { Data = new DateTime(2014,12,30), Abertura=70.99m, Maxima=72.5m, Minima=68.68m, Fechamento=72.48m },
new Cotacao() { Data = new DateTime(2014,11,28), Abertura=73m, Maxima=73.48m, Minima=67.25m, Fechamento=71.4m },
new Cotacao() { Data = new DateTime(2014,10,31), Abertura=71.8m, Maxima=74.11m, Minima=67.05m, Fechamento=73.19m },
new Cotacao() { Data = new DateTime(2014,9,30), Abertura=73.11m, Maxima=74.78m, Minima=70.01m, Fechamento=70.02m },
};
ObservableCollection<Cotacao> Resultado = new ObservableCollection<Cotacao>();
DateTime FinalMes = new DateTime(Final.Year, Final.Month, DateTime.DaysInMonth(Final.Year, Final.Month), 23, 59, 59);
DateTime InicioMes = new DateTime(Inicio.Year, Inicio.Month, 1, 0, 0, 0);
foreach (Cotacao item in DB)
{
if ((item.Data > InicioMes) && (item.Data <= FinalMes))
{
Resultado.Add(item);
}
}
return Resultado;
}
/// <summary>
/// Carrega o historico de cotaรงรตes de uma data de inicio atรฉ hoje
/// </summary>
/// <param name="Inicio"></param>
/// <returns></returns>
public static ObservableCollection<Cotacao> CarregarCotacoes(DateTime Inicio)
{
ObservableCollection<Cotacao> DB = new ObservableCollection<Cotacao>()
{
new Cotacao() { Data = new DateTime(2019,7,19), Abertura=88.90m, Maxima=89.00m, Minima=87.07m, Fechamento=87.18m },
new Cotacao() { Data = new DateTime(2019,6,28), Abertura=88.97m, Maxima=88.97m, Minima=86.30m, Fechamento=88.03m },
new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m },
new Cotacao() { Data = new DateTime(2019,5,31), Abertura=88.2m, Maxima=90m, Minima=86m, Fechamento=89m },
new Cotacao() { Data = new DateTime(2019,4,30), Abertura=85.95m, Maxima=88.9m, Minima=84m, Fechamento=88.2m },
new Cotacao() { Data = new DateTime(2019,3,29), Abertura=80.89m, Maxima=88m, Minima=79.5m, Fechamento=86m },
new Cotacao() { Data = new DateTime(2019,2,28), Abertura=80.94m, Maxima=82.79m, Minima=78.75m, Fechamento=81m },
new Cotacao() { Data = new DateTime(2019,1,31), Abertura=75.24m, Maxima=81.99m, Minima=74.8m, Fechamento=80.5m },
new Cotacao() { Data = new DateTime(2018,12,28), Abertura=74.79m, Maxima=77.99m, Minima=72.26m, Fechamento=75.26m },
new Cotacao() { Data = new DateTime(2018,11,30), Abertura=73.9m, Maxima=75.2m, Minima=72.02m, Fechamento=74.95m },
new Cotacao() { Data = new DateTime(2018,10,31), Abertura=72.75m, Maxima=75m, Minima=70m, Fechamento=74.86m },
new Cotacao() { Data = new DateTime(2018,9,28), Abertura=72.48m, Maxima=73.27m, Minima=71.16m, Fechamento=72.75m },
new Cotacao() { Data = new DateTime(2018,8,31), Abertura=74m, Maxima=74.59m, Minima=71m, Fechamento=72.71m },
new Cotacao() { Data = new DateTime(2018,7,31), Abertura=72.2m, Maxima=74.95m, Minima=70.99m, Fechamento=74.39m },
new Cotacao() { Data = new DateTime(2018,6,29), Abertura=71.99m, Maxima=72.89m, Minima=69.13m, Fechamento=72.2m },
new Cotacao() { Data = new DateTime(2018,5,30), Abertura=79.2m, Maxima=79.2m, Minima=67.16m, Fechamento=73m },
new Cotacao() { Data = new DateTime(2018,4,30), Abertura=77.6m, Maxima=80m, Minima=76.81m, Fechamento=79m },
new Cotacao() { Data = new DateTime(2018,3,29), Abertura=77.6m, Maxima=80m, Minima=74.4m, Fechamento=79.95m },
new Cotacao() { Data = new DateTime(2018,2,28), Abertura=79m, Maxima=80.2m, Minima=74.5m, Fechamento=77.5m },
new Cotacao() { Data = new DateTime(2018,1,31), Abertura=74.51m, Maxima=80m, Minima=74.05m, Fechamento=79.05m },
new Cotacao() { Data = new DateTime(2017,12,29), Abertura=74.4m, Maxima=75m, Minima=72.03m, Fechamento=74.37m },
new Cotacao() { Data = new DateTime(2017,11,30), Abertura=74.49m, Maxima=75.74m, Minima=71.2m, Fechamento=75m },
new Cotacao() { Data = new DateTime(2017,10,31), Abertura=73.3m, Maxima=76m, Minima=71.2m, Fechamento=74.5m },
new Cotacao() { Data = new DateTime(2017,9,29), Abertura=72.59m, Maxima=73.4m, Minima=70.11m, Fechamento=73.36m },
new Cotacao() { Data = new DateTime(2017,8,31), Abertura=68.7m, Maxima=73m, Minima=68.7m, Fechamento=72.6m },
new Cotacao() { Data = new DateTime(2017,7,31), Abertura=70.11m, Maxima=73.48m, Minima=68.9m, Fechamento=68.9m },
new Cotacao() { Data = new DateTime(2017,6,30), Abertura=70m, Maxima=74.85m, Minima=68.5m, Fechamento=72m },
new Cotacao() { Data = new DateTime(2017,5,31), Abertura=71.77m, Maxima=74m, Minima=67m, Fechamento=71.35m },
new Cotacao() { Data = new DateTime(2017,4,28), Abertura=72.5m, Maxima=74.99m, Minima=67m, Fechamento=72.3m },
new Cotacao() { Data = new DateTime(2017,3,31), Abertura=63.67m, Maxima=75m, Minima=63.65m, Fechamento=71.5m },
new Cotacao() { Data = new DateTime(2017,2,24), Abertura=63m, Maxima=64.95m, Minima=62.5m, Fechamento=64m },
new Cotacao() { Data = new DateTime(2017,1,31), Abertura=60.26m, Maxima=63.63m, Minima=58.36m, Fechamento=63.4m },
new Cotacao() { Data = new DateTime(2016,12,29), Abertura=58m, Maxima=60.8m, Minima=55.3m, Fechamento=60.8m },
new Cotacao() { Data = new DateTime(2016,11,30), Abertura=61m, Maxima=62m, Minima=53.01m, Fechamento=58m },
new Cotacao() { Data = new DateTime(2016,10,31), Abertura=59m, Maxima=63.95m, Minima=55.51m, Fechamento=61m },
new Cotacao() { Data = new DateTime(2016,9,30), Abertura=60m, Maxima=60m, Minima=54.2m, Fechamento=59.85m },
new Cotacao() { Data = new DateTime(2016,8,31), Abertura=74.99m, Maxima=80m, Minima=57.3m, Fechamento=59.12m },
new Cotacao() { Data = new DateTime(2016,7,29), Abertura=69.69m, Maxima=79.49m, Minima=68m, Fechamento=75.8m },
new Cotacao() { Data = new DateTime(2016,6,30), Abertura=69.75m, Maxima=69.99m, Minima=67.8m, Fechamento=69.7m },
new Cotacao() { Data = new DateTime(2016,5,31), Abertura=67m, Maxima=69.99m, Minima=64m, Fechamento=69.19m },
new Cotacao() { Data = new DateTime(2016,4,29), Abertura=68.48m, Maxima=69m, Minima=65.1m, Fechamento=68.4m },
new Cotacao() { Data = new DateTime(2016,3,31), Abertura=54.02m, Maxima=69.89m, Minima=53.1m, Fechamento=67.99m },
new Cotacao() { Data = new DateTime(2016,2,29), Abertura=56.01m, Maxima=56.49m, Minima=51.62m, Fechamento=55.33m },
new Cotacao() { Data = new DateTime(2016,1,29), Abertura=60.42m, Maxima=60.42m, Minima=55m, Fechamento=56.5m },
new Cotacao() { Data = new DateTime(2015,12,30), Abertura=64.49m, Maxima=64.49m, Minima=58.57m, Fechamento=61.3m },
new Cotacao() { Data = new DateTime(2015,11,30), Abertura=64.98m, Maxima=64.98m, Minima=62m, Fechamento=64.5m },
new Cotacao() { Data = new DateTime(2015,10,30), Abertura=63.96m, Maxima=65m, Minima=61.61m, Fechamento=65m },
new Cotacao() { Data = new DateTime(2015,9,30), Abertura=68m, Maxima=68.45m, Minima=62.5m, Fechamento=64.88m },
new Cotacao() { Data = new DateTime(2015,8,31), Abertura=70.11m, Maxima=70.11m, Minima=65.22m, Fechamento=69m },
new Cotacao() { Data = new DateTime(2015,7,31), Abertura=70.34m, Maxima=70.5m, Minima=69.31m, Fechamento=70.5m },
new Cotacao() { Data = new DateTime(2015,6,30), Abertura=70.25m, Maxima=71m, Minima=69.13m, Fechamento=70.7m },
new Cotacao() { Data = new DateTime(2015,5,29), Abertura=70.1m, Maxima=71.97m, Minima=68m, Fechamento=70.69m },
new Cotacao() { Data = new DateTime(2015,4,30), Abertura=70.75m, Maxima=72.49m, Minima=68.83m, Fechamento=72.29m },
new Cotacao() { Data = new DateTime(2015,3,31), Abertura=70.53m, Maxima=71.48m, Minima=68.01m, Fechamento=70m },
new Cotacao() { Data = new DateTime(2015,2,27), Abertura=73.44m, Maxima=73.44m, Minima=71m, Fechamento=71m },
new Cotacao() { Data = new DateTime(2015,1,30), Abertura=74.98m, Maxima=74.99m, Minima=71m, Fechamento=73.47m },
new Cotacao() { Data = new DateTime(2014,12,30), Abertura=70.99m, Maxima=72.5m, Minima=68.68m, Fechamento=72.48m },
new Cotacao() { Data = new DateTime(2014,11,28), Abertura=73m, Maxima=73.48m, Minima=67.25m, Fechamento=71.4m },
new Cotacao() { Data = new DateTime(2014,10,31), Abertura=71.8m, Maxima=74.11m, Minima=67.05m, Fechamento=73.19m },
new Cotacao() { Data = new DateTime(2014,9,30), Abertura=73.11m, Maxima=74.78m, Minima=70.01m, Fechamento=70.02m },
};
ObservableCollection<Cotacao> Resultado = new ObservableCollection<Cotacao>();
DateTime FinalMes = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month), 23, 59, 59);
DateTime InicioMes = new DateTime(Inicio.Year, Inicio.Month, 1, 0, 0, 0);
foreach (Cotacao item in DB)
{
if ((item.Data > InicioMes) && (item.Data <= FinalMes))
{
Resultado.Add(item);
}
}
return Resultado;
}
}
}
|
Java
|
UTF-8
| 3,191 | 2.84375 | 3 |
[] |
no_license
|
package com.mq.demo.rpc;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.AMQP.BasicProperties;
/**
* Created by hzzhaolong on 2016/2/3.
*/
public class RPCServer {
private static final String RPC_REQUEST_QUEUE_NAME = "hzzhaolong_rpc_queue";
private static final int QUEUE_PORT = 5672;
private static final String IP = "xxx";
private static final String USERNAME = "admin";
private static final String PASSWORD = "d97aNp";
private static int fib(int n) {
if (n ==0) return 0;
if (n == 1) return 1;
return fib(n-1) + fib(n-2);
}
public static void main(String[] argv) {
Connection connection = null;
Channel channel = null;
try {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(IP);
factory.setUsername(USERNAME);
factory.setPassword(PASSWORD);
factory.setPort(QUEUE_PORT);
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(RPC_REQUEST_QUEUE_NAME, false, false, false, null);
// ่ฎพ็ฝฎๆฏไธชๆถ่ดน่ฟๆๅคๅค็ไธไธชไปปๅก
channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(RPC_REQUEST_QUEUE_NAME, false, consumer);
System.out.println(" [x] Awaiting RPC requests");
while (true) {
String response = null;
// Main application-side API: wait for the next message delivery and return it.
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
BasicProperties requestProps = delivery.getProperties();
// ็ธๅบๅช่ฆๆๅฎ่ฏทๆฑIDๅณๅฏ
BasicProperties replyProps = new BasicProperties
.Builder()
.correlationId(requestProps.getCorrelationId())
.build();
try {
String message = new String(delivery.getBody(),"UTF-8");
int n = Integer.parseInt(message);
System.out.println(" [.] fib(" + message + ")");
response = "" + fib(n);
}
catch (Exception e){
System.out.println(" [.] " + e.toString());
response = "";
}
finally {
// ๅๅ
ฅresponse้ๅ
channel.basicPublish( "", requestProps.getReplyTo(), replyProps, response.getBytes("UTF-8"));
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (connection != null) {
try {
connection.close();
}
catch (Exception ignore) {}
}
}
}
}
|
JavaScript
|
UTF-8
| 893 | 2.765625 | 3 |
[] |
no_license
|
import axios from "axios";
export const fetchOrganisationsByQueryService = async (qwery = "") => {
try {
const response = await axios(
`https://api.github.com/search/users?q=type:org+${qwery}`
);
const { items } = response.data;
return items;
} catch (error) {
return [];
}
};
export const fetchOrganisationMembersByNameService = async name => {
try {
const response = await axios(`https://api.github.com/orgs/${name}/members`);
return response.data;
} catch (error) {
return [];
}
};
export const fetchOrganisationByNameService = async name => {
try {
const response = await axios(`https://api.github.com/orgs/${name}`);
const organisationData = response.data;
organisationData.members = await fetchOrganisationMembersByNameService(
name
);
return organisationData;
} catch (error) {
return null;
}
};
|
Markdown
|
UTF-8
| 9,621 | 2.828125 | 3 |
[] |
no_license
|
# swagger_client.InvoiceResourceApi
All URIs are relative to *https://localhost:8080*
Method | HTTP request | Description
------------- | ------------- | -------------
[**create_invoice_using_post**](InvoiceResourceApi.md#create_invoice_using_post) | **POST** /api/invoices | createInvoice
[**delete_invoice_using_delete**](InvoiceResourceApi.md#delete_invoice_using_delete) | **DELETE** /api/invoices/{id} | deleteInvoice
[**get_all_invoices_using_get**](InvoiceResourceApi.md#get_all_invoices_using_get) | **GET** /api/invoices | getAllInvoices
[**get_invoice_by_subscriber_using_get**](InvoiceResourceApi.md#get_invoice_by_subscriber_using_get) | **GET** /api/invoices/subscriber/{subscriberSecureId} | getInvoiceBySubscriber
[**get_invoice_using_get**](InvoiceResourceApi.md#get_invoice_using_get) | **GET** /api/invoices/{id} | getInvoice
[**update_invoice_using_put**](InvoiceResourceApi.md#update_invoice_using_put) | **PUT** /api/invoices | updateInvoice
# **create_invoice_using_post**
> Invoice create_invoice_using_post(invoice)
createInvoice
### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: apiKey
configuration = swagger_client.Configuration()
configuration.api_key['Authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration))
invoice = swagger_client.Invoice() # Invoice | invoice
try:
# createInvoice
api_response = api_instance.create_invoice_using_post(invoice)
pprint(api_response)
except ApiException as e:
print("Exception when calling InvoiceResourceApi->create_invoice_using_post: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoice** | [**Invoice**](Invoice.md)| invoice |
### Return type
[**Invoice**](Invoice.md)
### Authorization
[apiKey](../README.md#apiKey)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **delete_invoice_using_delete**
> delete_invoice_using_delete(id)
deleteInvoice
### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: apiKey
configuration = swagger_client.Configuration()
configuration.api_key['Authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration))
id = 789 # int | id
try:
# deleteInvoice
api_instance.delete_invoice_using_delete(id)
except ApiException as e:
print("Exception when calling InvoiceResourceApi->delete_invoice_using_delete: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **int**| id |
### Return type
void (empty response body)
### Authorization
[apiKey](../README.md#apiKey)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_all_invoices_using_get**
> list[Invoice] get_all_invoices_using_get()
getAllInvoices
### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: apiKey
configuration = swagger_client.Configuration()
configuration.api_key['Authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration))
try:
# getAllInvoices
api_response = api_instance.get_all_invoices_using_get()
pprint(api_response)
except ApiException as e:
print("Exception when calling InvoiceResourceApi->get_all_invoices_using_get: %s\n" % e)
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**list[Invoice]**](Invoice.md)
### Authorization
[apiKey](../README.md#apiKey)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_invoice_by_subscriber_using_get**
> list[Invoice] get_invoice_by_subscriber_using_get(subscriber_secure_id)
getInvoiceBySubscriber
### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: apiKey
configuration = swagger_client.Configuration()
configuration.api_key['Authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration))
subscriber_secure_id = 'subscriber_secure_id_example' # str | subscriberSecureId
try:
# getInvoiceBySubscriber
api_response = api_instance.get_invoice_by_subscriber_using_get(subscriber_secure_id)
pprint(api_response)
except ApiException as e:
print("Exception when calling InvoiceResourceApi->get_invoice_by_subscriber_using_get: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriber_secure_id** | **str**| subscriberSecureId |
### Return type
[**list[Invoice]**](Invoice.md)
### Authorization
[apiKey](../README.md#apiKey)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_invoice_using_get**
> Invoice get_invoice_using_get(id)
getInvoice
### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: apiKey
configuration = swagger_client.Configuration()
configuration.api_key['Authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration))
id = 789 # int | id
try:
# getInvoice
api_response = api_instance.get_invoice_using_get(id)
pprint(api_response)
except ApiException as e:
print("Exception when calling InvoiceResourceApi->get_invoice_using_get: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**id** | **int**| id |
### Return type
[**Invoice**](Invoice.md)
### Authorization
[apiKey](../README.md#apiKey)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **update_invoice_using_put**
> Invoice update_invoice_using_put(invoice)
updateInvoice
### Example
```python
from __future__ import print_function
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: apiKey
configuration = swagger_client.Configuration()
configuration.api_key['Authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instance = swagger_client.InvoiceResourceApi(swagger_client.ApiClient(configuration))
invoice = swagger_client.Invoice() # Invoice | invoice
try:
# updateInvoice
api_response = api_instance.update_invoice_using_put(invoice)
pprint(api_response)
except ApiException as e:
print("Exception when calling InvoiceResourceApi->update_invoice_using_put: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**invoice** | [**Invoice**](Invoice.md)| invoice |
### Return type
[**Invoice**](Invoice.md)
### Authorization
[apiKey](../README.md#apiKey)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: */*
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
|
PHP
|
UTF-8
| 3,442 | 2.53125 | 3 |
[] |
no_license
|
<?php
/**
* Copyright. "NewGen" investment engine. All rights reserved.
* Any questions? Please, visit https://newgen.company
*/
namespace App\Console\Commands\Automatic;
use App\Http\Controllers\Admin\WithdrawalRequestsController;
use App\Models\Currency;
use App\Models\PaymentSystem;
use App\Models\Transaction;
use App\Models\TransactionType;
use App\Models\Wallet;
use Illuminate\Console\Command;
/**
* Class ProcessInstantPaymentsCommand
* @package App\Console\Commands\Automatic
*/
class ProcessInstantPaymentsCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'process:instant_payments';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Process customers instant payments.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* @throws \Exception
*/
public function handle()
{
/** @var TransactionType $transactionWithdrawType */
$transactionWithdrawType = TransactionType::getByName('withdraw');
/** @var Transaction $orders */
$orders = Transaction::where('type_id', $transactionWithdrawType->id)
->where('approved', 0)
->get();
$messages = [];
$this->info('Found '.$orders->count().' orders.');
$this->line('---');
/** @var Transaction $order */
foreach ($orders as $order) {
$this->info('Start processing withdraw order with ID '.$order->id.' and amount '.$order->amount);
/** @var Wallet $wallet */
$wallet = $order->wallet()->first();
/** @var PaymentSystem $paymentSystem */
$paymentSystem = $wallet->paymentSystem()->first();
/** @var Currency $currency */
$currency = $wallet->currency()->first();
if (null == $wallet || null == $paymentSystem) {
continue;
}
if (null === $limits = $paymentSystem->instant_limit) {
$this->info('Limits is not set up..');
return;
}
$decodedLimits = @json_decode($limits, true);
if (!isset($decodedLimits[$currency->code])) {
$this->info('Limit for this currency '.$currency->code.' not found.');
return;
}
$limit = (float) $decodedLimits[$currency->code];
if ($limit <= 0) {
$this->info('Skip. Payment system instant limit is 0.');
continue;
}
if ($order->amount > $limit) {
$this->info('Skip. Order amount '.$order->amount.' and payment system limit '.$limit);
continue;
}
try {
$message = WithdrawalRequestsController::approve($order->id, true);
} catch (\Exception $e) {
$message = $e->getMessage();
}
$messages[] = $message;
}
if (count($messages) == 0) {
return;
}
$msg = 'Processed '.count($messages).' instant payments. Results:\n'.implode('<hr>', $messages);
$this->info($msg);
\Log::info($msg);
}
}
|
C#
|
UTF-8
| 289 | 2.953125 | 3 |
[] |
no_license
|
๏ปฟusing System;
namespace RocketEquation
{
public static class FuelCalculator
{
public static int RequiredFuel(int mass)
{
var step1 = Math.Floor((double) mass / 3);
var step2 = step1 - 2;
return (int)step2;
}
}
}
|
PHP
|
UTF-8
| 8,675 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
/** op-unit-curl:/Curl.class.php
*
* @created 2017-06-01
* @version 1.0
* @package op-unit-curl
* @author Tomoaki Nagahara <tomoaki.nagahara@gmail.com>
* @copyright Tomoaki Nagahara All right reserved.
*/
/** namespace
*
* @created 2018-07-02
*/
namespace OP\UNIT;
/** Used class
*
*/
use OP\OP_CORE;
use OP\OP_UNIT;
use OP\OP_DEBUG;
use OP\IF_UNIT;
use OP\Config;
use OP\Notice;
use OP\UNIT\CURL\File;
use function OP\RootPath;
use function OP\ConvertURL;
use function OP\UNIT\CURL\GetReferer;
/*
use function OP\UNIT\CURL\GetCookieFilePath;
*/
/** Curl
*
*/
class Curl implements IF_UNIT
{
/** trait.
*
*/
use OP_CORE, OP_UNIT, OP_DEBUG;
/** Last error message.
*
* @var string
*/
static private $_errors;
/** Parse header string.
*
* @param string $header
* @return array $header
*/
static private function _Header($headers)
{
// ...
$result = [];
// ...
foreach( explode("\r\n", $headers) as $header ){
if( strlen($header) === 0 ){
// ...
}else if( $pos = strpos($header, ':') ){
// ...
$key = substr($header, 0, $pos );
$val = substr($header, $pos+1);
// ...
$result[strtolower($key)] = trim($val);
// Content-Type
if( strtolower($key) === 'content-type' ){
// MIME, Charset
list($mime, $charset) = explode(';', $val.';');
// MIME
$result['mime'] = trim($mime);
// Charset
if( $charset ){
list($key, $val) = explode('=', trim($charset));
$result[$key] = $val;
};
};
}else if( strpos($header, 'HTTP/') === 0 ){
list($result['http'], $result['status']) = explode(' ', $header);
}else{
$result[] = $header;
};
};
// ...
return $result;
}
/** Convert to string from array at post data.
*
* @param array $post
* @param string $format
* @return string $data
*/
static private function _Data($post, $format=null)
{
switch( $format ){
case 'json':
$data = json_encode($post);
break;
default:
// Content-Type: application/x-www-form-urlencoded
/*
$temp = [];
foreach( $post as $key => $val ){
$temp[$key] = self::Escape($val);
}
*/
$data = http_build_query($post, null, '&');
}
// ...
return $data;
}
/** Execute to Curl.
*
* @param string $url
* @param array $post
* @param array $option
* @return string $body
*/
static private function _Execute($url, $post, $option=[])
{
// ...
$config = Config::Get('curl');
// ...
$option = array_merge($config, $option);
// ...
if(!empty($option['cookie']) ){
// ...
$parsed = parse_url($url);
// ...
$path = RootPath('asset').'cache/cookie/'.$parsed['host'];
// ...
foreach(['cookie_read','cookie_write'] as $key){
if( empty($option[$key]) ){
$option[$key] = $path;
}
}
}
// ...
$format = $option['format'] ?? null; // Json, Xml
$referer = $option['referer'] ?? null; // Specified referer.
$has_header = $option['header'] ?? null; // Return request and response headers.
// Timeout second.
$timeout = $option['timeout'] ?? $config['ua'] ?? 10;
// Specified User Agent.
$ua = $option['ua'] ?? $config['ua'] ?? null;
// Content Type
switch( $format ){
default:
$content_type = 'application/x-www-form-urlencoded';
};
// Get referer at current app uri.
if( $referer === true ){
require_once(__DIR__.'/function/GetReferer.php');
$referer = GetReferer();
}
// Data serialize.
$data = $post ? self::_Data($post, $format): null;
// HTTP Header
$header = [];
$header[] = "Content-Type: {$content_type}";
$header[] = "Content-Length: ".strlen($data);
// Cookie is direct string.
if( $cookie = $option['cookie_string'] ?? null ){
$header[] = "Cookie: $cookie";
}
// Referer
if( $referer ){
$header[] = "Referer: $referer";
}
// Check if installed PHP CURL.
if(!defined('CURLOPT_URL') ){
// ...
D('PHP CURL is not installed.');
// ...
if( $post ){
// ...
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $header),
'content' => $data
],
/*
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
],
*/
]);
};
// ...
return file_get_contents($url, false, ($context ?? null));
};
// ...
$curl = curl_init();
// ...
if( $has_header ){
curl_setopt($curl, CURLOPT_HEADER, true);
};
// POST
if( $post !== null ){
curl_setopt( $curl, CURLOPT_CUSTOMREQUEST , 'POST' );
curl_setopt( $curl, CURLOPT_POST , true );
curl_setopt( $curl, CURLOPT_POSTFIELDS , $data );
};
// SSL
if( strpos($url, 'https://') === 0 ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt( $curl, CURLOPT_CAINFO, __DIR__.'/cacert.pem');
};
// Cookie read/write
foreach(['cookie_read' => CURLOPT_COOKIEFILE, 'cookie_write' => CURLOPT_COOKIEJAR] as $key => $var){
// ...
if(!$path = $option[$key] ?? null ){
continue;
}
// ...
if(!file_exists($path)){
require_once(__DIR__.'/File.class.php');
File::Create($path);
};
// ...
curl_setopt($curl, $var, $path);
}
// ...
$curl_option = [
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_USERAGENT => $ua,
CURLOPT_REFERER => $referer,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
];
// ...
curl_setopt_array($curl, $curl_option);
// ...
if(!$body = curl_exec($curl)){
$info = curl_getinfo($curl);
// ...
if( $errno = curl_errno($curl) ){
$error = sprintf('Error(%s): %s', $errno, $url);
self::$_errors[] = $error;
};
};
// Return ['head','body'] array.
if( $has_header ){
$body = curl_exec($curl);
$size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
return [
'errno'=> $errno ?? null,
'info' => $info ?? null,
'head' => self::_Header(
substr($body, 0, $size) ),
'body' => substr($body, $size),
];
};
// Return body string only.
return $body;
}
/** Separate error routine.
*
* @param integer $error is Curl error code
* @param integer $info is Curl transfer information
* @param string $url is fetch URL
* @param integer $timeout is timeout sec
*/
static private function _ExecuteError($errno, $info, $url, $timeout)
{
// ...
switch( $errno ){
case CURLE_OK:
break;
case CURLE_URL_MALFORMAT:
self::$_errors[] = 'The URL was not properly formatted.';
break;
case CURLE_COULDNT_RESOLVE_HOST:
self::$_errors[] = 'Couldn\'t resolve host. The given remote host was not resolved.';
break;
case 28:
case OPERATION_TIMEOUTED:
self::$_errors[] = "Response is timeout. ({$timeout} sec.)";
break;
case 60:
case CURLE_PEER_FAILED_VERIFICATION:
self::$_errors[] = 'The remote server\'s SSL certificate or SSH md5 fingerprint was deemed not OK.';
break;
default:
self::$_errors[] = "Response is error. ({$errno}, {$url})";
break;
}
// ...
switch( $code = $info['http_code'] ){
case 0:
return false;
case 200:
case 302:
case 403:
case 404:
case 405:
break;
/*
case 301:
if(!$body ){
$body = $info;
};
break;
*/
default:
Notice::Set("Http status code is {$code}.");
break;
}
}
/** Escape of string.
*
* @param string $string
* @return string $string
*/
static function Escape($string)
{
$string = preg_replace('/&/' , '%26', $string);
$string = preg_replace('/ /' , '%20', $string);
$string = preg_replace('/\t/', '%09', $string);
$string = preg_replace('/\s/', '%20', $string);
return $string;
}
/** Get method.
*
* @param string $url
* @param array $data
* @param string $option
* @return string $body
*/
static function Get($url, $data=null, $option=[])
{
// ...
if( $data ){
// ...
if( strpos($url, '?') ){
list($url, $query) = explode('?', $url);
parse_str($query, $query);
$data = array_merge($query, $data);
}
// ...
$url .= '?'.http_build_query($data);
}
// ...
return self::_Execute($url, null, $option);
}
/** Post method.
*
* @param string $url
* @param array $post
* @param string $option
* @return string $body
*/
static function Post($url, $post=[], $option=null)
{
return self::_Execute($url, $post, $option);
}
/** Return last error message.
*
* @return string
*/
static function Error()
{
return array_shift(self::$_errors[]);
}
}
|
Python
|
UTF-8
| 1,593 | 2.859375 | 3 |
[] |
no_license
|
###############
#CS519
#Xiao Tan
#HW 7 - 2
###############
from collections import defaultdict
def best(amount, value):
opt = defaultdict(lambda : -1)
types = -1
res = [0]*len(value)
def _best(i, x):
if i < 0 or x < 0 :
return 0
if x == 0:
opt[i, x] = 1
return opt[i, x]
if (i, x) in opt:
return opt[i, x]
op1 = _best(i-1, x)
op2 = _best(i, x - value[i])
opt[i, x] = op1 or op2
return opt[i, x]
def trace(i):
t, m, n = 0, 0, i
flag = 1
tmp = [0]*len(value)
while m < amount:
if opt[n, m + value[n]]==1:
tmp[n] += 1
m += value[n]
if flag ==1:
t += 1
flag = 0
else:
n += 1
flag = 1
return t,tmp
_best(len(value)-1, amount)
#print opt
if opt[len(value)-1, amount]== 0:
return None
else:
for i in range(len(value)):
if opt[i, 0] == 1:
a, b = trace(i)
if types == -1 or types > a:
types = a
res = b
return types, res
if __name__ == "__main__":
print best(47, [6, 10, 15])
# (3, [2, 2, 1])
print best(59, [6, 10, 15])
# (3, [4, 2, 1])
print best(37, [4, 6, 15])
# (3, [4, 1, 1])
print best(27, [4, 6, 15])
#(2, [3, 0, 1])
print best(75, [4, 6, 15])
#(1, [0, 0, 5])
print best(17, [2, 4, 6])
#None
|
JavaScript
|
UTF-8
| 2,926 | 2.78125 | 3 |
[] |
no_license
|
export default function buildSlider() {
const sliderWrapper = document.getElementsByClassName('slider-wrapper')[0];
const sliderNav = document.getElementsByClassName('slider-nav')[0];
const slides = [
{ name: '1 slide', img: '', startActive: true},
{ name: '2 slide', img: ''},
{ name: '3 slide', img: ''},
{ name: '4 slide', img: ''}
];
slides
.map((slide, i) => {
let newSlide = document.createElement(`div`);
let newNav = document.createElement(`a`);
if(slide.startActive) {
newSlide.className = 'slider-wrapper__slide active-slide-left';
newNav.className = 'slider-nav__slide active-nav';
} else {
newSlide.className = 'slider-wrapper__slide';
newNav.className = 'slider-nav__slide';
}
newSlide.innerHTML = `<span>${slide.name}</span>`;
newNav.href = '#';
newNav.onclick = (e) => {
let activeNav = document.getElementsByClassName('active-nav')[0];
if(e.target !== activeNav) {
activeNav.classList.toggle('active-nav');
e.target.classList.toggle('active-nav');
let pastActive;
let futureActive;
for(let i = 0; i < sliderNav.children.length; i++) {
if(sliderNav.children[i] === activeNav) {
pastActive = i;
}
if(sliderNav.children[i] === e.target) {
futureActive = i;
}
}
if(pastActive < futureActive) {
sliderWrapper.children[pastActive].classList.add('hide-slide-left')
setTimeout(function(){
sliderWrapper.children[pastActive].classList.remove('active-slide-right')
sliderWrapper.children[pastActive].classList.remove('active-slide-left')
sliderWrapper.children[pastActive].classList.remove('hide-slide-left')
}, 500);
sliderWrapper.children[futureActive].classList.add('active-slide-left')
}
else if(pastActive > futureActive) {
sliderWrapper.children[pastActive].classList.add('hide-slide-right')
setTimeout(function(){
sliderWrapper.children[pastActive].classList.remove('active-slide-left')
sliderWrapper.children[pastActive].classList.remove('active-slide-right')
sliderWrapper.children[pastActive].classList.remove('hide-slide-right')
}, 500);
sliderWrapper.children[futureActive].classList.add('active-slide-right')
}
}
}
sliderWrapper.appendChild(newSlide);
sliderNav.appendChild(newNav);
});
}
|
Go
|
UTF-8
| 49,882 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
package wrapper
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/alaingilbert/ogame/pkg/ogame"
"github.com/alaingilbert/ogame/pkg/utils"
echo "github.com/labstack/echo/v4"
)
// APIResp ...
type APIResp struct {
Status string
Code int
Message string
Result any
}
// SuccessResp ...
func SuccessResp(data any) APIResp {
return APIResp{Status: "ok", Code: 200, Result: data}
}
// ErrorResp ...
func ErrorResp(code int, message string) APIResp {
return APIResp{Status: "error", Code: code, Message: message}
}
// HomeHandler ...
func HomeHandler(c echo.Context) error {
version := c.Get("version").(string)
commit := c.Get("commit").(string)
date := c.Get("date").(string)
return c.JSON(http.StatusOK, map[string]any{
"version": version,
"commit": commit,
"date": date,
})
}
// TasksHandler return how many tasks are queued in the heap.
func TasksHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetTasks()))
}
// GetServerHandler ...
func GetServerHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetServer()))
}
// GetServerDataHandler ...
func GetServerDataHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.serverData))
}
// SetUserAgentHandler ...
// curl 127.0.0.1:1234/bot/set-user-agent -d 'userAgent="New user agent"'
func SetUserAgentHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
userAgent := c.Request().PostFormValue("userAgent")
bot.SetUserAgent(userAgent)
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// ServerURLHandler ...
func ServerURLHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.ServerURL()))
}
// GetLanguageHandler ...
func GetLanguageHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetLanguage()))
}
// PageContentHandler ...
// curl 127.0.0.1:1234/bot/page-content -d 'page=overview&cp=123'
func PageContentHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
if err := c.Request().ParseForm(); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
pageHTML, _ := bot.GetPageContent(c.Request().Form)
return c.JSON(http.StatusOK, SuccessResp(pageHTML))
}
// LoginHandler ...
func LoginHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
if _, err := bot.LoginWithExistingCookies(); err != nil {
if err == ogame.ErrBadCredentials {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// LogoutHandler ...
func LogoutHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
bot.Logout()
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetUsernameHandler ...
func GetUsernameHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetUsername()))
}
// GetUniverseNameHandler ...
func GetUniverseNameHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetUniverseName()))
}
// GetUniverseSpeedHandler ...
func GetUniverseSpeedHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.serverData.Speed))
}
// GetUniverseSpeedFleetHandler ...
func GetUniverseSpeedFleetHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.serverData.SpeedFleet))
}
// ServerVersionHandler ...
func ServerVersionHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.serverData.Version))
}
// ServerTimeHandler ...
func ServerTimeHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.ServerTime()))
}
// IsUnderAttackHandler ...
func IsUnderAttackHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
isUnderAttack, err := bot.IsUnderAttack()
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(isUnderAttack))
}
// IsVacationModeHandler ...
func IsVacationModeHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
isVacationMode := bot.isVacationModeEnabled
return c.JSON(http.StatusOK, SuccessResp(isVacationMode))
}
// GetUserInfosHandler ...
func GetUserInfosHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetUserInfos()))
}
// GetCharacterClassHandler ...
func GetCharacterClassHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.CharacterClass()))
}
// HasCommanderHandler ...
func HasCommanderHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
hasCommander := bot.hasCommander
return c.JSON(http.StatusOK, SuccessResp(hasCommander))
}
// HasAdmiralHandler ...
func HasAdmiralHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
hasAdmiral := bot.hasAdmiral
return c.JSON(http.StatusOK, SuccessResp(hasAdmiral))
}
// HasEngineerHandler ...
func HasEngineerHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
hasEngineer := bot.hasEngineer
return c.JSON(http.StatusOK, SuccessResp(hasEngineer))
}
// HasGeologistHandler ...
func HasGeologistHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
hasGeologist := bot.hasGeologist
return c.JSON(http.StatusOK, SuccessResp(hasGeologist))
}
// HasTechnocratHandler ...
func HasTechnocratHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
hasTechnocrat := bot.hasTechnocrat
return c.JSON(http.StatusOK, SuccessResp(hasTechnocrat))
}
// GetEspionageReportMessagesHandler ...
func GetEspionageReportMessagesHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
report, err := bot.GetEspionageReportMessages()
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(report))
}
// GetEspionageReportHandler ...
func GetEspionageReportHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
msgID, err := utils.ParseI64(c.Param("msgid"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid msgid id"))
}
espionageReport, err := bot.GetEspionageReport(msgID)
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(espionageReport))
}
// GetEspionageReportForHandler ...
func GetEspionageReportForHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
galaxy, err := utils.ParseI64(c.Param("galaxy"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy"))
}
system, err := utils.ParseI64(c.Param("system"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system"))
}
position, err := utils.ParseI64(c.Param("position"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position"))
}
planet, err := bot.GetEspionageReportFor(ogame.Coordinate{Type: ogame.PlanetType, Galaxy: galaxy, System: system, Position: position})
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(planet))
}
// SendMessageHandler ...
// curl 127.0.0.1:1234/bot/send-message -d 'playerID=123&message="Sup boi!"'
func SendMessageHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
playerID, err := utils.ParseI64(c.Request().PostFormValue("playerID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
message := c.Request().PostFormValue("message")
if err := bot.SendMessage(playerID, message); err != nil {
if err.Error() == "invalid parameters" {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetFleetsHandler ...
func GetFleetsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
fleets, _ := bot.GetFleets()
return c.JSON(http.StatusOK, SuccessResp(fleets))
}
// GetSlotsHandler ...
func GetSlotsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
slots := bot.GetSlots()
return c.JSON(http.StatusOK, SuccessResp(slots))
}
// CancelFleetHandler ...
func CancelFleetHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
fleetID, err := utils.ParseI64(c.Param("fleetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(bot.CancelFleet(ogame.FleetID(fleetID))))
}
// GetAttacksHandler ...
func GetAttacksHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
attacks, err := bot.GetAttacks()
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(attacks))
}
// GalaxyInfosHandler ...
func GalaxyInfosHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
galaxy, err := utils.ParseI64(c.Param("galaxy"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
system, err := utils.ParseI64(c.Param("system"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
res, err := bot.GalaxyInfos(galaxy, system)
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// GetResearchHandler ...
func GetResearchHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetResearch()))
}
// BuyOfferOfTheDayHandler ...
func BuyOfferOfTheDayHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
if err := bot.BuyOfferOfTheDay(); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetMoonsHandler ...
func GetMoonsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetMoons()))
}
// GetMoonHandler ...
func GetMoonHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
moonID, err := utils.ParseI64(c.Param("moonID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid moon id"))
}
moon, err := bot.GetMoon(moonID)
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid moon id"))
}
return c.JSON(http.StatusOK, SuccessResp(moon))
}
// GetMoonByCoordHandler ...
func GetMoonByCoordHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
galaxy, err := utils.ParseI64(c.Param("galaxy"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy"))
}
system, err := utils.ParseI64(c.Param("system"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system"))
}
position, err := utils.ParseI64(c.Param("position"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position"))
}
planet, err := bot.GetMoon(ogame.Coordinate{Type: ogame.MoonType, Galaxy: galaxy, System: system, Position: position})
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(planet))
}
// GetPlanetsHandler ...
func GetPlanetsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
return c.JSON(http.StatusOK, SuccessResp(bot.GetPlanets()))
}
// GetCelestialItemsHandler ...
func GetCelestialItemsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
celestialID, err := utils.ParseI64(c.Param("celestialID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial id"))
}
items, err := bot.GetItems(ogame.CelestialID(celestialID))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(items))
}
// ActivateCelestialItemHandler ...
func ActivateCelestialItemHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
celestialID, err := utils.ParseI64(c.Param("celestialID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial id"))
}
ref := c.Param("itemRef")
if err := bot.ActivateItem(ref, ogame.CelestialID(celestialID)); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetPlanetHandler ...
func GetPlanetHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
planet, err := bot.GetPlanet(ogame.PlanetID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(planet))
}
// GetPlanetByCoordHandler ...
func GetPlanetByCoordHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
galaxy, err := utils.ParseI64(c.Param("galaxy"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy"))
}
system, err := utils.ParseI64(c.Param("system"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system"))
}
position, err := utils.ParseI64(c.Param("position"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position"))
}
planet, err := bot.GetPlanet(ogame.Coordinate{Type: ogame.PlanetType, Galaxy: galaxy, System: system, Position: position})
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(planet))
}
// GetResourcesDetailsHandler ...
func GetResourcesDetailsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
resources, err := bot.GetResourcesDetails(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(resources))
}
// GetResourceSettingsHandler ...
func GetResourceSettingsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetResourceSettings(ogame.PlanetID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// SetResourceSettingsHandler ...
// curl 127.0.0.1:1234/bot/planets/123/resource-settings -d 'metalMine=100&crystalMine=100&deuteriumSynthesizer=100&solarPlant=100&fusionReactor=100&solarSatellite=100'
func SetResourceSettingsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
metalMine, err := utils.ParseI64(c.Request().PostFormValue("metalMine"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid metalMine"))
}
crystalMine, err := utils.ParseI64(c.Request().PostFormValue("crystalMine"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid crystalMine"))
}
deuteriumSynthesizer, err := utils.ParseI64(c.Request().PostFormValue("deuteriumSynthesizer"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid deuteriumSynthesizer"))
}
solarPlant, err := utils.ParseI64(c.Request().PostFormValue("solarPlant"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid solarPlant"))
}
fusionReactor, err := utils.ParseI64(c.Request().PostFormValue("fusionReactor"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid fusionReactor"))
}
solarSatellite, err := utils.ParseI64(c.Request().PostFormValue("solarSatellite"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid solarSatellite"))
}
crawler, err := utils.ParseI64(c.Request().PostFormValue("crawler"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid crawler"))
}
settings := ogame.ResourceSettings{
MetalMine: metalMine,
CrystalMine: crystalMine,
DeuteriumSynthesizer: deuteriumSynthesizer,
SolarPlant: solarPlant,
FusionReactor: fusionReactor,
SolarSatellite: solarSatellite,
Crawler: crawler,
}
if err := bot.SetResourceSettings(ogame.PlanetID(planetID), settings); err != nil {
if err == ogame.ErrInvalidPlanetID {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetLfBuildingsHandler ...
func GetLfBuildingsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetLfBuildings(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// GetLfResearchHandler ...
func GetLfResearchHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetLfResearch(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// GetResourcesBuildingsHandler ...
func GetResourcesBuildingsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetResourcesBuildings(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// GetDefenseHandler ...
func GetDefenseHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetDefense(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// GetShipsHandler ...
func GetShipsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetShips(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// GetFacilitiesHandler ...
func GetFacilitiesHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetFacilities(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// BuildHandler ...
func BuildHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
nbr, err := utils.ParseI64(c.Param("nbr"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr"))
}
if err := bot.Build(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// BuildCancelableHandler ...
func BuildCancelableHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
if err := bot.BuildCancelable(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// BuildProductionHandler ...
func BuildProductionHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
nbr, err := utils.ParseI64(c.Param("nbr"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr"))
}
if err := bot.BuildProduction(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// BuildBuildingHandler ...
func BuildBuildingHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
if err := bot.BuildBuilding(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// BuildTechnologyHandler ...
func BuildTechnologyHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
if err := bot.BuildTechnology(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// BuildDefenseHandler ...
func BuildDefenseHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
nbr, err := utils.ParseI64(c.Param("nbr"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr"))
}
if err := bot.BuildDefense(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// BuildShipsHandler ...
func BuildShipsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
nbr, err := utils.ParseI64(c.Param("nbr"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr"))
}
if err := bot.BuildShips(ogame.CelestialID(planetID), ogame.ID(ogameID), nbr); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetProductionHandler ...
func GetProductionHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, _, err := bot.GetProduction(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// ConstructionsBeingBuiltHandler ...
func ConstructionsBeingBuiltHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
buildingID, buildingCountdown, researchID, researchCountdown, lfBuildingID, lfBuildingCountdown, lfResearchID, lfResearchCountdown := bot.ConstructionsBeingBuilt(ogame.CelestialID(planetID))
return c.JSON(http.StatusOK, SuccessResp(
struct {
BuildingID int64
BuildingCountdown int64
ResearchID int64
ResearchCountdown int64
LfBuildingID int64
LfBuildingCountdown int64
LfResearchID int64
LfResearchCountdown int64
}{
BuildingID: int64(buildingID),
BuildingCountdown: buildingCountdown,
ResearchID: int64(researchID),
ResearchCountdown: researchCountdown,
LfBuildingID: int64(lfBuildingID),
LfBuildingCountdown: lfBuildingCountdown,
LfResearchID: int64(lfResearchID),
LfResearchCountdown: lfResearchCountdown,
},
))
}
// CancelBuildingHandler ...
func CancelBuildingHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
if err := bot.CancelBuilding(ogame.CelestialID(planetID)); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// CancelResearchHandler ...
func CancelResearchHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
if err := bot.CancelResearch(ogame.CelestialID(planetID)); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetResourcesHandler ...
func GetResourcesHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
res, err := bot.GetResources(ogame.CelestialID(planetID))
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(res))
}
// GetRequirementsHandler ...
func GetRequirementsHandler(c echo.Context) error {
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID"))
}
ogameObj := ogame.Objs.ByID(ogame.ID(ogameID))
if ogameObj != nil {
requirements := ogameObj.GetRequirements()
return c.JSON(http.StatusOK, SuccessResp(requirements))
}
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID"))
}
// GetPriceHandler ...
func GetPriceHandler(c echo.Context) error {
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID"))
}
nbr, err := utils.ParseI64(c.Param("nbr"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr"))
}
ogameObj := ogame.Objs.ByID(ogame.ID(ogameID))
if ogameObj != nil {
price := ogameObj.GetPrice(nbr)
return c.JSON(http.StatusOK, SuccessResp(price))
}
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogameID"))
}
// SendFleetHandler ...
// curl 127.0.0.1:1234/bot/planets/123/send-fleet -d 'ships=203,1&ships=204,10&speed=10&galaxy=1&system=1&type=1&position=1&mission=3&metal=1&crystal=2&deuterium=3'
func SendFleetHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
if err := c.Request().ParseForm(); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid form"))
}
var ships []ogame.Quantifiable
where := ogame.Coordinate{Type: ogame.PlanetType}
mission := ogame.Transport
var duration int64
var unionID int64
payload := ogame.Resources{}
speed := ogame.HundredPercent
for key, values := range c.Request().PostForm {
switch key {
case "ships":
for _, s := range values {
a := strings.Split(s, ",")
shipID, err := utils.ParseI64(a[0])
if err != nil || !ogame.ID(shipID).IsShip() {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ship id "+a[0]))
}
nbr, err := utils.ParseI64(a[1])
if err != nil || nbr < 0 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr "+a[1]))
}
ships = append(ships, ogame.Quantifiable{ID: ogame.ID(shipID), Nbr: nbr})
}
case "speed":
speedInt, err := utils.ParseI64(values[0])
if err != nil || speedInt < 0 || speedInt > 10 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid speed"))
}
speed = ogame.Speed(speedInt)
case "galaxy":
galaxy, err := utils.ParseI64(values[0])
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy"))
}
where.Galaxy = galaxy
case "system":
system, err := utils.ParseI64(values[0])
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system"))
}
where.System = system
case "position":
position, err := utils.ParseI64(values[0])
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position"))
}
where.Position = position
case "type":
t, err := utils.ParseI64(values[0])
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid type"))
}
where.Type = ogame.CelestialType(t)
case "mission":
missionInt, err := utils.ParseI64(values[0])
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid mission"))
}
mission = ogame.MissionID(missionInt)
case "duration":
duration, err = utils.ParseI64(values[0])
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid duration"))
}
case "union":
unionID, err = utils.ParseI64(values[0])
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid union id"))
}
case "metal":
metal, err := utils.ParseI64(values[0])
if err != nil || metal < 0 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid metal"))
}
payload.Metal = metal
case "crystal":
crystal, err := utils.ParseI64(values[0])
if err != nil || crystal < 0 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid crystal"))
}
payload.Crystal = crystal
case "deuterium":
deuterium, err := utils.ParseI64(values[0])
if err != nil || deuterium < 0 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid deuterium"))
}
payload.Deuterium = deuterium
}
}
fleet, err := bot.SendFleet(ogame.CelestialID(planetID), ships, speed, where, mission, payload, duration, unionID)
if err != nil &&
(err == ogame.ErrInvalidPlanetID ||
err == ogame.ErrNoShipSelected ||
err == ogame.ErrUninhabitedPlanet ||
err == ogame.ErrNoDebrisField ||
err == ogame.ErrPlayerInVacationMode ||
err == ogame.ErrAdminOrGM ||
err == ogame.ErrNoAstrophysics ||
err == ogame.ErrNoobProtection ||
err == ogame.ErrPlayerTooStrong ||
err == ogame.ErrNoMoonAvailable ||
err == ogame.ErrNoRecyclerAvailable ||
err == ogame.ErrNoEventsRunning ||
err == ogame.ErrPlanetAlreadyReservedForRelocation) {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(fleet))
}
// GetAlliancePageContentHandler ...
func GetAlliancePageContentHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
allianceID := c.QueryParam("allianceId")
vals := url.Values{"allianceId": {allianceID}}
pageHTML, _ := bot.GetPageContent(vals)
return c.HTML(http.StatusOK, string(pageHTML))
}
func replaceHostname(bot *OGame, html []byte) []byte {
serverURLBytes := []byte(bot.serverURL)
apiNewHostnameBytes := []byte(bot.apiNewHostname)
escapedServerURL := bytes.Replace(serverURLBytes, []byte("/"), []byte(`\/`), -1)
doubleEscapedServerURL := bytes.Replace(serverURLBytes, []byte("/"), []byte("\\\\\\/"), -1)
escapedAPINewHostname := bytes.Replace(apiNewHostnameBytes, []byte("/"), []byte(`\/`), -1)
doubleEscapedAPINewHostname := bytes.Replace(apiNewHostnameBytes, []byte("/"), []byte("\\\\\\/"), -1)
html = bytes.Replace(html, serverURLBytes, apiNewHostnameBytes, -1)
html = bytes.Replace(html, escapedServerURL, escapedAPINewHostname, -1)
html = bytes.Replace(html, doubleEscapedServerURL, doubleEscapedAPINewHostname, -1)
return html
}
// GetStaticHandler ...
func GetStaticHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
newURL := bot.serverURL + c.Request().URL.String()
req, err := http.NewRequest(http.MethodGet, newURL, nil)
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
req.Header.Add("Accept-Encoding", "gzip, deflate, br")
resp, err := bot.client.Do(req)
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
defer resp.Body.Close()
body, err := utils.ReadBody(resp)
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
// Copy the original HTTP headers to our client
for k, vv := range resp.Header { // duplicate headers are acceptable in HTTP spec, so add all of them individually: https://stackoverflow.com/questions/4371328/are-duplicate-http-response-headers-acceptable
k = http.CanonicalHeaderKey(k)
if k != "Content-Length" && k != "Content-Encoding" { // https://github.com/alaingilbert/ogame/pull/80#issuecomment-674559853
for _, v := range vv {
c.Response().Header().Add(k, v)
}
}
}
if strings.Contains(c.Request().URL.String(), ".xml") {
body = replaceHostname(bot, body)
return c.Blob(http.StatusOK, "application/xml", body)
}
contentType := http.DetectContentType(body)
if strings.Contains(newURL, ".css") {
contentType = "text/css"
} else if strings.Contains(newURL, ".js") {
contentType = "application/javascript"
} else if strings.Contains(newURL, ".gif") {
contentType = "image/gif"
}
return c.Blob(http.StatusOK, contentType, body)
}
// GetFromGameHandler ...
func GetFromGameHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
vals := url.Values{"page": {"ingame"}, "component": {"overview"}}
if len(c.QueryParams()) > 0 {
vals = c.QueryParams()
}
pageHTML, _ := bot.GetPageContent(vals)
pageHTML = replaceHostname(bot, pageHTML)
return c.HTMLBlob(http.StatusOK, pageHTML)
}
// PostToGameHandler ...
func PostToGameHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
vals := url.Values{"page": {"ingame"}, "component": {"overview"}}
if len(c.QueryParams()) > 0 {
vals = c.QueryParams()
}
payload, _ := c.FormParams()
pageHTML, _ := bot.PostPageContent(vals, payload)
pageHTML = replaceHostname(bot, pageHTML)
return c.HTMLBlob(http.StatusOK, pageHTML)
}
// GetStaticHEADHandler ...
func GetStaticHEADHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
newURL := "/api/" + strings.Join(c.ParamValues(), "") // + "?" + c.QueryString()
if len(c.QueryString()) > 0 {
newURL = newURL + "?" + c.QueryString()
}
headers, err := bot.HeadersForPage(newURL)
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
if len(headers) < 1 {
return c.NoContent(http.StatusFailedDependency)
}
// Copy the original HTTP HEAD headers to our client
for k, vv := range headers { // duplicate headers are acceptable in HTTP spec, so add all of them individually: https://stackoverflow.com/questions/4371328/are-duplicate-http-response-headers-acceptable
k = http.CanonicalHeaderKey(k)
for _, v := range vv {
c.Response().Header().Add(k, v)
}
}
return c.NoContent(http.StatusOK)
}
// GetEmpireHandler ...
func GetEmpireHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
nbr, err := utils.ParseI64(c.Param("typeID"))
if err != nil || nbr > 1 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid typeID"))
}
getEmpire, err := bot.GetEmpireJSON(nbr)
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(getEmpire))
}
// DeleteMessageHandler ...
func DeleteMessageHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
messageID, err := utils.ParseI64(c.Param("messageID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid message id"))
}
if err := bot.DeleteMessage(messageID); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// DeleteEspionageMessagesHandler ...
func DeleteEspionageMessagesHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
if err := bot.DeleteAllMessagesFromTab(20); err != nil { // 20 = Espionage Reports
return c.JSON(http.StatusBadRequest, ErrorResp(400, "Unable to delete Espionage Reports"))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// DeleteMessagesFromTabHandler ...
func DeleteMessagesFromTabHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
tabIndex, err := utils.ParseI64(c.Param("tabIndex"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "must provide tabIndex"))
}
if tabIndex < 20 || tabIndex > 24 {
/*
tabid: 20 => Espionage
tabid: 21 => Combat Reports
tabid: 22 => Expeditions
tabid: 23 => Unions/Transport
tabid: 24 => Other
*/
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid tabIndex provided"))
}
if err := bot.DeleteAllMessagesFromTab(ogame.MessagesTabID(tabIndex)); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "Unable to delete message from tab "+utils.FI64(tabIndex)))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// SendIPMHandler ...
func SendIPMHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
ipmAmount, err := utils.ParseI64(c.Param("ipmAmount"))
if err != nil || ipmAmount < 1 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ipmAmount"))
}
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil || planetID < 1 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
galaxy, err := utils.ParseI64(c.Request().PostFormValue("galaxy"))
if err != nil || galaxy < 1 || galaxy > bot.serverData.Galaxies {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy"))
}
system, err := utils.ParseI64(c.Request().PostFormValue("system"))
if err != nil || system < 1 || system > bot.serverData.Systems {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system"))
}
position, err := utils.ParseI64(c.Request().PostFormValue("position"))
if err != nil || position < 1 || position > 15 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position"))
}
planetTypeInt, err := utils.ParseI64(c.Param("type"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
planetType := ogame.CelestialType(planetTypeInt)
if planetType != ogame.PlanetType && planetType != ogame.MoonType { // only accept planet/moon types
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid type"))
}
priority := utils.DoParseI64(c.Request().PostFormValue("priority"))
coord := ogame.Coordinate{Type: planetType, Galaxy: galaxy, System: system, Position: position}
duration, err := bot.SendIPM(ogame.PlanetID(planetID), coord, ipmAmount, ogame.ID(priority))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(duration))
}
// TeardownHandler ...
func TeardownHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
planetID, err := utils.ParseI64(c.Param("planetID"))
if err != nil || planetID < 0 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid planet id"))
}
ogameID, err := utils.ParseI64(c.Param("ogameID"))
if err != nil || planetID < 0 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ogame id"))
}
if err = bot.TearDown(ogame.CelestialID(planetID), ogame.ID(ogameID)); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// GetAuctionHandler ...
func GetAuctionHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
auction, err := bot.GetAuction()
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "could not open auction page"))
}
return c.JSON(http.StatusOK, SuccessResp(auction))
}
// DoAuctionHandler (`celestialID=metal:crystal:deuterium` eg: `123456=123:456:789`)
func DoAuctionHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
bid := make(map[ogame.CelestialID]ogame.Resources)
if err := c.Request().ParseForm(); err != nil { // Required for PostForm, not for PostFormValue
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid form"))
}
for key, values := range c.Request().PostForm {
for _, s := range values {
var metal, crystal, deuterium int64
if n, err := fmt.Sscanf(s, "%d:%d:%d", &metal, &crystal, &deuterium); err != nil || n != 3 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid bid format"))
}
celestialIDInt, err := utils.ParseI64(key)
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial ID"))
}
bid[ogame.CelestialID(celestialIDInt)] = ogame.Resources{Metal: metal, Crystal: crystal, Deuterium: deuterium}
}
}
if err := bot.DoAuction(bid); err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(nil))
}
// PhalanxHandler ...
func PhalanxHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
moonID, err := utils.ParseI64(c.Param("moonID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid moon id"))
}
galaxy, err := utils.ParseI64(c.Param("galaxy"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid galaxy"))
}
system, err := utils.ParseI64(c.Param("system"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid system"))
}
position, err := utils.ParseI64(c.Param("position"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid position"))
}
coord := ogame.Coordinate{Type: ogame.PlanetType, Galaxy: galaxy, System: system, Position: position}
fleets, err := bot.Phalanx(ogame.MoonID(moonID), coord)
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(fleets))
}
// JumpGateHandler ...
func JumpGateHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
if err := c.Request().ParseForm(); err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid form"))
}
moonOriginID, err := utils.ParseI64(c.Param("moonID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid origin moon id"))
}
moonDestinationID, err := utils.ParseI64(c.Request().PostFormValue("moonDestination"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid destination moon id"))
}
var ships ogame.ShipsInfos
for key, values := range c.Request().PostForm {
switch key {
case "ships":
for _, s := range values {
a := strings.Split(s, ",")
shipID, err := utils.ParseI64(a[0])
if err != nil || !ogame.ID(shipID).IsShip() {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid ship id "+a[0]))
}
nbr, err := utils.ParseI64(a[1])
if err != nil || nbr < 0 {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid nbr "+a[1]))
}
ships.Set(ogame.ID(shipID), nbr)
}
}
}
success, rechargeCountdown, err := bot.JumpGate(ogame.MoonID(moonOriginID), ogame.MoonID(moonDestinationID), ships)
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(map[string]any{
"success": success,
"rechargeCountdown": rechargeCountdown,
}))
}
// TechsHandler ...
func TechsHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
celestialID, err := utils.ParseI64(c.Param("celestialID"))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, "invalid celestial id"))
}
supplies, facilities, ships, defenses, researches, lfbuildings, err := bot.GetTechs(ogame.CelestialID(celestialID))
if err != nil {
return c.JSON(http.StatusBadRequest, ErrorResp(400, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(map[string]any{
"supplies": supplies,
"facilities": facilities,
"ships": ships,
"defenses": defenses,
"researches": researches,
"lfbuildings": lfbuildings,
}))
}
// GetCaptchaHandler ...
func GetCaptchaHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
_, err := GFLogin(bot.client, bot.ctx, bot.lobby, bot.Username, bot.password, bot.otpSecret, "")
var captchaErr *CaptchaRequiredError
if errors.As(err, &captchaErr) {
questionRaw, iconsRaw, err := StartCaptchaChallenge(bot.GetClient(), bot.ctx, captchaErr.ChallengeID)
if err != nil {
return c.HTML(http.StatusOK, err.Error())
}
questionB64 := base64.StdEncoding.EncodeToString(questionRaw)
iconsB64 := base64.StdEncoding.EncodeToString(iconsRaw)
html := `<img style="background-color: black;" src="data:image/png;base64,` + questionB64 + `" /><br />
<img style="background-color: black;" src="data:image/png;base64,` + iconsB64 + `" /><br />
<form action="/bot/captcha/solve" method="POST">
<input type="hidden" name="challenge_id" value="` + captchaErr.ChallengeID + `" />
Enter 0,1,2 or 3 and press Enter <input type="number" name="answer" />
</form>` + captchaErr.ChallengeID
return c.HTML(http.StatusOK, html)
} else if err != nil {
return c.HTML(http.StatusOK, err.Error())
}
return c.HTML(http.StatusOK, "no captcha found")
}
// GetCaptchaSolverHandler ...
func GetCaptchaSolverHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
challengeID := c.Request().PostFormValue("challenge_id")
answer := utils.DoParseI64(c.Request().PostFormValue("answer"))
if err := SolveChallenge(bot.GetClient(), bot.ctx, challengeID, answer); err != nil {
bot.error(err)
}
if !bot.IsLoggedIn() {
if err := bot.Login(); err != nil {
bot.error(err)
}
}
return c.Redirect(http.StatusTemporaryRedirect, "/")
}
// CaptchaChallenge ...
type CaptchaChallenge struct {
ID string
Question string
Icons string
}
// GetCaptchaChallengeHandler ...
func GetCaptchaChallengeHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
_, err := GFLogin(bot.client, bot.ctx, bot.lobby, bot.Username, bot.password, bot.otpSecret, "")
var captchaErr *CaptchaRequiredError
if errors.As(err, &captchaErr) {
questionRaw, iconsRaw, err := StartCaptchaChallenge(bot.GetClient(), bot.ctx, captchaErr.ChallengeID)
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
questionB64 := base64.StdEncoding.EncodeToString(questionRaw)
iconsB64 := base64.StdEncoding.EncodeToString(iconsRaw)
return c.JSON(http.StatusOK, SuccessResp(CaptchaChallenge{
ID: captchaErr.ChallengeID,
Question: questionB64,
Icons: iconsB64,
}))
} else if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(CaptchaChallenge{}))
}
// GetPublicIPHandler ...
func GetPublicIPHandler(c echo.Context) error {
bot := c.Get("bot").(*OGame)
ip, err := bot.GetPublicIP()
if err != nil {
return c.JSON(http.StatusInternalServerError, ErrorResp(500, err.Error()))
}
return c.JSON(http.StatusOK, SuccessResp(ip))
}
|
Markdown
|
UTF-8
| 11,401 | 3.59375 | 4 |
[
"Apache-2.0",
"CC-BY-3.0"
] |
permissive
|
---
title: JavaScript๏ผ่ฟๆฏไปไนๆๆ๏ผ
subhead: ๅจ JavaScript ไธญๆพๅบ `this` ็ๅผๅฏ่ฝๅพ้พ๏ผ่ฟ้ไป็ปไบๆนๆณโฆโฆ
description: ๅจ JavaScript ไธญๆพๅบ `this` ็ๅผๅฏ่ฝๅพ้พ๏ผ่ฟ้ไป็ปไบๆนๆณโฆโฆ
authors:
- jakearchibald
date: 2021-03-08
hero: image/CZmpGM8Eo1dFe0KNhEO9SGO8Ok23/cePCOGeXNFT6WCy85gb4.png
alt: "this \U0001F914"
tags:
- blog
- javascript
---
JavaScript ็`this`ไบง็ไบ่ฎธๅค็ฌ่ฏ๏ผๅ ไธบๅฎ้ๅธธๅคๆใไฝๆฏ๏ผๆๅทฒ็ป็ๅฐๅผๅไบบๅๅไบๆดๅคๆๅ็นๅฎ้ขๅ็ไบๆฅ้ฟๅ
ๅค็`this` ใๅฆๆๆจไธ็กฎๅฎ`this`ๆฏไปไน๏ผๅธๆๆฌๆไผๅฏนๆจๆๆๅธฎๅฉใ่ฟๆฏๆ็`this`ๆๅใ
ๆไผไปๆๅ
ทไฝ็ๆ
ๅตๅผๅง่ฎฒ่ตท๏ผไปฅๆไธๅ
ทไฝ็ๆ
ๅต็ปๆใ่ฟ็ฏๆ็ซ ๆ็นๅไธไธชๅคงๅคง็`if (โฆ) โฆ else if () โฆ else if (โฆ) โฆ` ๏ผๆไปฅๆจๅฏไปฅ็ดๆฅ่ฟๅ
ฅไธๆจ่ฆไบ่งฃ็ไปฃ็ ็ธๅน้
็็ฌฌไธ่ใ
1. [ๅฆๆๅฝๆฐๅฎไนไธบ็ฎญๅคดๅฝๆฐ](#arrow-functions)
2. [ๅฆๅ๏ผๅฆๆไฝฟ็จ`new`](#new)่ฐ็จๅฝๆฐ/็ฑป
3. [ๅฆๅ๏ผๅฆๆๅฝๆฐๆไธไธชโ็ปๅฎโ็`this`ๅผ](#bound)
4. [ๅฆๅ๏ผๅฆๆ`this`ๆฏๅจ่ฐ็จๆถ่ฎพ็ฝฎ็](#call-apply)
5. ๅฆๅ๏ผๅฆๆๅฝๆฐๆฏ้่ฟ็ถๅฏน่ฑก (<code>parent.func()</code>) ่ฐ็จ็๏ผ {: #object-member }
6. [ๅฆๅ๏ผๅฆๆๅฝๆฐๆ็ถไฝ็จๅๅคไบไธฅๆ ผๆจกๅผ](#strict)
7. [ๅฆๅ](#otherwise)
## ๅฆๆๅฝๆฐๅฎไนไธบ็ฎญๅคดๅฝๆฐ๏ผ{: #arrow-functions }
```js
const arrowFunction = () => {
console.log(this);
};
```
ๅจ่ฟ็งๆ
ๅตไธ๏ผ`this`็ๅผ*ๅง็ป*ไธ็ถไฝ็จๅ็`this`็ธๅ๏ผ
```js
const outerThis = this;
const arrowFunction = () => {
// Always logs `true`:
console.log(this === outerThis);
};
```
็ฎญๅคดๅฝๆฐๅฅฝๅฐฑๅฅฝๅจ`this`็ๅ
้จๅผๆ ๆณๆดๆน๏ผๅฎ*ๅง็ป*ไธๅค้จ`this`็ธๅใ
### ๅ
ถไป็คบไพ
ไฝฟ็จ็ฎญๅคดๅฝๆฐๆถ๏ผ*ไธ่ฝ*้่ฟ[`bind`](#bound)ๆดๆน `this`็ๅผ๏ผ
```js
// Logs `true` - bound `this` value is ignored:
arrowFunction.bind({foo: 'bar'})();
```
ไฝฟ็จ็ฎญๅคดๅฝๆฐๆถ๏ผ*ไธ่ฝ*้่ฟ[`call`ๆ`apply`](#call-apply)ๆดๆน`this`็ๅผ๏ผ
```js
// Logs `true` - called `this` value is ignored:
arrowFunction.call({foo: 'bar'});
// Logs `true` - applied `this` value is ignored:
arrowFunction.apply({foo: 'bar'});
```
ไฝฟ็จ็ฎญๅคดๅฝๆฐๆถ๏ผ*ไธ่ฝ*้่ฟๅฐๅฝๆฐไฝไธบๅฆไธไธชๅฏน่ฑก็ๆๅ่ฐ็จๆฅๆดๆน`this`็ๅผ๏ผ
```js
const obj = {arrowFunction};
// Logs `true` - parent object is ignored:
obj.arrowFunction();
```
ไฝฟ็จๅฏนไบ็ฎญๅคดๅฝๆฐๆถ๏ผ*ไธ่ฝ*้่ฟๅฐๅฝๆฐไฝไธบๆ้ ๅฝๆฐ่ฐ็จๆฅๆดๆน`this`็ๅผ๏ผ
```js
// TypeError: arrowFunction is not a constructor
new arrowFunction();
```
### โ็ปๅฎโๅฎไพๆนๆณ
ไฝฟ็จๅฎไพๆนๆณๆถ๏ผๅฆๆๆจๆณ็กฎไฟ`this`ๅง็ปๆๅ็ฑปๅฎไพ๏ผๆๅฅฝ็ๆนๆณๆฏไฝฟ็จ็ฎญๅคดๅฝๆฐๅ[็ฑปๅญๆฎต](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields)๏ผ
```js
class Whatever {
someMethod = () => {
// Always the instance of Whatever:
console.log(this);
};
}
```
ๅฝๅจ็ปไปถ๏ผไพๅฆ React ็ปไปถๆ Web ็ปไปถ๏ผไธญไฝฟ็จๅฎไพๆนๆณไฝไธบไบไปถไพฆๅฌๅจๆถ๏ผๆญคๆจกๅผ้ๅธธๆ็จใ
ไธ้ข็ๅ
ๅฎนๅฏ่ฝไผ่ฎฉไบบ่งๅพๅฎๆ็ ดไบโ`this`ไธ็ถไฝ็จๅ็`this`็ธๅโ่งๅ๏ผไฝๅฆๆๆจๅฐ็ฑปๅญๆฎต่งไธบๅจๆ้ ๅฝๆฐไธญ่ฎพ็ฝฎๅ
ๅฎน็่ฏญๆณ็ณ๏ผ่ฟๆ ทๅฐฑ่ฎฒๅพ้ไบ๏ผ
```js
class Whatever {
someMethod = (() => {
const outerThis = this;
return () => {
// Always logs `true`:
console.log(this === outerThis);
};
})();
}
// โฆis roughly equivalent to:
class Whatever {
constructor() {
const outerThis = this;
this.someMethod = () => {
// Always logs `true`:
console.log(this === outerThis);
};
}
}
```
ๆฟไปฃๆจกๅผๆถๅๅจๆ้ ๅฝๆฐไธญ็ปๅฎ็ฐๆๅฝๆฐ๏ผๆๅจๆ้ ๅฝๆฐไธญๅ้
ๅฝๆฐใๅฆๆ็ฑไบๆ็งๅๅ ไธ่ฝไฝฟ็จ็ฑปๅญๆฎต๏ผ้ฃไนๅจๆ้ ๅฝๆฐไธญๅ้
ๅฝๆฐๆฏไธไธชๅ็็้ๆฉ๏ผ
```js
class Whatever {
constructor() {
this.someMethod = () => {
// โฆ
};
}
}
```
## ๅฆๅ๏ผๅฆๆไฝฟ็จ<code>new</code>่ฐ็จๅฝๆฐ/็ฑป {: #new }
```js
new Whatever();
```
ไธ้ข็ไปฃ็ ไผ่ฐ็จ`Whatever`๏ผๆๅฆๆๅฎๆฏ็ฑป็่ฏ๏ผไผ่ฐ็จๅฎ็ๆ้ ๅฝๆฐ๏ผ๏ผๅนถๅฐ`this`่ฎพ็ฝฎไธบ`Object.create(Whatever.prototype)`็็ปๆใ
```js
class MyClass {
constructor() {
console.log(
this.constructor === Object.create(MyClass.prototype).constructor,
);
}
}
// Logs `true`:
new MyClass();
```
ๅฏนไบๆงๅผๆ้ ๅฝๆฐไนๆฏๅฆๆญค๏ผ
```js
function MyClass() {
console.log(
this.constructor === Object.create(MyClass.prototype).constructor,
);
}
// Logs `true`:
new MyClass();
```
### ๅ
ถไป็คบไพ
ๅฝไฝฟ็จ`new`่ฐ็จๆถ๏ผ*ๆ ๆณ*็จ[`bind`](#bound)ๆนๅ`this`็ๅผ๏ผ
```js
const BoundMyClass = MyClass.bind({foo: 'bar'});
// Logs `true` - bound `this` value is ignored:
new BoundMyClass();
```
ๅฝไฝฟ็จ`new`่ฐ็จๆถ๏ผ*ไธ่ฝ*้่ฟๅฐๅฝๆฐไฝไธบๅฆไธไธชๅฏน่ฑก็ๆๅ่ฐ็จๆฅๆดๆน`this`็ๅผ๏ผ
```js
const obj = {MyClass};
// Logs `true` - parent object is ignored:
new obj.MyClass();
```
## ๅฆๅ๏ผๅฆๆๅฝๆฐๆไธไธชโ็ปๅฎโ็<code>this</code>ๅผ {: #bound }
```js
function someFunction() {
return this;
}
const boundObject = {hello: 'world'};
const boundFunction = someFunction.bind(boundObject);
```
ๆฏๆฌก่ฐ็จ`boundFunction`ๆถ๏ผๅฎ็`this`ๅผๅฐๆฏไผ ้็ป`bind` ( `boundObject` ) ็ๅฏน่ฑกใ
```js
// Logs `false`:
console.log(someFunction() === boundObject);
// Logs `true`:
console.log(boundFunction() === boundObject);
```
{% Aside 'warning' %} ้ฟๅ
ไฝฟ็จ`bind`ๅฐๅฝๆฐ็ปๅฎๅฐๅฎ็ๅค้จ`this` ใ็ธๅ๏ผไฝฟ็จ[็ฎญๅคดๅฝๆฐ](#arrow-functions)๏ผๅ ไธบๅฎไปฌ้่ฟๅฝๆฐ็ๅฝ่ฎฉ`this`ๆดๆธ
ๆฐ๏ผ่ไธๆฏๅจไปฃ็ ๅ้ขๅ็็ไบๆ
ใ
ไธ่ฆไฝฟ็จ`bind`ๅฐ`this`่ฎพ็ฝฎไธบไธ็ถๅฏน่ฑกๆ ๅ
ณ็ๆไธชๅผ๏ผ่ฟ้ๅธธๆฏๅบไนๆๆ็๏ผ่ฟๅฐฑๆฏ`this`้ญไบบ่ฏ็
็ๅๅ ใ่่ๅฐๅผไฝไธบๅๆฐไผ ้๏ผๅฎๆดๆ็กฎ๏ผๅนถไธๅฏไธ็ฎญๅคดๅฝๆฐไธ่ตทไฝฟ็จใ {% endAside %}
### ๅ
ถไป็คบไพ
่ฐ็จ็ปๅฎๅฝๆฐๆถ๏ผ*ๆ ๆณ*้่ฟ[`call`ๆ`apply`](#call-apply)ๆดๆน`this`็ๅผ๏ผ
```js
// Logs `true` - called `this` value is ignored:
console.log(boundFunction.call({foo: 'bar'}) === boundObject);
// Logs `true` - applied `this` value is ignored:
console.log(boundFunction.apply({foo: 'bar'}) === boundObject);
```
่ฐ็จ็ปๅฎๅฝๆฐๆถ๏ผ*ไธ่ฝ*้่ฟๅฐๅฝๆฐไฝไธบๅฆไธไธชๅฏน่ฑก็ๆๅ่ฐ็จๆฅๆดๆน`this`็ๅผ๏ผ
```js
const obj = {boundFunction};
// Logs `true` - parent object is ignored:
console.log(obj.boundFunction() === boundObject);
```
## ๅฆๅ๏ผๅฆๆ`this`ๆฏๅจ่ฐ็จๆถ่ฎพ็ฝฎ็๏ผ{: #call-apply }
```js
function someFunction() {
return this;
}
const someObject = {hello: 'world'};
// Logs `true`:
console.log(someFunction.call(someObject) === someObject);
// Logs `true`:
console.log(someFunction.apply(someObject) === someObject);
```
`this`็ๅผๆฏไผ ้็ป`call` / `apply`็ๅฏน่ฑกใ
{% Aside 'warning' %}ไธ่ฆไฝฟ็จ`call`/`apply` ๅฐ`this`่ฎพ็ฝฎไธบไธ็ถๅฏน่ฑกๆ ๅ
ณ็ๆไธชๅผ๏ผ่ฟ้ๅธธๆฏๅบไนๆๆ็๏ผ่ฟๅฐฑๆฏ`this`้ญไบบ่ฏ็
็ๅๅ ใ่่ๅฐๅผไฝไธบๅๆฐไผ ้๏ผๅฎๆดๆ็กฎ๏ผๅนถไธๅฏไธ็ฎญๅคดๅฝๆฐไธ่ตทไฝฟ็จใ {% endAside %}
ไธๅนธ็ๆฏ๏ผ `this`่ขซ่ฏธๅฆ DOM ไบไปถไพฆๅฌๅจไน็ฑป็ไธ่ฅฟ่ฎพ็ฝฎไธบๅ
ถไปไธไบๅผ๏ผๅนถไธไฝฟ็จๅฎๅฏ่ฝไผๅฏผ่ด้พไปฅ็่งฃ็ไปฃ็ ๏ผ
{% Compare 'worse' %}
```js
element.addEventListener('click', function (event) {
// Logs `element`, since the DOM spec sets `this` to
// the element the handler is attached to.
console.log(this);
});
```
{% endCompare %}
ๆไผ้ฟๅ
ๅจไธ่ฟฐๆ
ๅตไธไฝฟ็จ`this`๏ผ่ๆฏ็จ๏ผ
{% Compare 'better' %}
```js
element.addEventListener('click', (event) => {
// Ideally, grab it from a parent scope:
console.log(element);
// But if you can't do that, get it from the event object:
console.log(event.currentTarget);
});
```
{% endCompare %}
## ๅฆๅ๏ผๅฆๆๅฝๆฐๆฏ้่ฟ็ถๅฏน่ฑก (`parent.func()`) ่ฐ็จ็๏ผ {: #object-member }
```js
const obj = {
someMethod() {
return this;
},
};
// Logs `true`:
console.log(obj.someMethod() === obj);
```
ๅจ่ฟ็งๆ
ๅตไธ๏ผๅฝๆฐไฝไธบ`obj`็ๆๅ่ขซ่ฐ็จ๏ผๆไปฅ`this`ไผๆฏ`obj` ใ่ฟๅ็ๅจ่ฐ็จๆถ๏ผๆไปฅๅฆๆๅจๆฒกๆ็ถๅฏน่ฑก็ๆ
ๅตไธ่ฐ็จๅฝๆฐ๏ผๆ่
ไฝฟ็จไธๅ็็ถๅฏน่ฑก่ฐ็จๅฝๆฐ๏ผ้พๆฅๅฐฑไผๆญๅผ๏ผ
```js
const {someMethod} = obj;
// Logs `false`:
console.log(someMethod() === obj);
const anotherObj = {someMethod};
// Logs `false`:
console.log(anotherObj.someMethod() === obj);
// Logs `true`:
console.log(anotherObj.someMethod() === anotherObj);
```
`someMethod() === obj`ๆฏ false๏ผๅ ไธบ`someMethod`*ไธๆฏ*ไฝไธบ`obj`็ๆๅ่ฐ็จ็ใๅจๅฐ่ฏ่ฟๆ ท็ไบๆ
ๆถ๏ผๆจๅฏ่ฝ้ๅฐ่ฟ่ฟไธช้ฎ้ข๏ผ
```js
const $ = document.querySelector;
// TypeError: Illegal invocation
const el = $('.some-element');
```
่ฟไผไธญๆญ๏ผๅ ไธบ`querySelector`็ๅฎ็ฐๆฅ็่ชๅทฑ็`this`ๅผๅนถๆๆๅฎๆฏๆ็ง DOM ่็น๏ผ่ไธ่ฟฐไปฃ็ ไธญๆญไบ่ฏฅ่ฟๆฅใ่ฆๆญฃ็กฎๅฎ็ฐไธ่ฟฐ็ฎๆ ๏ผ
```js
const $ = document.querySelector.bind(document);
// Or:
const $ = (...args) => document.querySelector(...args);
```
ๆ่ถฃ็ไบๅฎ๏ผๅนถ้ๆๆ็ API ้ฝๅจๅ
้จไฝฟ็จ`this`ใๅฆ`console.log`่ฟๆ ท็ๆงๅถๅฐๆนๆณๅทฒๅ่ฟๆดๆน๏ผไป่้ฟๅ
ๅผ็จ`this`๏ผๅ ๆญคไธ้่ฆๅฐ`log`็ปๅฎๅฐ`console`ใ
{% Aside 'warning' %}ไธ่ฆๅฐๅฝๆฐ็งปๆคๅฐๅฏน่ฑกไธ๏ผๆฅๅฐ<code>this</code>่ฎพ็ฝฎไธบไธ็ถๅฏน่ฑกๆ ๅ
ณ็ๆไธชๅผ๏ผ่ฟ้ๅธธๆฏๅบไนๆๆ็๏ผ่ฟๅฐฑๆฏ<code>this</code>้ญไบบ่ฏ็
็ๅๅ ใ่่ๅฐๅผไฝไธบๅๆฐไผ ้๏ผๅฎๆดๆ็กฎ๏ผๅนถไธๅฏไธ็ฎญๅคดๅฝๆฐไธ่ตทไฝฟ็จใ {% endAside %}
## ๅฆๅ๏ผๅฆๆๅฝๆฐๆ็ถไฝ็จๅๅคไบไธฅๆ ผๆจกๅผ๏ผ{: #strict }
```js
function someFunction() {
'use strict';
return this;
}
// Logs `true`:
console.log(someFunction() === undefined);
```
ๅจ่ฟ็งๆ
ๅตไธ๏ผไปทๅผ`this`ๆฒกๆๅฎไนใ ๅฆๆ็ถไฝ็จๅๅคไบ[ไธฅๆ ผๆจกๅผ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode)๏ผๅนถไธๆๆๆจกๅ้ฝๅคไบไธฅๆ ผๆจกๅผ๏ผ๏ผๅๅฝๆฐไธญไธ้่ฆ`'use strict'`ใ
{% Aside 'warning' %}ไธ่ฆไพ่ต่ฟไธชๆนๆณใๆ็ๆๆๆฏ๏ผๆๆด็ฎๅ็ๆนๆณๅฏไปฅ่ทๅพ`undefined`ๅผ๐ใ {% endAside %}
## ๅฆๅ๏ผ{: #otherwise }
```js
function someFunction() {
return this;
}
// Logs `true`:
console.log(someFunction() === globalThis);
```
ๅจ่ฟ็งๆ
ๅตไธ๏ผ`this`็ๅผไธ`globalThis`็ธๅใ
{% Aside %} ๅคงๅคๆฐไบบ๏ผๅ
ๆฌๆ๏ผ้ฝๅฐ`globalThis`็งฐไธบๅ
จๅฑๅฏน่ฑก๏ผไฝ่ฟๅจๆๆฏไธๅนถไธๆฏๅฎๅ
จๆญฃ็กฎ็ใ่ฟ้ๆฏ[Mathias Bynens ็่ฏฆ็ปไป็ป](https://mathiasbynens.be/notes/globalthis#terminology)๏ผๅ
ๆฌไธบไปไนๅฐๅ
ถ็งฐไธบ`globalThis`่ไธๆฏ็ฎๅ็`global` ใ {% endAside %}
{% Aside 'warning' %} ้ฟๅ
ไฝฟ็จ`this`ๆฅๅผ็จๅ
จๅฑๅฏน่ฑก๏ผๆฏ็๏ผๆไป็ถ่ฟๆ ท็งฐๅผๅฎ๏ผใ็ธๅ๏ผ่ฏทไฝฟ็จๆดๅ ๆ็กฎ็[`globalThis`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/globalThis) {% endAside %}
## ๅคงๅๅๆ๏ผ
ๅฐฑๆฏ่ฟๆ ท๏ผ่ฟๅฐฑๆฏๆ็ฅ้็ๅ
ณไบ`this`็ไธๅใๆไปปไฝ็้ฎ๏ผๆๆผๆไบไปไน๏ผ่ฏท้ๆถ[็ปๆๅๆจๆ](https://twitter.com/jaffathecake)ใ
ๆ่ฐข [Mathias Bynens](https://twitter.com/mathias) ใ[Ingvar Stepanyan](https://twitter.com/RReverser) ๅ [Thomas Steiner](https://twitter.com/tomayac)็ๆ กๅฏนใ
|
Go
|
UTF-8
| 214 | 3.28125 | 3 |
[
"MIT",
"Unlicense"
] |
permissive
|
package main
import (
"fmt"
)
func coprime(x, y int) bool {
gcd := func(x, y int) int {
for y != 0 {
x, y = y, x % y
}
return x
}
return gcd(x, y) == 1
}
func main() {
fmt.Println(coprime(2, 7))
}
|
PHP
|
UTF-8
| 2,654 | 3.6875 | 4 |
[] |
no_license
|
<!-- Q.10) Write a PHP program to sort the student records which are stored in the database using selection sort. -->
<!DOCTYPE html>
<html>
<body>
<style>
table, td, th {
border: 1px solid black;
width: 33.3%;
text-align: center;
background-color: lightblue;
border-collapse: collapse;
}
table {
margin: auto;
}
</style>
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="weblab";
$a = [];
// Create a connection
// Opens a new connection to the MySQL server
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection and return the error description from the last connection error, if any.
if($conn->connect_error)
die("Connection failed: " . $conn->connect_error());
$sql = "SELECT * FROM student";
// Performs a query against the database
$result = $conn->query($sql);
echo "<br>";
echo "<center> BEFORE SORTING </center>";
echo "<table border='2'>";
echo "<tr>";
echo "<th> USN </th> <th> Name </th> <th> Address </th>";
echo "</tr>";
if($result->num_rows > 0) // If returned result has some data
{
// Outputs data of each row and fetches result row as an associative array
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["usn"] . "</td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["addr"] . "</td>";
echo "</tr>";
array_push($a, $row["usn"]); // Insert element to end of array
}
}
else
echo "Table is empty";
echo "</table>";
$n = count($a);
$b = $a;
// Perform selection sort
for($i=0; $i<($n-1); $i++) {
$pos = $i;
for($j=$i+1; $j<$n; $j++) {
if($a[$pos] > $a[$j])
$pos = $j;
}
if($pos != $i) {
$temp = $a[$i];
$a[$i] = $a[$pos];
$a[$pos] = $temp;
}
}
$c = [];
$d = [];
$result = $conn->query($sql);
// Output data of each row
if($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
for($i=0; $i<$n; $i++) {
if($row["usn"] == $a[$i]) {
$c[$i] = $row["name"];
$d[$i] = $row["addr"];
}
}
}
}
echo "<br>";
echo "<center> AFTER SORTING </center>";
echo "<table border='2'>";
echo "<tr>";
echo "<th> USN </th> <th> Name </th> <th> Address </th>";
echo "</tr>";
for($i=0; $i<$n; $i++) {
echo "<tr>";
echo "<td>" . $a[$i] . "</td>";
echo "<td>" . $c[$i] . "</td>";
echo "<td>" . $d[$i] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close the connection
$conn->close();
?>
</body>
</html>
|
Java
|
UTF-8
| 824 | 3.453125 | 3 |
[] |
no_license
|
/*Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum โฅ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). */
Solution:
class Solution
{
public int minSubArrayLen(int s, int[] a) {
if (a == null || a.length == 0)
return 0;
int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;
while (j < a.length) {
sum += a[j++];
while (sum >= s) {
min = Math.min(min, j - i);
sum -= a[i++];
}
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}
|
C
|
UTF-8
| 107 | 2.5625 | 3 |
[] |
no_license
|
#include <stdio.h>
double putchard(double v) {
putchar((char) v);
fflush(stdout);
return 0;
}
|
JavaScript
|
UTF-8
| 672 | 3.40625 | 3 |
[] |
no_license
|
// assume div.json with a pre inside
var inJson = document.getElementById("json").textContent;
console.log("inJson: "+inJson);
// same, assume div.cbor with a pre inside
document.getElementById("cbor").insertAdjacentText("beforeend", inJson);
var encoded = new Uint8Array(CBOR.encode(inJson));
var hexArray = [];
for (var i=0; i< encoded.byteLength; i++) {
hexArray.push(byteToHex(encoded[i]));
}
document.getElementById("cborbytes").insertAdjacentText("beforeend", hexArray.join(" "));
document.getElementById("cborbytesize").insertAdjacentText("beforeend", hexArray.length);
function byteToHex(b) {
return (b >>> 4).toString(16)+(b & 0xF).toString(16)+" ";
}
|
Markdown
|
UTF-8
| 4,572 | 2.625 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: ะะปะฐัั CConstantTransition
ms.date: 11/04/2016
f1_keywords:
- CConstantTransition
- AFXANIMATIONCONTROLLER/CConstantTransition
- AFXANIMATIONCONTROLLER/CConstantTransition::CConstantTransition
- AFXANIMATIONCONTROLLER/CConstantTransition::Create
- AFXANIMATIONCONTROLLER/CConstantTransition::m_duration
helpviewer_keywords:
- CConstantTransition [MFC], CConstantTransition
- CConstantTransition [MFC], Create
- CConstantTransition [MFC], m_duration
ms.assetid: f6fa4780-a71b-4cd6-80aa-d4792ace36c2
ms.openlocfilehash: 9641af2f184d2edaa82922363dff75783e79f87e
ms.sourcegitcommit: c3093251193944840e3d0a068ecc30e6449624ba
ms.translationtype: MT
ms.contentlocale: ru-RU
ms.lasthandoff: 03/04/2019
ms.locfileid: "57326339"
---
# <a name="cconstanttransition-class"></a>ะะปะฐัั CConstantTransition
ะะฝะบะฐะฟััะปะธััะตั ะฟะพััะพัะฝะฝัะน ะฟะตัะตั
ะพะด.
## <a name="syntax"></a>ะกะธะฝัะฐะบัะธั
```
class CConstantTransition : public CBaseTransition;
```
## <a name="members"></a>ะฃัะฐััะฝะธะบะธ
### <a name="public-constructors"></a>ะัะบััััะต ะบะพะฝััััะบัะพัั
|ะะผั|ะะฟะธัะฐะฝะธะต|
|----------|-----------------|
|[CConstantTransition::CConstantTransition](#cconstanttransition)|ะกะพะทะดะฐะตั ะพะฑัะตะบั ะฟะตัะตั
ะพะดะฐ ะธ ะธะฝะธัะธะฐะปะธะทะธััะตั ะตะณะพ ะดะปะธัะตะปัะฝะพััั.|
### <a name="public-methods"></a>ะัะบััััะต ะผะตัะพะดั
|ะะผั|ะะฟะธัะฐะฝะธะต|
|----------|-----------------|
|[CConstantTransition::Create](#create)|ะัะทัะฒะฐะตั ะฟะตัะตั
ะพะด ะฑะธะฑะปะธะพัะตะบั ะดะปั ัะพะทะดะฐะฝะธั ะธะฝะบะฐะฟััะปะธัะพะฒะฐะฝะฝัะน ะฟะตัะตั
ะพะดะฐ COM-ะพะฑัะตะบัะฐ. (ะะตัะตะพะฟัะตะดะตะปัะตั [CBaseTransition::Create](../../mfc/reference/cbasetransition-class.md#create).)|
### <a name="public-data-members"></a>ะัะบััััะต ัะปะตะฝั ะดะฐะฝะฝัั
|ะะผั|ะะฟะธัะฐะฝะธะต|
|----------|-----------------|
|[CConstantTransition::m_duration](#m_duration)|ะะปะธัะตะปัะฝะพััั ะฟะตัะตั
ะพะดะฐ.|
## <a name="remarks"></a>ะัะธะผะตัะฐะฝะธั
ะะพ ะฒัะตะผั ะฟะตัะตั
ะพะดะฐ ะบะพะฝััะฐะฝัะฐ ะทะฝะฐัะตะฝะธะต ะฟะตัะตะผะตะฝะฝะพะน ะฐะฝะธะผะฐัะธะธ ะพััะฐะตััั ะฒ ะฝะฐัะฐะปัะฝะพะต ะทะฝะฐัะตะฝะธะต ะฝะฐ ะฟัะพััะถะตะฝะธะธ ะฟะตัะตั
ะพะดะฐ. ะขะฐะบ ะบะฐะบ ะฐะฒัะพะผะฐัะธัะตัะบะธ ัะดะฐะปััััั ะฒัะต ะฟะตัะตั
ะพะดั, ัะตะบะพะผะตะฝะดัะตััั ะฒัะดะตะปะธัั ะธั
ั ะฟะพะผะพััั ะพะฟะตัะฐัะพัะฐ new. ะะฝะบะฐะฟััะปะธัะพะฒะฐะฝะฝัะน ะพะฑัะตะบั IUIAnimationTransition COM ัะพะทะดะฐะฝะฝัะน CAnimationController::AnimateGroup, ะฟะพะบะฐ ัะพ ะฒะพะทะฒัะฐัะฐะตััั ะทะฝะฐัะตะฝะธะต NULL. ะะทะผะตะฝะตะฝะธะต ะฟะตัะตะผะตะฝะฝัั
-ัะปะตะฝะพะฒ, ะฟะพัะปะต ัะพะทะดะฐะฝะธั COM-ะพะฑัะตะบัะฐ ะฝะต ะพะบะฐะทัะฒะฐะตั ะฒะปะธัะฝะธั.
## <a name="inheritance-hierarchy"></a>ะะตัะฐัั
ะธั ะฝะฐัะปะตะดะพะฒะฐะฝะธั
[CObject](../../mfc/reference/cobject-class.md)
[CBaseTransition](../../mfc/reference/cbasetransition-class.md)
`CConstantTransition`
## <a name="requirements"></a>ะขัะตะฑะพะฒะฐะฝะธั
**ะะฐะณะพะปะพะฒะพะบ:** afxanimationcontroller.h
## <a name="cconstanttransition"></a> CConstantTransition::CConstantTransition
ะกะพะทะดะฐะตั ะพะฑัะตะบั ะฟะตัะตั
ะพะดะฐ ะธ ะธะฝะธัะธะฐะปะธะทะธััะตั ะตะณะพ ะดะปะธัะตะปัะฝะพััั.
```
CConstantTransition (UI_ANIMATION_SECONDS duration);
```
### <a name="parameters"></a>ะะฐัะฐะผะตััั
*ะะปะธัะตะปัะฝะพััั*<br/>
ะะปะธัะตะปัะฝะพััั ะฟะตัะตั
ะพะดะฐ.
## <a name="create"></a> CConstantTransition::Create
ะัะทัะฒะฐะตั ะฟะตัะตั
ะพะด ะฑะธะฑะปะธะพัะตะบั ะดะปั ัะพะทะดะฐะฝะธั ะธะฝะบะฐะฟััะปะธัะพะฒะฐะฝะฝัะน ะฟะตัะตั
ะพะดะฐ COM-ะพะฑัะตะบัะฐ.
```
virtual BOOL Create(
IUIAnimationTransitionLibrary* pLibrary,
IUIAnimationTransitionFactory* \*not used*\);
```
### <a name="parameters"></a>ะะฐัะฐะผะตััั
*pLibrary*<br/>
ะฃะบะฐะทะฐัะตะปั ะฝะฐ [IUIAnimationTransitionLibrary ะธะฝัะตััะตะนั](/windows/desktop/api/uianimation/nn-uianimation-iuianimationtransitionlibrary), ะบะพัะพััะน ะพะฟัะตะดะตะปัะตั ะฑะธะฑะปะธะพัะตะบั ััะฐะฝะดะฐััะฝัั
ะฟะตัะตั
ะพะดะพะฒ.
### <a name="return-value"></a>ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต
ะะฝะฐัะตะฝะธะต TRUE, ะตัะปะธ ะฟะตัะตั
ะพะด ัะพะทะดะฐะฝ ััะฟะตัะฝะพ; ะฒ ะฟัะพัะธะฒะฝะพะผ ัะปััะฐะต โ ะทะฝะฐัะตะฝะธะต FALSE.
## <a name="m_duration"></a> CConstantTransition::m_duration
ะะปะธัะตะปัะฝะพััั ะฟะตัะตั
ะพะดะฐ.
```
UI_ANIMATION_SECONDS m_duration;
```
## <a name="see-also"></a>ะกะผ. ัะฐะบะถะต
[ะะปะฐััั](../../mfc/reference/mfc-classes.md)
|
Markdown
|
UTF-8
| 18,941 | 3.171875 | 3 |
[
"Apache-2.0"
] |
permissive
|
[TOC]
# ็ก
่ฐท - NIO
## Java NIO ็ฎไป
```shell
# Java NIO <New IO> ๆฏไป Java1.4 ็ๆฌๅผๅงๅผๅ
ฅ็ไธไธชๆฐ็IO Api๏ผๅฏไปฅๆฟไปฃๆ ๅ็ Java IO Apiใ
# NIO ไธๅๆฅ็ IO ๆๅๆ ท็ไฝ็จๅ็ฎ็๏ผไฝๆฏไฝฟ็จ็ๆนๅผๅฎๅ
จไธๅ๏ผNIO ๆฏๆ้ขๅ็ผๅฒๅบ็ใๅบไบ้้็ IO ๆไฝใ NIO ๅฐไปฅๆดๅ ้ซๆ็ๆนๅผ่ฟ่กๆไปถ็่ฏปๅๆไฝใ
```
## NIO ไธ IO ็ไธป่ฆๅบๅซ
| IO | NIO |
| ------------------------- | ----------------------------- |
| ้ขๅๆต๏ผStream Oriented๏ผ | ้ขๅ็ผๅฒๅบ๏ผBuffer Oriented๏ผ |
| ้ปๅกIO๏ผBloking IO๏ผ | ้้ปๅกIO๏ผNon Bloking IO๏ผ |
| ๏ผๆ ๏ผ | ้ๆฉๅจ๏ผSelectors๏ผ |
## ้้ไธ็ผๅฒๅบ
```shell
# Java NIO ็ณป็ป็ๆ ธๅฟ
# ้้่กจ็คบๆๅผๅฐ IO ่ฎพๅค<ไพๅฆ: ๆไปถใๅฅๆฅๅญ> ็่ฟๆฅใ
# ไฝฟ็จ NIO๏ผ้่ฆ่ทๅ็จไบ่ฟๆฅ IO ่ฎพๅค็้้ไปฅๅ็จไบๅฎน็บณๆฐๆฎ็็ผๅฒๅบใ
# ็ถๅๆไฝ็ผๅฒๅบ๏ผๅฏนๆฐๆฎ่ฟ่กๅค็ใ
# ็ฎ่่จไน: Channel ่ด่ดฃไผ ่พ๏ผBuffer ่ด่ดฃๅญๅจ
```
### ็ผๅฒๅบ
```shell
# Buffer:
# ไธไธช็จไบ็นๅฎๅบๆฌๆฐๆฎ็ฑปๅ็ๅฎนๅจใ็ฑ java.nio ๅ
ๅฎไน๏ผๆๆ็ผๅฒๅบ้ฝๆฏ Buffer ๆฝ่ฑก็ฑป็ๅญ็ฑป
# ไธป่ฆ็จไบไธ NIO ้้่ฟ่กไบคไบ๏ผๆฐๆฎไป้้่ฏปๅ
ฅ็ผๅฒๅบ๏ผไป็ผๅฒๅบๅๅ
ฅ้้ไธญ
# Buffer ๅฐฑๅไธไธชๆฐ็ป๏ผๅฏไปฅไฟๅญๅคไธช็ธๅ็ฑปๅ็ๆฐๆฎใ
# Buffer ๅธธ็จๅญ็ฑป:
# ByteBuffer
# CharBuffer
# ShortBuffer
# IntBuffer
# LongBuffer
# FloatBuffer
# DoubleBuffer
# ๆๆBuffer ๅญ็ฑป้ฝ้็จ็ธไผผ็ๆนๆณ่ฟ่ก็ฎก็ๆฐๆฎ๏ผๅชๆฏๅ่ช็็ฎก็ๆฐๆฎ็ฑปๅไธๅใ
# ่ทๅBuffer ๅฏน่ฑก็ๆนๆณ:
# static XxxBuffer allocate(int capacity)
# ๅๅปบไธไธชๅฎน้ไธบ capacity ็XxxBuffer ๅฏน่ฑก
```
#### Buffer ไธญ็้่ฆๆฆๅฟต
```shell
# ๅฎน้<capacity>:
# ่กจ็คบ Buffer ๆๅคงๆฐๆฎๅฎน้๏ผ็ผๅฒๅบๅฎน้ไธ่ฝไธบ่ด๏ผๅนถไธๅๅปบๅไธ่ฝๆดๆนใ
# ้ๅถ<limit>:
# ็ฌฌไธไธชไธๅบ่ฏฅ่ฏปๅๆๅๅ
ฅ็ๆฐๆฎ็็ดขๅผ๏ผๅณไฝไบ limit ๅ็ๆฐๆฎไธๅฏ่ฏปๅใ
# ็ผๅฒๅบ็้ๅถไธ่ฝไธบ่ด๏ผๅนถไธไธ่ฝๅคงไบๅ
ถๅฎน้ใ
# ไฝ็ฝฎ<position>:
# ไธไธไธช่ฆ่ฏปๅๆๅๅ
ฅ็ๆฐๆฎ็็ดขๅผใ
# ็ผๅฒๅบ็ไฝ็ฝฎไธ่ฝไธบ่ด๏ผๅนถไธไธ่ฝๅคงไบๅ
ถ้ๅถใ
# ๆ ่ฎฐไธ้็ฝฎ<mark And reset>
# ๆ ่ฎฐๆฏไธไธช็ดขๅผ๏ผ้่ฟ Buffer ไธญ็ mark() ๆนๆณๆๅฎ Buffer ไธญไธไธช็นๅฎ็ position๏ผไนๅๅฏไปฅ้่ฟ่ฐ็จ reset() ๆนๆณๆขๅคๅฐ่ฟไธช positionใ
# ๆ ่ฎฐใไฝ็ฝฎใ้ๅถใๅฎน้ ้ตๅพชไปฅไธไธๅๅผ:
# 0 <= mark <= position <= limit <= capacity
```
#### Buffer ็ๅธธ็จๆนๆณ
```shell
# Buffer clear():
# ๆธ
็ฉบ็ผๅฒๅบๅนถ่ฟๅๅฏน็ผๅฒๅบ็ๅผ็จใ
# Buffer flip():
# ๅฐ็ผๅฒๅบ็็้่ฎพ็ฝฎไธบๅฝๅไฝ็ฝฎ๏ผๅนถๅฐๅฝๅไฝ็ฝฎ้็ฝฎไธบ0
# int capacity():
# ่ฟๅ Buffer ็ capacity ๅคงๅฐ
# boolean hasRemaining():
# ๅคๆญ็ผๅฒๅบไธญๆฏๅฆ่ฟๆๅ
็ด
# int limit():
# ่ฟๅ Buffer ็็้<limit> ็ไฝ็ฝฎ
# Buffer limit(int n):
# ๅฐ่ฎพ็ฝฎ็ผๅฒๅบ็้ไธบ n๏ผๅนถ่ฟๅไธไธชๅ
ทๆๆฐ limit ็็ผๅฒๅบๅฏน่ฑก
# Buffer mark():
# ๅฏน็ผๅฒๅบ่ฎพ็ฝฎๆ ่ฎฐ
# int position():
# ่ฟๅ็ผๅฒๅบ็ๅฝๅไฝ็ฝฎ position
# Buffer position(int n):
# ๅฐ่ฎพ็ฝฎ็ผๅฒๅบ็ๅฝๅไฝ็ฝฎไธบ n๏ผๅนถ่ฟๅไฟฎๆนๅ็ Buffer ๅฏน่ฑก
# int reamining():
# ่ฟๅ position ๅฐ limit ไน้ด็ๅ
็ด ไธชๆฐ
# Buffer reset():
# ๅฐไฝ็ฝฎ position ่ฝฌๅฐไปฅๅ่ฎพ็ฝฎ็ mark ๆๅจ็ไฝ็ฝฎ
# Buffer rewind():
# ๅฐไฝ็ฝฎ่ฎพไธบ0๏ผๅๆถ่ฎพ็ฝฎ็ mark
```
#### ็ผๅฒๅบ็ๆฐๆฎๆไฝ
```shell
# Buffer ๆๆๅญ็ฑปๆไพไบไธคไธช็จไบๆฐๆฎๆไฝ็ๆนๆณ:
# get()
# put()
# ่ทๅ Buffer ไธญ็ๆฐๆฎ:
# get(): ่ฏปๅๅไธชๅญ่
# get(byte[] dst): ๆน้่ฏปๅๅคไธชๅญ่ๅฐ dst ไธญ
# get(int index): ่ฏปๅๆๅฎ็ดขๅผไฝ็ฝฎ็ๅญ่(ไธไผ็งปๅจ position)
# ๆพๅ
ฅๆฐๆฎๅฐ Buffer ไธญ:
# put(byte b): ๅฐ็ปๅฎๅไธชๅญ่ๅๅ
ฅ็ผๅฒๅบ็ๅฝๅไฝ็ฝฎ
# put(byte[] src): ๅฐ src ไธญ็ๅญ่ๅๅ
ฅ็ผๅฒๅบ็ๅฝๅไฝ็ฝฎ
# put(int index, byte b): ๅฐๆๅฎๅญ่ๅๅ
ฅ็ผๅฒๅบ็็ดขๅผไฝ็ฝฎ(ไธไผ็งปๅจ position)
```
#### ็ดๆฅไธ้็ดๆฅ็ผๅฒๅบ
```shell
# ๅญ่็ผๅฒๅบ่ฆไนๆฏ็ดๆฅ็๏ผ่ฆไนๆฏ้็ดๆฅ็ใ
# ็ดๆฅๅญ่็ผๅฒๅบ:
# JVM ไผๅฐฝๆๅคงๅชๅ็ดๆฅๅจๆญค็ผๅฒๅบไธๆง่กๆฌๆบ I/O ๆไฝใ
# ๆฏๆฌก่ฐ็จๅบ็กๆไฝ็ณป็ป็ไธไธชๆฌๆบ I/O ๆไฝไนๅ(ๆไนๅ)๏ผJVM ้ฝไผๅฐฝ้้ฟๅ
ๅฐ็ผๅฒๅบ็ๅ
ๅฎนๅคๅถๅฐไธญ้ด็ผๅฒๅบไธญใ(ๆไปไธญ้ด็ผๅฒๅบไธญๅคๅถๅ
ๅฎน)
# ็ดๆฅๅญ่็ผๅฒๅบๅฏไปฅ้่ฟๆญค็ฑป็ allocateDirect() ๅทฅๅๆนๆณๆฅๅๅปบ๏ผๆญคๆนๆณ่ฟๅ็็ผๅฒๅบ่ฟ่กๅ้
ๅๅๆถๅ้
ๆ้ๆๆฌ้ๅธธ้ซไบ้็ดๆฅ็ผๅฒๅบใ
# ็ดๆฅ็ผๅฒๅบ็ๅ
ๅฎนๅฏไปฅ้ฉป็ๅจ JVM ๅธธ่ง็ๅๅพๅๆถๅ ไนๅค๏ผๅ ๆญค๏ผๅฎไปฌๅฏน Application ็ๅ
ๅญ้ๆฑ้้ ๆ็ๅฝฑๅๅฏ่ฝๅนถไธๆๆพใๆไปฅ๏ผๅปบ่ฎฎๅฐ็ดๆฅ็ผๅฒๅบไธป่ฆๅ้
็ป้ฃไบๆๅๅบ็กๆไฝ็ณป็ป็ๆฌๆบ I/O ๆไฝๅฝฑๅ็ๅคงๅใๆไน
็็ผๅฒๅบใ
# ไธ่ฌๆ
ๅตไธ๏ผๆๅฅฝไป
ๅจ็ดๆฅ็ผๅฒๅบ่ฝๅจ็จๅบๆง่ฝๆน้ขๅธฆๆฅๆๆพๅฅฝๅคๆถๅ้
ๅฎไปฌใ
# ็ดๆฅๅญ่็ผๅฒๅบ่ฟๅฏไปฅ้่ฟ FileChannel ็ map() ๆนๆณๅฐๆไปถๅบๅ็ดๆฅๆ ๅฐๅฐๅ
ๅญไธญๆฅๅๅปบใ่ฏฅๆนๆณ่ฟๅ MappedByteBuffer๏ผJava ๅนณๅฐ็ๅฎ็ฐๆๅฉไบ้่ฟ JNI ไปๆฌๆบไปฃ็ ๅๅปบ็ดๆฅๅญ่็ผๅฒๅบใๅฆๆไปฅไธ่ฟไบ็ผๅฒๅบไธญ็ๆไธช็ผๅฒๅบๅฎไพๆ็ๆฏไธๅฏ่ฎฟ้ฎ็ๅ
ๅญๅบๅ๏ผๅ่ฏๅพๆพ้ฎ่ฏฅๅบๅไธไผๆดๆน็ผๅฒๅบ็ๅ
ๅฎน๏ผๅนถไธๅฐไผๅจ่ฎฟ้ฎๆ้ดๆ็จๅ็ๆไธชๆถ้ดๅฏผ่ดๆๅบไธ็กฎๅฎ็ๅผๅธธใ
# ๅญ่็ผๅฒๅบๆฏ็ดๆฅ็ผๅฒๅบ่ฟๆฏ้็ดๆฅ็ผๅฒๅบๅฏ้่ฟ่ฐ็จๅ
ถ isDirect() ๆนๆณๆฅ็กฎๅฎ๏ผๆไพๆญคๆนๆณๆฏไธบไบ่ฝๅคๅจๆง่ฝๅ
ณ้ฎๆงไปฃ็ ไธญๆง่กๆพ็คบ็ผๅฒๅบ็ฎก็ใ
```


### ้้
```shell
# Channel:
# java.nio.channels ๅ
ๅฎไนใ
# ่กจ็คบ IO ๆบไบ็ฎๆ ๆๅผ็่ฟๆฅใ
# ็ฑปไผผไผ ็ป็ "ๆต"ใๅชไธ่ฟๆฌ่บซไธ่ฝ็ดๆฅ่ฎฟ้ฎๆฐๆฎ๏ผๅช่ฝไธ Buffer ่ฟ่กไบคไบใ
```

#### ไธป่ฆๅฎ็ฐ็ฑป
```shell
# FileChannel:
# ็จไบ่ฏปๅใๅๅ
ฅใๆ ๅฐๅๆไฝๆไปถ็้้ใ
# DatagramChannel:
# ้่ฟ UDP ่ฏปๅ็ฝ็ปไธญ็ๆฐๆฎ้้ใ
# SocketChannel:
# ้่ฟ TCP ่ฏปๅ็ฝ็ปไธญ็ๆฐๆฎใ
# ServerSocketChannel:
# ๅฏไปฅ็ๅฌๆฐ่ฟๆฅ็ TCP ่ฟๆฅ๏ผๅฏนๆฏไธไธชๆฐ่ฟๆฅ็่ฟๆฅ้ฝไผๅๅปบไธไธช SocketChannelใ
```
#### ่ทๅ้้
```shell
# ่ทๅ้้็ไธ็งๆนๅผๆฏๅฏนๆฏๆ้้็ๅฏน่ฑก่ฐ็จ getChannel() ๆนๆณ๏ผๆฏๆ้้็็ฑปๆ:
# FileInputStream
# FileOutputStream
# RandomAccessFile
# DatagramSocket
# Socket
# ServerSocket
# ่ทๅ้้็ๅ
ถไปๆนๅผๆฏไฝฟ็จ Files ็ฑป็้ๆๆนๆณ๏ผnewByteChannel() ่ทๅๅญ่้้ใๆ่
้่ฟ้้็้ๆๆนๆณ open() ๆๅผๅนถ่ฟๅๆๅฎ้้ใ
```
#### ้้็ๆฐๆฎไผ ่พ
```shell
# ๅฐ Buffer ไธญๆฐๆฎๅๅ
ฅ Channel
# ไพๅฆ: int bytesWritten = inChannel.write(buf);
# ไป Channel ่ฏปๅๆฐๆฎๅฐ Buffer
# ไพๅฆ: int bytesRead = inChannel.read(buf);
```
#### ๅๆฃๅ่้
```shell
# ๅๆฃ่ฏปๅ<Scattering Reads> ๆฏๆไป Channel ไธญ่ฏปๅ็ๆฐๆฎๅๆฃๅฐๅคไธช Buffer ไธญ
# ๆณจๆ: ๆ็
ง็ผๅฒๅบ็้กบๅบ๏ผไป Channel ไธญ่ฏปๅ็ๆฐๆฎไพๆฌกๅฐ Buffer ๅกซๆปกใ
# ่้ๅๅ
ฅ<Gathering Writes> ๆฏๆๅฐๅคไธช Buffer ไธญ็ๆฐๆฎ"่้" ๅฐ Channelใ
# ๆณจๆ: ๆ็
ง็ผๅฒๅบ็้กบๅบ๏ผๅๅ
ฅ position ๅ limit ไน้ด็ๆฐๆฎๅฐ Channelใ
```
#### transferFrom()
```shell
# ๅฐๆฐๆฎไปๆบ้้ไผ ่พๅฐๅ
ถไป Channel ไธญ:
```
```java
RandomAccessFile fromFile = new RandomAccessFile("data/fromFile.txt","rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("data/toFile.txt","rw");
FileChannel toChannel = toFile.getChannel();
// ๅฎไนไผ ่พไฝ็ฝฎ
long position = 0L;
// ๆๅคไผ ่พ็ๅญ่ๆฐ
long count = fromChannel.size();
// ๅฐๆฐๆฎไปๆบ้้ไผ ่พๅฐๅฆไธไธช้้
toChannel.transferFrom(fromChannel, count, position);
```
#### transferTo()
```shell
# ๅฐๆฐๆฎไปๆบ้้ไผ ่พๅฐๅฆไธไธช้้
# ไธ่ฟฐไปฃ็ ๆๅไธๅฅๅ็ๅๅ:
fromChannel.transferTo(position, count, toChannel);
```
#### FileChannel ็ๅธธ็จๆนๆณ
| ๆนๆณ | ๆ่ฟฐ |
| ----------------------------- | -------------------------------------------- |
| int read(ByteBuffer dst) | ไปChannel ไธญ่ฏปๅๆฐๆฎๅฐ ByteBuffer |
| long read(ByteBuffer[] dsts) | ๅฐChannel ไธญ็ๆฐๆฎ"ๅๆฃ"ๅฐ ByteBuffer[] |
| int write(ByteBuffer src) | ๅฐByteBuffer ไธญ็ๆฐๆฎๅๅ
ฅๅฐ Channel |
| long write(ByteBuffer[] srcs) | ๅฐByteBuffer[] ไธญๆฐๆฎ"่้" ๅฐ Channel |
| long position() | ่ฟๅๆญค้้็ๆไปถไฝ็ฝฎ |
| FileChannel position(long p) | ่ฎพ็ฝฎๆญค้้็ๆไปถไฝ็ฝฎ |
| long size() | ่ฟๅๆญค้้็ๆไปถ็ๅฝๅๅคงๅฐ |
| FileChannel truncate(long s) | ๅฐๆญค้้็ๆไปถๆชๅไธบ็ปๅฎๅคงๅฐ |
| void force(boolean metaData) | ๅผบๅถๅฐๆๆๅฏนๆญค้้็ๆไปถๆดๆฐๅๅ
ฅๅฐๅญๅจ่ฎพๅคไธญ |
## NIO ็้้ปๅกๅผ็ฝ็ป้ไฟก
### ้ปๅกไธ้้ปๅก
```shell
# ไผ ็ป็ IO ๆต้ฝๆฏ้ปๅกๅผ็๏ผๅฝไธไธช็บฟ็จ่ฐ็จ read() ๆ write() ๆถ๏ผ่ฏฅ็บฟ็จ่ขซ้ปๅก๏ผ็ดๅฐๆไธไบๆฐๆฎ่ขซ่ฏปๅๆๅๅ
ฅ๏ผ่ฏฅ็บฟ็จๅจๆญคๆ้ดไธ่ฝๆง่กๅ
ถไปไปปๅกใ
# ๅ ๆญค๏ผๅจๅฎๆ็ฝ็ป้ไฟก่ฟ่ก IO ๆไฝๆถ๏ผ็ฑไบ็บฟ็จไผ้ปๅก๏ผๆไปฅๆๅกๅจ็ซฏๅฟ
้กปไธบๆฏไธชๅฎขๆท็ซฏ้ฝๆไพไธไธช็ฌ็ซ็็บฟ็จ่ฟ่กๅค็๏ผๅฝๆๅก็ซฏ้่ฆๅค็ๅคง้ๅฎขๆท็ซฏๆถ๏ผๆง่ฝๆฅๅงไธ้ใ
# NIO ๆฏ้้ปๅกๆจกๅผ็ใๅฝ็บฟ็จไปๆ้้่ฟ่ก่ฏปๅๆฐๆฎๆถ๏ผ่ฅๆฒกๆๆฐๆฎๅฏ็จๆถ๏ผ่ฏฅ็บฟ็จๅฏไปฅ่ฟ่กๅ
ถไปไปปๅกใ็บฟ็จ้ๅธธๅฐ้้ปๅก IO ็็ฉบ้ฒๆถ้ด็จไบๅจๅ
ถไป้้ไธๆง่ก IO ๆไฝ๏ผๆไปฅๅ็ฌ็็บฟ็จๅฏไปฅ็ฎก็ๅคไธช่พๅ
ฅๅ่พๅบ็ฎก้ใๅ ๆญค๏ผNIO ๅฏไปฅ่ฎฉๆๅกๅจ็ซฏไฝฟ็จไธไธชๆๆ้ๅ ไธช็บฟ็จๆฅๅๆถๅค็่ฟๆฅๅฐๆๅกๅจ็ซฏ็ๆๆๅฎขๆท็ซฏใ
```
### ้ๆฉๅจ
```shell
# Selector ๆฏ SelectableChannel ๅฏน่ฑก็ๅค่ทฏๅค็จๅจ๏ผSelector ๅฏไปฅๅๆถ็ๆงๅคไธช SelectableChannel ็IO ็ถๅต๏ผไนๅฐฑๆฏ่ฏด๏ผๅฉ็จ Selector ๅฏไฝฟไธไธชๅ็ฌ็็บฟ็จ็ฎก็ๅคไธช ChannelใSelector ๆฏ้้ปๅก IO ็ๆ ธๅฟใ
```
#### SelectableChannel ็ปๆๅพ

#### ้ๆฉๅจ็ๅบ็จ
```java
// ๅๅปบ Selector
Selector selector = Selector.open();
// ๅ้ๆฉๅจๆณจๅ้้
// ๅๅปบไธไธช Socket ๅฅๆฅๅญ
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9898);
// ่ทๅ SocketChannel
SocketChannel channel = socket.getChannel();
// ๅฐ SocketChannel ๅๆขๅฐ้้ปๅกๆจกๅผ
channel.configureBlocking(false);
/**
* ๅ Selector ๆณจๅ Channel
* ๅฝ่ฐ็จ register(Selector,int ops) ๅฐ้้ๆณจๅ้ๆฉๅจๆถ๏ผ้ๆฉๅจๅฏน้้็็ๅฌไบไปถ๏ผ้่ฆ้่ฟ็ฌฌ
* ไบไธชๅๆฐ ops ๆๅฎใ
* ๅฏไปฅ็ๅฌ็ไบไปถ็ฑปๅ(ๅฏไฝฟ็จ SelectionKey ็ๅไธชๅธธ้่กจ็คบ):
* ่ฏป: SelectionKey.OP_READ
* ๅ: SelectionKey.OP_WRITE
* ่ฟๆฅ: SelectionKey.OP_CONNECT
* ๆฅๆถ: SelectionKey.OP_ACCEPT
* ่ฅๆณจๅๆถไธๆญข็ๅฌไธไธชไบไปถ๏ผๅๅฏไปฅไฝฟ็จ | ๆไฝ็ฌฆ่ฟๆฅ๏ผไพ:
* int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
*/
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
```
#### SelectionKey
```shell
# SelectionKey:
# ่กจ็คบ SelectableChannel ๅ Selector ไน้ด็ๆณจๅๅ
ณ็ณปใๆฏๆฌกๅ้ๆฉๅจๆณจๅ้้ๆถ๏ผๅฐฑไผ้ๆฉไธไธชไบไปถ(้ๆฉ้ฎ)ใ
# ้ๆฉ้ฎๅ
ๅซไธคไธช่กจ็คบไธบๆดๆฐๅผ็ๆไฝ้๏ผๆไฝ้็ๆฏไธไฝ้ฝ่กจ็คบ่ฏฅ้ฎ็้้ๆๆฏๆ็ไธ็ฑปๅฏ้ๆฉๆไฝใ
```
| ๆนๆณ | ๆ่ฟฐ |
| --------------------------- | -------------------------------- |
| int interestOps() | ่ทๅๆๅ
ด่ถฃๆถ้ด้ๅ |
| int readyOps() | ่ทๅ้้ๅทฒ็ปๅๅคๅฐฑ็ปช็ๆไฝ็้ๅ |
| SelectableChannel channel() | ่ทๅๆณจๅ้้ |
| Selector selector() | ่ฟๅ้ๆฉๅจ |
| boolean isReadable() | ๆฃๆต Channel ไธญ่ฏปไบไปถๆฏๅฆๅฐฑ็ปช |
| boolean isWritable() | ๆฃๆต Channel ไธญๅไบไปถๆฏๅฆๅฐฑ็ปช |
| boolean isConnectable() | ๆฃๆต Channel ไธญ่ฟๆฅๆฏๅฆๅฐฑ็ปช |
| boolean isAcceptable() | ๆฃๆต Channel ไธญๆฅๆถๆฏๅฆๅฐฑ็ปช |
#### Selector ็ๅธธ็จๆนๆณ
| ๆนๆณ | ๆ่ฟฐ |
| ------------------------ | ------------------------------------------------------------ |
| Set<SelectionKey> keys() | ๆๆ็ SelectionKey ้ๅ๏ผไปฃ่กจๆณจๅๅจ่ฏฅ Selector ไธ็ Channel |
| selectedKeys() | ่ขซ้ๆฉ็SelectionKey ้ๅ๏ผ่ฟๅๆญค Selector ็ๅทฒ้ๆฉ้ฎ้ |
| int select() | ็ๆตๆๆๆณจๅ็ Channel๏ผๅฝๅฎไปฌไธญ้ดๆ้่ฆๅค็็ IO ๆไฝๆถ๏ผ่ฏฅๆนๆณ่ฟๅ๏ผๅนถๅฐๅฏนๅบ็ SelectionKey ๅ ๅ
ฅ่ขซ้ๆฉ็ SelectionKey ้ๅไธญ๏ผ่ฏฅๆนๆณ่ฟๅ่ฟไบ Channel ็ๆฐ้ใ |
| int select(long timeout) | ๅฏไปฅ่ฎพ็ฝฎ่ถ
ๆถๆถ้ฟ็ select() ๆไฝ |
| int selectNow() | ๆง่กไธไธช็ซๅณ่ฟๅ็ select() ๆไฝ๏ผ่ฏฅๆนๆณไธไผ้ปๅก็บฟ็จ |
| Selector wakeup() | ไฝฟไธไธช่ฟๆช่ฟๅ็ select() ๆนๆณ็ซๅณ่ฟๅ |
| void close() | ๅ
ณ้ญ่ฏฅ้ๆฉๅจ |
### SocketChannel
```shell
# Java NIO ไธญ็ SocketChannel ๆฏไธไธช่ฟๆฅๅฐ TCP ็ฝ็ปๅฅๆฅๅญ็้้ใ
# ๆไฝๆญฅ้ชค:
# ๆๅผ SocketChannel
# ่ฏปๅๆฐๆฎ
# ๅ
ณ้ญ SocketChannel
# NIO ไธญ็ ServerSocketChannel ๆฏไธไธชๅฏไปฅ็ๅฌๆฐ่ฟๆฅ็ TCP ่ฟๆฅ็้้๏ผๅฐฑๅๆ ๅ IO ไธญ็ ServerSocket ไธๆ ทใ
```
### DatagramChannel
```shell
# NIO ไธญ็ DatagramChannel ๆฏไธไธช่ฝๆถๅ UDP ๅ
็้้ใ
# ๆไฝๆญฅ้ชค:
# ๆๅผ DatagramChannel
# ๆฅๆถ/ๅ้ๆฐๆฎ
```
### ็ฎก้
```shell
# NIO ็ฎก้ๆฏ2ไธช็บฟ็จไน้ด็ๅๅๆฐๆฎ่ฟๆฅใ
# Pipe ๆไธไธช source ้้ๅไธไธช sink ้้ใ
# ๆฐๆฎไผ่ขซๅๅฐ sink ้้๏ผไป source ้้่ฏปๅใ
```

#### ๅ็ฎก้ๅๆฐๆฎ
```java
@Test
public void test1() throws IOException{
String str = "ๅฟซไน็ไธๅชๅฐ้่";
// ๅๅปบ็ฎก้
Pipe pipe = Pipe.open();
// ๅ็ฎก้ๅ่พๅ
ฅ
Pipe.SinkChannel sinkChannel = pipe.sink();
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
buf.put(str.getBytes());
buf.flip();
while(buf.hasRemaining()){
sinkChannel.write(buf);
}
}
```
#### ไป็ฎก้่ฏปๅๆฐๆฎ
```java
Pipe.SourceChannel sourceChannel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(1024);
sourceChannel.read(buf);
```
## NIO.2 - PathใPathsใFiles
### NIO.2
```shell
# ้็ JDK7 ็ๅๅธ๏ผJava ๅฏน NIO ่ฟ่กไบๆๅคง็ๆฉๅฑ๏ผๅขๅผบไบๅฏนๆไปถๅค็ๅๆไปถ็ณป็ป็นๆง็ๆฏๆ๏ผๅ ๆญค่ขซ็งฐไธบ NIO.2ใ
```
### Path ไธ Paths
```shell
# java.nio.file.Path ๆฅๅฃไปฃ่กจไธไธชๅนณๅฐๆ ๅ
ณ็ๅนณๅฐ่ทฏๅพ๏ผๆ่ฟฐไบ็ฎๅฝ็ปๆไธญๆไปถ็ไฝ็ฝฎใ
# Paths ๆไพ็ get() ๆนๆณ็จๆฅ่ทๅ Path ๅฏน่ฑก
# Path get(String first,String ...more) : ็จไบๅฐๅคไธชๅญ็ฌฆไธฒไธฒ่ๆ่ทฏๅพใ
# Path ๅธธ็จๆนๆณ:
# boolean endsWith(String path): ๅคๆญๆฏๅฆไปฅ path ่ทฏๅพ็ปๆ
# boolean startsWith(String path): ๅคๆญๆฏๅฆไปฅ path ่ทฏๅพๅผๅง
# boolean isAbsolute(): ๅคๆญๆฏๅฆ็ปๅฏน่ทฏๅพ
# Path getFileName(): ่ฟๅไธ่ฐ็จ Path ๅฏน่ฑกๅ
ณ่็ๆไปถๅ
# Path getName(int idx): ่ฟๅ็ๆๅฎ็ดขๅผไฝ็ฝฎ idx ็่ทฏๅพๅ็งฐ
# int getNameCount(): ่ฟๅ Path ๆ น็ฎๅฝๅ้ขๅ
็ด ็ๆฐ้
# Path getParent(): ่ฟๅ Path ๅฏน่ฑกๅ
ๅซๆดไธช่ทฏๅพ๏ผไธๅ
ๅซ Path ๅฏน่ฑกๆๅฎ็ๆไปถ่ทฏๅพ
# Path getRoot(): ่ฟๅ่ฐ็จ Path ๅฏน่ฑก็ๆ น่ทฏๅพ
# Path resolve(Path p): ๅฐ็ธๅฏน่ทฏๅพ่งฃๆไธบ็ปๅฏน่ทฏๅพ
# Path toAbsolutePath(): ไฝไธบ็ปๅฏน่ทฏๅพ่ฟๅ่ฐ็จ Path ๅฏน่ฑก
# String toString(): ่ฟๅ่ฐ็จ Path ๅฏน่ฑก็ๅญ็ฌฆไธฒ่กจ็คบๅฝขๅผ
```
### Files ็ฑป
```shell
# java.nio.file.Files ็จไบๆไฝๆไปถๆ็ฎๅฝ็ๅทฅๅ
ท็ฑป
# Files ๅธธ็จๆนๆณ:
# Path copy(Path src, Path dest, CopyOption ...how): ๆไปถ็ๅคๅถ
# Path createDirectory(Path path,FileAttribute<?> ...attr): ๅๅปบไธไธช็ฎๅฝ
# Path createFile(Path path,FileAttribute<?> ...attr): ๅๅปบไธไธชๆไปถ
# void delete(Path path): ๅ ้คไธไธชๆไปถ
# Path move(Path src, Path dest, CopyOption ...how): ๅฐ src ็งปๅจๅฐ destไฝ็ฝฎ
# long size(Path path): ่ฟๅpath ๆๅฎๆไปถ็ๅคงๅฐ
# Files ๅธธ็จๆนๆณ: ็จไบๅคๆญ
# boolean exists(Path path, LinkOption ...opts): ๅคๆญๆไปถๆฏๅฆๅญๅจ
# boolean isDirectory(Path path, LinkOption ...opts): ๅคๆญๆฏๅฆๆฏ็ฎๅฝ
# boolean isExecutable(Path path): ๅคๆญๆฏๅฆๆฏๅฏๆง่กๆไปถ
# boolean isHidden(Path path): ๅคๆญๆฏๅฆๆฏ้่ๆไปถ
# boolean isReadable(Path path): ๅคๆญๆไปถๆฏๅฆๅฏ่ฏป
# boolean isWritable(Path path): ๅคๆญๆไปถๆฏๅฆๅฏๅ
# boolean notExists(Path path, LinkOption ...opts): ๅคๆญๆไปถๆฏๅฆไธๅญๅจ
# Files ๅธธ็จๆนๆณ: ็จไบๆไฝๅ
ๅฎน
# SeekableByteChannel newByteChannel(Path path,OpenOption ...how): ่ทๅไธๆๅฎๆไปถ็่ฟๆฅ๏ผhow ๆๅฎๆๅผๆนๅผใ
# DirectoryStream newDirectoryStream(Path path): ๆๅผ path ๆๅฎ็็ฎๅฝ
# InputStream newInputStream(Path path, OpenOption ...how): ่ทๅ InputStream ๅฏน่ฑก
# OutputStream newOutputStream(Path path, OpenOption ...how): ่ทๅ OutputStream ๅฏน่ฑก
```
## ่ชๅจ่ตๆบ็ฎก็
```shell
# JDK7 ๅขๅ ไบไธไธชๆฐ็นๆง๏ผ่ฏฅ็นๆงๆไพไบๅฆๅคไธ็ง็ฎก็่ตๆบ็ๆนๅผ๏ผ่ฟ็งๆนๅผ่ฝ่ชๅจๅ
ณ้ญๆไปถใ
```
```java
/**
* ่ชๅจ่ตๆบ็ฎก็ๅบไบ try ่ฏญๅฅ็ๆฉๅฑๅฝขๅผ
* ๅฝ try ไปฃ็ ๅ็ปๆๆถ๏ผ่ชๅจ้ๆพ่ตๆบ๏ผๅ ๆญคไธ้่ฆๆพ็คบ็่ฐ็จ close() ๆนๆณ๏ผ
* ๆณจๆ:
* try ่ฏญๅฅไธญๅฃฐๆ็่ตๆบ่ขซ้ๅผๅฃฐๆไธบ final๏ผ่ตๆบ็ไฝ็จๅฑ้ไบๅธฆ่ตๆบ็ try ่ฏญๅฅ
* ๅฏไปฅๅจไธๆก try ่ฏญๅฅไธญ็ฎก็ๅคไธช่ตๆบ๏ผๆฏไธช่ตๆบไปฅ ":" ้ๅผๅณๅฏ
* ้่ฆๅ
ณ้ญ็่ตๆบ๏ผๅฟ
้กปๅฎ็ฐไบ AutoCloseable ๆฅๅฃๆๅ
ถๅญๆฅๅฃ Closeable
*/
try ("้่ฆๅ
ณ้ญ็่ตๆบๅฃฐๆ") {
// ๅฏ่ฝๅ็ๅผๅธธ็่ฏญๅฅ
} catch ("ๅผๅธธ็ฑปๅ ๅ้ๅ") {
// ๅผๅธธ็ๅค็่ฏญๅฅ
}
......
finally {
// ไธๅฎๆง่ก็่ฏญๅฅ
}
```
###
|
C#
|
UTF-8
| 797 | 2.875 | 3 |
[] |
no_license
|
private async Task<string> ProcessRestMethod(string methodName, string parameters)
{
string result = "";
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string strParams = parameters;
if ((!String.IsNullOrEmpty(parameters)) && (parameters.IndexOf('?') != 0))
strParams = "?" + parameters;
result = await httpClient.GetStringAsync(baseUri + methodName + strParams);
}
if (result == "")
result = "{\"status\":{\"code\":1000,\"message\":\"Unkown Error Ocured\"}}";
return result;
}
|
Markdown
|
UTF-8
| 4,197 | 3.609375 | 4 |
[] |
no_license
|
## LeetCode link(Easy)
https://leetcode.com/problems/largest-time-for-given-digits/
## Keyword
DFS, Permutation
## Problem description
```
Given an array of 4 digits, return the largest 24 hour time that can be made.
The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
Return the answer as a string of length 5. If no valid time can be made, return an empty string.
Example 1:
Input: [1,2,3,4]
Output: "23:41"
Example 2:
Input: [5,5,5,5]
Output: ""
Note:
A.length == 4
0 <= A[i] <= 9
```
## 8/18/2020 DFS
```java
class Solution {
String ans;
public String largestTimeFromDigits(int[] A) {
//compute all permutations of A and find the largest one
ans = null;
List<Integer> digits = new ArrayList<>();
for (int i : A) {
digits.add(i);
}
dfs(digits, new StringBuilder());
return ans == null ? "" : ans;
}
private void dfs(List<Integer> digits, StringBuilder sb) {
//used all digits
if (digits.size() == 0) {
//compare with ans
String res = sb.toString();
if (ans == null) {
ans = res;
return;
}
for (int i = 0; i < 5; ++i) {
if (ans.charAt(i) < res.charAt(i)) {
ans = res;
return;
} else if (ans.charAt(i) > res.charAt(i)) {
return;
}
}
return;
}
//':'
if (sb.length() == 2) {
sb.append(':');
dfs(digits, sb);
sb.deleteCharAt(sb.length() - 1);
return;
}
//pick one legal character for this layer
for (int i = 0; i < digits.size(); ++i) {
//first digit cannot be more than 2
if (sb.length() == 0 && digits.get(i) > 2) {
continue;
}
//first two digits cannot be more than 23
if (sb.length() == 1 && sb.charAt(0) == '2' && digits.get(i) > 3) {
continue;
}
//third digit cannot be more than 5
if (sb.length() == 3 && digits.get(i) > 5) {
continue;
}
// backtracking
List<Integer> next = new ArrayList<>();
for (int j = 0; j < digits.size(); ++j) {
if (j != i) {
next.add(digits.get(j));
}
}
sb.append(digits.get(i));
dfs(next, sb);
sb.deleteCharAt(sb.length() - 1);
}
}
}
```
## Complexity Analyze
Time complexity: O(1)\
Space complexity: O(1)
## Notes
Use dfs to enumerate all permutation and find the largest one.
## Key points
Corner cases: \
API:
```java
class Solution {
private int max_time = -1;
public String largestTimeFromDigits(int[] A) {
this.max_time = -1;
permutate(A, 0);
if (this.max_time == -1)
return "";
else
return String.format("%02d:%02d", max_time / 60, max_time % 60);
}
protected void permutate(int[] array, int start) {
if (start == array.length) {
this.build_time(array);
return;
}
for (int i = start; i < array.length; ++i) {
this.swap(array, i, start);
this.permutate(array, start + 1);
this.swap(array, i, start);
}
}
protected void build_time(int[] perm) {
int hour = perm[0] * 10 + perm[1];
int minute = perm[2] * 10 + perm[3];
if (hour < 24 && minute < 60)
this.max_time = Math.max(this.max_time, hour * 60 + minute);
}
protected void swap(int[] array, int i, int j) {
if (i != j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
```
## Complexity Analyze
Time complexity: O(1)\
Space complexity: O(1)
## Notes
Better permutation.
## Key points
Corner cases: \
API:
|
C#
|
UTF-8
| 932 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
๏ปฟusing Asphalt_9_Materials.Annotations;
using System;
using System.Globalization;
using System.Windows.Data;
namespace Asphalt_9_Materials.ViewModel.Converters
{
public class ToLowerCaseConverter : IValueConverter
{
/// <summary>
/// Convert string to lower case.
/// </summary>
/// <param name="value">Value to convert</param>
/// <param name="targetType"></param>
/// <param name="parameter"></param>
/// <param name="culture"></param>
/// <returns>Lower case string</returns>
public object Convert([CanBeNull] object value, Type targetType, object parameter, CultureInfo culture)
{ return (!string.IsNullOrEmpty(value as string)) ? ((string)value).ToLower() : string.Empty; }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{ throw new NotImplementedException(); }
}
}
|
Swift
|
UTF-8
| 1,070 | 2.90625 | 3 |
[] |
no_license
|
//
// ViewController.swift
// TextFieldDelegate
//
// Created by Hongdonghyun on 2019/12/10.
// Copyright ยฉ 2019 hong3. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
@IBOutlet weak var myTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
myTextField.delegate = self
}
}
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
myTextField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
guard let text = textField.text else { return }
let textColor: [String:UIColor] = ["red": .red, "black": .black, "blue": .blue]
myView.backgroundColor = textColor.keys.contains(text) ? textColor[text] : .gray
}
// func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//
// return true
// }
}
|
Python
|
UTF-8
| 1,506 | 2.59375 | 3 |
[] |
no_license
|
import RPi.GPIO as GPIO
import time
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import messaging
import firebase_admin
cred = credentials.Certificate(
"/home/pi/dev/python/temp_server/check-my-temp-5e3d6-firebase-adminsdk-m5rzd-e70cd0a740.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.IN) # Read output from PIR motion sensor
def get_token():
doc_ref = db.collection(u'tokens').document(u'token')
doc = doc_ref.get()
tokens = doc.to_dict()
token_value = tokens['token']
print(token_value)
return token_value
def send_to_token():
message = messaging.MulticastMessage(
notification=messaging.Notification(
title="MY ROOM",
body="Motion detected in your room"
),
tokens=get_token(),
android=messaging.AndroidConfig(
priority="high"
),
)
try:
response = messaging.send_multicast(message)
except Exception as error:
print(f'Something went wrong: {error}')
return False
else:
print('Successfully sent message:', response)
return True
while True:
i = GPIO.input(8)
if i == 1: # When output from motion sensor is HIGH
print("movement detected")
f = send_to_token()
while(f == False):
f = send_to_token()
time.sleep(2)
time.sleep(120)
|
Java
|
UTF-8
| 137 | 1.679688 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.aditya.meditrack.services;
public class ProductService {
private final String TAG=this.getClass().getSimpleName();
}
|
C#
|
UTF-8
| 4,365 | 3.25 | 3 |
[] |
no_license
|
๏ปฟusing System;
using ADCode.Lists.ArrayList;
using ADCode.Lists.LinkedList;
using ADCode.Lists.Queue;
using ADCode.Lists.Stack;
namespace ADCode.Lists
{
internal class ListProgram
{
public ListProgram()
{
// MyArrayList<int> arrayList = new MyArrayList<int>(4);
// arrayList.Add(1);
// arrayList.Add(2);
// arrayList.Add(3);
// arrayList.Add(4);
// arrayList.Print();
// arrayList.CountOccurences(5);
// arrayList.Set(2, 5);
// arrayList.Print();
// arrayList.Clear();
// arrayList.Add(5);
// arrayList.Print();
//
// MyLinkedList<int> linkedList = new MyLinkedList<int>();
// linkedList.AddFirst(1);
// linkedList.AddFirst(2);
// linkedList.AddFirst(3);
// linkedList.Print();
// linkedList.Insert(3, 5);
// linkedList.Print();
//
// linkedList.RemoveFirst();
// linkedList.Print();
// linkedList.RemoveFirst();
// linkedList.Print();
// linkedList.RemoveFirst();
// linkedList.Print();
// linkedList.RemoveFirst();
// linkedList.Print();
//
// Console.WriteLine(CheckBrackets("((()))"));
// Console.WriteLine(CheckBrackets("(()"));
// Console.WriteLine(CheckBrackets2("([][])()"));
// Console.WriteLine(CheckBrackets2("[()"));
MyQueue<int> myQueue = new MyQueue<int>();
myQueue.Enqueue(4);
myQueue.Enqueue(3);
myQueue.Enqueue(2);
myQueue.Enqueue(1);
Console.WriteLine(myQueue);
myQueue.Dequeue();
Console.WriteLine(myQueue);
myQueue.Enqueue(6);
Console.WriteLine(myQueue);
Console.WriteLine(myQueue.Size());
myQueue.Enqueue(7);
myQueue.Enqueue(8);
myQueue.Enqueue(8);
myQueue.Enqueue(8);
Console.WriteLine(myQueue);
Console.WriteLine(myQueue.Size());
}
// Week 2 - Opdracht 4a
private static bool CheckBrackets(string s)
{
MyStack<char> stack = new MyStack<char>();
bool balanced = true;
for (int i = 0; i < s.Length && balanced; i++)
{
char c = s[i];
if (c == '(')
{
stack.Push(c);
}
else
{
try
{
stack.Pop();
}
catch (NullReferenceException)
{
balanced = false;
}
}
}
try
{
stack.Top();
}
catch (NullReferenceException)
{
return balanced;
}
return false;
}
// Week 2 - Opdracht 4b
private static bool CheckBrackets2(string s)
{
MyStack<char> stack = new MyStack<char>();
bool balanced = true;
for (int i = 0; i < s.Length && balanced; i++)
{
char c = s[i];
if ("[(".IndexOf(c) != -1)
{
stack.Push(c);
}
else
{
try
{
var top = stack.Pop();
balanced = SameBracket(top, c);
}
catch (NullReferenceException)
{
balanced = false;
}
}
}
try
{
stack.Top();
}
catch (NullReferenceException)
{
return balanced;
}
return false;
}
private static bool SameBracket(char first, char end)
{
const string firsts = "[(";
const string ends = "])";
return firsts.IndexOf(first) == ends.IndexOf(end);
}
}
}
|
PHP
|
UTF-8
| 1,034 | 3.09375 | 3 |
[] |
no_license
|
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_NAME", "ny_db");
$dbh = new PDO('mysql:dbname=' . DB_NAME . ';host=' . DB_SERVER . ';charset=utf8', DB_USER, DB_PASSWORD);
$array = array("Hus", "Pinne", "Gran", "Toalett","Pilbรฅge","Dator","Hund","Rymdskepp","Tangentbord","U-bรฅt","Papperskorg","Fedora");
$index = rand(0, 11 );
$sql = "INSERT INTO `Saker`(`id`, `Namn`) VALUES ('','$array[$index]')";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$sql = "SELECT * FROM Saker";
$stmt = $dbh->prepare($sql);
$stmt->execute();
$saker = $stmt->fetchAll();
foreach ($saker as $sak) {
echo $sak["Namn"];
echo "<br>";
}
?>
</body>
</html>
|
Python
|
UTF-8
| 1,466 | 3.625 | 4 |
[] |
no_license
|
import clipboard
import string
import random
lower_case = string.ascii_lowercase
upper_case = string.ascii_uppercase
digits = string.digits
symbols = string.punctuation
password_length = input("How long do you want your password to be?\n")
#colored warning
choice = input("""Seperate Using Space
Press 1 for lowercase
Press 2 for uppercase
Press 3 for digits
Press 4 for symbols
Press 5 for everything\n""")
def listbuilder():
global list
list= ''
if '1' in choice:
list += lower_case
if '2' in choice:
list += upper_case
if '3' in choice:
list += digits
if '4' in choice:
list += symbols
if '5' in choice:
list = lower_case + upper_case + digits + symbols
def passwordgenerator(list, password_length):
global password
password = ''
try:
for i in range(int(password_length)):
index = random.randint(0, int(len(list)))
password += list[index - 1]
except:
print('Something went wrong, check the length you have provided')
def passwordretriever():
print('Here is your password : {}'.format(password))
copy = input("Do you want to copy it to your clipboard y or n\n")
if 'y' in copy:
#copy to clipboard
clipboard.copy(password)
elif 'Y' in copy:
clipboard.copy(password)
#copy to clipboard
else:
quit()
listbuilder()
passwordgenerator(list, password_length)
passwordretriever()
|
Java
|
UTF-8
| 1,251 | 2.1875 | 2 |
[] |
no_license
|
package com.felipeska.banking.presenter;
import java.util.List;
import com.felipeska.banking.interactor.FindHistoryTransactionInteractor;
import com.felipeska.banking.interactor.FindHistoryTransactionInteractorImpl;
import com.felipeska.banking.listener.OnFinisLoadHistoryTransactionsListener;
import com.felipeska.banking.model.Transaction;
import com.felipeska.banking.view.TransactionHistoryView;
public class TransactionHistoryPresenterImpl implements
TransactionHistoryPresenter, OnFinisLoadHistoryTransactionsListener {
private TransactionHistoryView transactionHistoryView;
private FindHistoryTransactionInteractor findHistoryTransactionInteractor;
public TransactionHistoryPresenterImpl(
TransactionHistoryView transactionHistoryView) {
this.transactionHistoryView = transactionHistoryView;
this.findHistoryTransactionInteractor = new FindHistoryTransactionInteractorImpl();
}
@Override
public void findHistory(String accountNumber) {
this.transactionHistoryView.showProgress();
this.findHistoryTransactionInteractor.findAccounts(accountNumber, this);
}
@Override
public void onFinished(List<Transaction> items) {
this.transactionHistoryView.hideProgress();
this.transactionHistoryView.setClients(items);
}
}
|
Java
|
UTF-8
| 2,159 | 2.515625 | 3 |
[] |
no_license
|
package com.sitech.paas.javagen.benchmark.interpret;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* ็ๆๅฏนๅบๆจกๆฟ็ไปฃ็
* @author liwei_paas
* @date 2020/3/24
*/
public class TemplateUtil {
/**
* ็ๆไปฃ็
*
* @return ๆฐๆฎ
*/
public static void generatorCode(OutputStream outputStream, Map<String,Object> map,List<String> templates)
{
ZipOutputStream zip = new ZipOutputStream(outputStream);
// ็ๆไปฃ็
generator(zip,map,templates);
IOUtils.closeQuietly(zip);
}
/**
* ็ๆไปฃ็
*/
public static void generator(ZipOutputStream zip,Map<String,Object> map,List<String> templates){
VelocityInitializer.initVelocity();
VelocityContext context = new VelocityContext();
context.put("author", "liwei_paas");
map.forEach((k,v)->context.put(k,v));
String filePrefix = "main/java/com/sitech/paas/javagen/demo/";
for (String template : templates){
// ๆธฒๆๆจกๆฟ
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, "utf-8");
tpl.merge(context, sw);
try{
String tname = template.substring(template.indexOf("/") + 1, template.length());
if (tname.endsWith(".vm")){
tname = tname.substring(0,tname.lastIndexOf("."));
}
String filename = filePrefix + tname;
// ๆทปๅ ๅฐzip
zip.putNextEntry(new ZipEntry(filename));
IOUtils.write(sw.toString(), zip, "utf-8");
IOUtils.closeQuietly(sw);
zip.closeEntry();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
|
Java
|
UTF-8
| 5,562 | 1.640625 | 2 |
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.flipkart.android.utils;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.flipkart.android.fragments.model.InAppNotificationModel;
import com.flipkart.android.response.customwidgetitemvalue.Action;
import java.util.Map;
// Referenced classes of package com.flipkart.android.utils:
// StringUtils
public class InAppNotificationItemBuilder
{
public InAppNotificationItemBuilder()
{
}
public static View buildInAppNotificationItem(InAppNotificationModel inappnotificationmodel, View view, ImageLoader imageloader, android.view.View.OnClickListener onclicklistener, Context context)
{
RelativeLayout relativelayout;
if (inappnotificationmodel == null)
{
return new View(context);
}
LayoutInflater layoutinflater = LayoutInflater.from(context);
if (inappnotificationmodel.isShareable() && !StringUtils.isNullOrEmpty(inappnotificationmodel.getShareUrl()))
{
relativelayout = (RelativeLayout)layoutinflater.inflate(0x7f030055, null);
} else
{
relativelayout = (RelativeLayout)layoutinflater.inflate(0x7f030054, null);
}
if (relativelayout == null)
{
return new View(context);
}
TextView textview;
TextView textview1;
ImageView imageview;
TextView textview2;
NetworkImageView networkimageview;
TextView textview3;
View view1;
String s;
textview = (TextView)relativelayout.findViewById(0x7f0a0111);
textview1 = (TextView)relativelayout.findViewById(0x7f0a0112);
imageview = (ImageView)relativelayout.findViewById(0x7f0a011a);
textview2 = (TextView)relativelayout.findViewById(0x7f0a0118);
networkimageview = (NetworkImageView)relativelayout.findViewById(0x7f0a0110);
textview3 = (TextView)relativelayout.findViewById(0x7f0a0119);
view1 = relativelayout.findViewById(0x7f0a010e);
s = inappnotificationmodel.getImageUrl();
if (StringUtils.isNullOrEmpty(s)) goto _L2; else goto _L1
_L1:
networkimageview.setImageUrl(s, imageloader);
_L14:
textview.setText(inappnotificationmodel.getTitle());
if (!inappnotificationmodel.getNotificationType().equals("UPGRADE_APP")) goto _L4; else goto _L3
_L3:
textview2.setVisibility(8);
textview1.setText(Html.fromHtml(inappnotificationmodel.getSubTitle()));
_L8:
if (inappnotificationmodel.isShareable() && !StringUtils.isNullOrEmpty(inappnotificationmodel.getShareUrl()))
{
TextView textview4 = (TextView)relativelayout.findViewById(0x7f0a011e);
textview4.setOnClickListener(onclicklistener);
textview4.setTag((new StringBuilder("share:")).append(inappnotificationmodel.getNotificationType()).append(":").append(inappnotificationmodel.getShareUrl()).toString());
}
if (!inappnotificationmodel.isNew()) goto _L6; else goto _L5
_L5:
textview3.setVisibility(0);
view1.setVisibility(0);
_L9:
String s1 = inappnotificationmodel.getNotificationType();
if (!StringUtils.isNullOrEmpty(s1))
{
if (!s1.equals("TARGETED_OFFERS") && !s1.equals("SANTA_OFFERS"))
{
break MISSING_BLOCK_LABEL_494;
}
imageview.setVisibility(0);
}
_L10:
Action action = inappnotificationmodel.getAction();
if (action == null)
{
break MISSING_BLOCK_LABEL_430;
}
Map map = action.getParams();
if (map == null)
{
break MISSING_BLOCK_LABEL_423;
}
map.put("notificationType", inappnotificationmodel.getNotificationType());
map.put("notificationId", inappnotificationmodel.getNotificationId());
map.put("notificationTimeStamp", Long.valueOf(inappnotificationmodel.getTimeStamp()));
action.setParams(map);
relativelayout.setTag(action);
break MISSING_BLOCK_LABEL_504;
_L2:
try
{
networkimageview.setDefaultImageResId(0x7f020189);
continue; /* Loop/switch isn't completed */
}
catch (Exception exception) { }
goto _L7
_L4:
textview1.setText(inappnotificationmodel.getSubTitle());
textview2.setVisibility(0);
textview2.setText(inappnotificationmodel.getTime());
goto _L8
_L6:
textview3.setVisibility(8);
view1.setVisibility(8);
goto _L9
imageview.setVisibility(8);
goto _L10
_L12:
return relativelayout;
_L7:
if (true) goto _L12; else goto _L11
_L11:
if (true) goto _L14; else goto _L13
_L13:
}
public static View buildRefreshingListitem(View view, ImageLoader imageloader, android.view.View.OnClickListener onclicklistener, Context context, boolean flag)
{
if (!flag)
{
return new View(context);
} else
{
return (RelativeLayout)LayoutInflater.from(context).inflate(0x7f03005d, null);
}
}
}
|
Markdown
|
UTF-8
| 586 | 2.6875 | 3 |
[] |
no_license
|
# Image Processing With Java
## Introduction
In this lecture we continue our tour of cool stuff you can do with Java. This lecture is particularly important because we cover the exact material that will be on your final exam.
We are using all we learned about java and computers in general to do a cool trick. We are going to embed a 4 bit ASCII message in a ppm file and then write some Java to extract it. The code
for this lesson is in the SampleCode directory below here.
## References
[1] About PPM files https://www.cs.swarthmore.edu/~soni/cs35/f12/Labs/extras/01/ppm_info.html
|
C
|
UTF-8
| 550 | 2.9375 | 3 |
[] |
no_license
|
/*************************************************************************
> File Name: F.c
> Author: zxw
> Mail:
> Created Time: 2017ๅนด10ๆ17ๆฅ ๆๆไบ 21ๆถ49ๅ07็ง
************************************************************************/
#include<stdio.h>
#include<string.h>
int main(void){
int N;
int num;
int temp,sum;
while(EOF != scanf("%d",&N)){
sum = 0;
for(temp=0;temp<N;temp++){
scanf("%d",&num);
sum = sum+num;
}
printf("%d\n",sum);
}
}
|
PHP
|
UTF-8
| 2,792 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
<?php namespace Concrete\Package\Sequence\Src\Traits {
date_default_timezone_set('UTC');
use Database;
use DateTime;
use DateTimeZone;
/**
* Class Persistable
* @package Concrete\Package\Sequence\Src\Traits
* @todo: Installation test to ensure support for prepersist callbacks!
*/
trait Persistable {
/**
* @Id @Column(type="integer") @GeneratedValue
* @var int
*/
protected $id;
/**
* @Column(type="datetime")
* @var DateTime
*/
protected $createdUTC;
/**
* @Column(type="datetime")
* @var DateTime
*/
protected $modifiedUTC;
/**
* @PrePersist
*/
public function setCreatedUTC(){
if( !($this->createdUTC instanceof DateTime) ){
$this->createdUTC = new DateTime('now', new DateTimeZone('UTC'));
}
}
/**
* @PrePersist
* @PreUpdate
*/
public function setModifiedUTC(){
$this->modifiedUTC = new DateTime('now', new DateTimeZone('UTC'));
}
/**
* @return int|null
*/
public function getID(){
return $this->id;
}
/**
* @return DateTime
*/
public function getModifiedUTC(){
return $this->modifiedUTC;
}
/**
* @return DateTime
*/
public function getCreatedUTC(){
return $this->createdUTC;
}
/**
* @param array $properties
* @return mixed
*/
public static function create( array $properties = array() ){
$instance = new self();
$instance->setPropertiesFromArray( $properties );
$instance->save();
return $instance;
}
/**
* Update the instance with the given properties
* @param array $properties
*/
public function update( array $properties = array() ){
$this->setPropertiesFromArray( $properties );
$this->save();
}
/**
* Delete a record
*/
public function delete(){
$this->entityManager()->remove($this);
$this->entityManager()->flush();
}
/**
* Persist to the database
* @return void
*/
protected function save(){
$this->entityManager()->persist( $this );
$this->entityManager()->flush();
}
/**
* @return \Doctrine\ORM\EntityManager
*/
protected static function entityManager(){
return Database::get()->getEntityManager();
}
}
}
|
C#
|
UTF-8
| 2,440 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using SwiftReflector.Inventory;
using SwiftRuntimeLibrary;
namespace DylibBinder {
internal class InnerX {
// This class will be responsible for creating a dictionary
// telling us if a TypeDeclaration is on the top level or
// which TypeDeclaration it is an innerType for
public Dictionary<string, List<ClassContents>> InnerXDict { get; } = new Dictionary<string, List<ClassContents>> ();
public Dictionary<string, List<ClassContents>> AddClassContentsList (params SortedSet<ClassContents>[] contents)
{
foreach (var classContentsList in contents) {
foreach (var classContent in classContentsList) {
AddItem (classContent);
}
}
return InnerXDict;
}
void AddItem (ClassContents c)
{
Exceptions.ThrowOnNull (c, nameof (c));
var nestingNames = c.Name.NestingNames.ToList ();
if (nestingNames.Count == 0)
return;
var nestingNameString = c.Name.ToFullyQualifiedName ();
if (nestingNameString == null)
return;
if (nestingNames.Count == 1) {
AddKeyIfNotPresent (nestingNameString);
return;
}
var parentNestingNameString = GetParentNameString (nestingNameString);
if (parentNestingNameString == null)
return;
AddKeyIfNotPresent (parentNestingNameString);
var value = InnerXDict [parentNestingNameString];
value.Add (c);
InnerXDict [parentNestingNameString] = value;
}
void AddKeyIfNotPresent (string key)
{
Exceptions.ThrowOnNull (key, nameof (key));
if (InnerXDict.ContainsKey (key))
return;
InnerXDict.Add (key, new List<ClassContents> ());
}
string GetParentNameString (string childName)
{
Exceptions.ThrowOnNull (childName, nameof (childName));
MatchCollection matches = Regex.Matches (childName, @"\.");
if (matches.Count == 0)
return null;
return childName.Substring (0, matches [matches.Count - 1].Index);
}
public static bool IsInnerType (DBTypeDeclaration typeDeclaration)
{
Exceptions.ThrowOnNull (typeDeclaration, nameof (typeDeclaration));
var name = typeDeclaration.Name;
// if the name begins with the module and a period, we do not take that into consideration
if (name.StartsWith ($"{typeDeclaration.Module}."))
name = typeDeclaration.Name.Substring (typeDeclaration.Module.Length + 1);
return Regex.Matches (name, @"\.").Count > 0;
}
}
}
|
Python
|
UTF-8
| 731 | 3.171875 | 3 |
[] |
no_license
|
'''
Created on 12-Mar-2018
@author: Titan
'''
if __name__ == '__main__':
pass
import sqlite3
data_person_name = [('Michael', 'Fox'),
('Adam', 'Miller'),
('Andrew', 'Peck'),
('James', 'Shroyer'),
('Eric', 'Burger')]
con = sqlite3.connect(":memory:")
c = con.cursor()
c.execute('''CREATE TABLE q1_person_name
(name_id INTEGER PRIMARY KEY,
first_name varchar(40) NOT NULL,
last_name varchar(20) NOT NULL)''')
c.executemany('INSERT INTO q1_person_name(first_name, last_name) VALUES (?,?)', data_person_name)
for row in c.execute('SELECT * FROM q1_person_name'):
print(row)
|
TypeScript
|
UTF-8
| 965 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import { Body, Get, Controller, Res, Post, Query } from '@nestjs/common';
import { ApiBody } from '@nestjs/swagger';
import { LogoutDto } from '@user/dto/logout.dto';
import { UsersService } from '@user/users.service';
@Controller('User')
export class UserController {
constructor(private readonly userService: UsersService) {}
@Get('getProfile')
async getProfile(@Query('id') id: number, @Res() res) {
const user = await this.userService.findOneById(id);
return res.json(user);
}
@Post('logout')
@ApiBody({ type: LogoutDto })
async logout(@Body() data: LogoutDto, @Res() res) {
const result = await this.userService.removeFCMToken(
data.userID,
data.fcmToken,
);
if (result === true)
return res.json({
valid: true,
message: 'User has been logged out successfully !',
});
else
return res.json({
valid: false,
message: 'An unknown error occured',
});
}
}
|
Markdown
|
UTF-8
| 1,779 | 3.078125 | 3 |
[] |
no_license
|
# 1931๋ฒ ํ์์ค ๋ฐฐ์
[๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ](https://www.acmicpc.net/problem/1931)
๐ฉ `๊ทธ๋ฆฌ๋`
<br>
## ๐
ฐ ์ค๊ณ
`[SWEA] 5202-ํ๋ฌผ ๋ํฌ` ๋ ๋๊ฐ์ ๋ฌธ์ ์ฌ์ ๊ฐ์ ๋ฐฉ์์ผ๋ก ํ์๋ค.
์์-๋ ์๊ฐ์ ๋ฆฌ์คํธ๋ก ๋ฐ์ ๋ค์, **๋๋๋ ์๊ฐ ์**์ผ๋ก ์ ๋ ฌํ๋ค.
์ ํ์ฐจ์ ๋ ์๊ฐ๋ณด๋ค ๋ค์ํ์ฐจ ์์ ์๊ฐ์ด ๊ฐ๊ฑฐ๋ ํฌ๋ฉด ์นด์ดํ
์ ํด์ฃผ๋ฉด ๋๋ค.
์๊ฐ ๋๋ฌธ์ `pop(0)` ์ ์ํ๊ณ `pop()` ์ ํ๊ณ ์ถ์ด์ ๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌํ๋ค.
```python
# sorted(a, key=lambda x: (-x[1], -x[0])) ์ ๋ ฌ๊ฒฐ๊ณผ
[[12, 14], [2, 13], [8, 12], [8, 11], [6, 10], [5, 9], [3, 8], [5, 7], [0, 6], [3, 5], [1, 4]]
```
<br>
## ๐
ฑ ์ต์ข
์ฝ๋
```python
import sys
N = int(sys.stdin.readline()) # ํ์์ ์
a = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
a = sorted(a, key=lambda x: (-x[1], -x[0]))
cnt = 1
f1, f2 = a.pop() # ๋ค์์๋ถํฐ ์ฒดํฌ
while a:
n1, n2 = a.pop()
if n1 >= f2: # ๋ค์ ์์์ด ์ ํ์ฐจ ๋๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ผ๋ฉด ๊ฐฑ์
f1, f2 = n1, n2
cnt += 1
print(cnt)
```
<br>
## โ
ํ๊ธฐ
### ์๋กญ๊ฒ ์๊ฒ ๋ ์
(์๋กญ๊ฒ ์๊ฒ ๋ ์ ์ด ์๋๋ผ ์๋ ์ ์์๋๊ณ ๊น๋จน์ ๊ฒ..๐
)
โญ `input()`์ ๋งค์ฐ ๋๋ฆฌ๋ค. ์
๋ ฅ์ด **10๋ง์ค ์ด์** ๋๋ฉด `stdin.readline`์ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข๋ค.
- ์ฐธ๊ณ : [ํ์ด์ฌ ์
๋ ฅ ๋ฐ๊ธฐ (sys.stdin.readline)](https://velog.io/@yeseolee/Python-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%9E%85%EB%A0%A5-%EC%A0%95%EB%A6%ACsys.stdin.readline)
<br>
โ ์๊ฐ `stdin.readline` ์ ์ฌ์ฉํ ๊ฒ์ด๊ณ , ์๋๊ฐ `input()`์ ์ฌ์ฉํ ๊ฒ์ด๋ค.

|
Python
|
UTF-8
| 310 | 2.984375 | 3 |
[] |
no_license
|
#M
st=""
for r in range(7):
for c in range(0,7):
if ((c==0)or(c==6)or (r==1 and c!=2 and c!=3 and c!=4)
or (r==2 and c!=1 and c!=3 and c!=5 )or(r==3 and c!=1 and c!=2 and c!=4 and c!=5 )
):
st=st+"*"
else:
st=st+" "
st=st+"\n"
print(st)
|
PHP
|
UTF-8
| 2,701 | 2.609375 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: alexwinter
* Date: 23.08.18
* Time: 18:19
*/
namespace Ginero\GineroPhp\Model\Response;
use JMS\Serializer\Annotation as Serializer;
use Psr\Http\Message\ResponseInterface;
/**
* Class BaseResponse
* @package Ginero\GineroPhp\Model\Response
*/
abstract class BaseResponse
{
/**
* @var string
*
* @Serializer\Type("string")
* @Serializer\SerializedName("message")
*/
private $message;
/**
* @var int
*
* @Serializer\Type("integer")
* @Serializer\SerializedName("code")
*/
private $code = 200;
/**
* @var Error
*
* @Serializer\Type("Ginero\GineroPhp\Model\Response\Error")
* @Serializer\SerializedName("error")
*/
private $error;
/**
* @var Errors
*
* @Serializer\Type("Ginero\GineroPhp\Model\Response\Errors")
* @Serializer\SerializedName("errors")
*/
private $errors;
/**
* @var ResponseInterface
*/
private $response;
/**
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @return int
*/
public function getCode()
{
return $this->code;
}
/**
* @return Error
*/
public function getError()
{
return $this->error;
}
/**
* @return Errors
*/
public function getErrors()
{
return $this->errors;
}
/**
* @return ResponseInterface
*/
public function getResponse()
{
return $this->response;
}
/**
* @param int $code
* @return BaseResponse
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* @param ResponseInterface $response
* @return BaseResponse
*/
public function setResponse(ResponseInterface $response)
{
$this->response = $response;
return $this;
}
/* HELPERS */
/**
* @return bool
*/
public function isOk()
{
return null === $this->error && null === $this->errors && 2 == substr($this->code, 0, 1);
}
/**
* @return string|null
*/
public function getFirstError()
{
if (null !== $this->error) {
return $this->error;
}
if ($this->errors instanceof Errors) {
foreach ($this->errors->getChildren() as $child) {
if (count($child->getErrors()) > 0) {
foreach ($child->getErrors() as $error) {
return $error;
}
}
}
}
return null;
}
}
|
Markdown
|
UTF-8
| 1,332 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
# ํญ
## ๋ฐ๋ชจ
<client-only>
<demo-block>
<examples-tab-index/>
</demo-block>
</client-only>
๋จ์ํ๋ฉด ์ฌ๋ฏธ๊ฐ ์์ผ๋ฏ๋ก, ํธ๋์ง์
์ ์ฌ์ฉํด์ ์ฌ๋ผ์ด๋ ํ๊ฒ ๋ง๋ค์์ต๋๋ค.
## ์ฌ์ฉํ๊ณ ์๋ ์ฃผ์ ๊ธฐ๋ฅ
<page-info page="62">ํด๋์ค ๋ฐ์ดํฐ ๋ฐ์ธ๋ฉํ๊ธฐ</page-info>
<page-info page="64">์ฌ๋ฌ ์์ฑ ๋ฐ์ดํฐ ๋ฐ์ธ๋ฉํ๊ธฐ</page-info>
<page-info page="120">์ฐ์ถ ์์ฑ(computed)</page-info>
<page-info page="146">์ปดํฌ๋ํธ</page-info>
<page-info page="153">์ปดํฌ๋ํธ์ ์ปดํฌ๋ํธ ๋ผ๋ฆฌ์ ํต์ </page-info>
<page-info page="194">ํธ๋์ง์
</page-info>
## ์์ค ์ฝ๋
- [์์ค ์ฝ๋](https://github.com/mio3io/cr-vue/tree/master/docs/.vuepress/components/examples/tab)
<code-caption>index.vue</code-caption>
{include:examples/tab/index.vue}
<code-caption>TabItem.vue</code-caption>
{include:examples/tab/TabItem.vue}
::: tip ํญ ์์ ์ปดํฌ๋ํธ์ ์กํฐ๋ธ ์ํ๋ฅผ ์ค์ค๋ก ํ๋จํ๊ฒ ํ๊ธฐ
์ด๋ค ์ปดํฌ๋ํธ๊ฐ ์ ํ๋์ด ์๋ ์ํ์ธ์ง ํ๋จํด์ผ ํ๋ ์ํฉ์ ๊ต์ฅํ ๋ง์ต๋๋ค.
ํ์ฌ ์ํ์์๋ ๋ถ๋ชจ๋ก๋ถํฐ ์ ๋ฌ๋ฐ์ `currentId` ์์ฑ์ ์์ ์ ID์ ๋น๊ตํด์, ์์ ์ด ์กํฐ๋ธ ์ํ(์ ํ๋์ด ์๋ ์ํ)์ธ์ง ํ์ธํ๊ณ ์์ต๋๋ค. ๊ต์ฅํ ์์ฃผ ์ฌ์ฉํ๋ ํํ์
๋๋ค.
:::
|
Java
|
UTF-8
| 678 | 2.15625 | 2 |
[] |
no_license
|
package leapfrog_inc.icchi.Fragment;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Leapfrog-Software on 2018/01/25.
*/
public class BaseFragment extends Fragment {
@Override
public void onStart() {
super.onStart();
View view = getView();
if (view == null) {
return;
}
ViewGroup.LayoutParams params = view.getLayoutParams();
if (params != null) {
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = ViewGroup.LayoutParams.MATCH_PARENT;
view.setLayoutParams(params);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.