language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
3,133
2.671875
3
[]
no_license
/** * Copyright (C) 2012-2013 Dušan Vejnovič <vaadin@dussan.org> * * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 * * 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.dussan.vaadin.dcharts.base; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.dussan.vaadin.dcharts.helpers.ObjectHelper; @SuppressWarnings("serial") public class BaseData<T> implements Serializable { private boolean hasSubSeries = false; private boolean appendExtraBrackets = true; private List<Object> subSeries = null; private List<Object> series = null; public BaseData(boolean appendExtraBrackets) { this.appendExtraBrackets = appendExtraBrackets; subSeries = new ArrayList<Object>(); series = new ArrayList<Object>(); } protected List<Object> getSeries() { return series; } @SuppressWarnings("unchecked") protected T clean() { series = new ArrayList<Object>(); return (T) this; } @SuppressWarnings("unchecked") public T newSeries() { if (!hasSubSeries) { hasSubSeries = true; series = new ArrayList<Object>(); } if (!subSeries.isEmpty()) { series.add(subSeries.toArray(new Object[][] {})); subSeries = new ArrayList<Object>(); } return (T) this; } @SuppressWarnings("unchecked") public T add(Object... data) { if (hasSubSeries()) { subSeries.add((Object[]) data); } else { series.add((Object[]) data); } return (T) this; } public Object getSeriesValue(int seriesIndex, int pointIndex) { List<Object> series = this.series; if (hasSubSeries() && !subSeries.isEmpty()) { series.add(subSeries.toArray(new Object[][] {})); } try { Object[] serie = (Object[]) series.get(seriesIndex); return serie[pointIndex]; } catch (Exception e) { return null; } } public String getValue() { if (hasSubSeries() && !subSeries.isEmpty()) { series.add(subSeries.toArray(new Object[][] {})); subSeries = new ArrayList<Object>(); } StringBuilder dataSeries = new StringBuilder(); for (Object data : series) { if (dataSeries.length() > 0) { dataSeries.append(", "); } if (data instanceof Object[][]) { dataSeries .append(ObjectHelper.toArrayString((Object[][]) data)); } else { dataSeries.append(ObjectHelper.toArrayString((Object[]) data)); } } if (appendExtraBrackets) { dataSeries.insert(0, "[").append("]"); } return dataSeries.toString(); } public boolean hasSubSeries() { return hasSubSeries; } public boolean isEmpty() { return !(series != null && !series.isEmpty()) & !(hasSubSeries() && subSeries != null && !subSeries.isEmpty()); } @Override public String toString() { return getValue(); } }
C++
UTF-8
3,125
4.28125
4
[]
no_license
#include<iostream> using namespace std; class node{ public: int data; node* prev; node* next; }; class doublylinkedList{ node* head; public: doublylinkedList(){ head = NULL; } doublylinkedList(int data){ node* newNode = new node; newNode->data = data; head = newNode; } void insertAfter(int data, int newData){ node* currentNode = head; while (currentNode->next != NULL){ if (currentNode->data == data){ node* newNode = new node; newNode->data = newData; newNode->prev = currentNode; newNode->next = currentNode->next; currentNode->next = newNode; currentNode->next->prev = newNode; return; } currentNode = currentNode->next; } } void insertBefore(int data, int newData){ node* currentNode = head; while (currentNode->next != NULL){ if (currentNode->next->data == data){ node* newNode = new node; newNode->data = newData; newNode->prev = currentNode; newNode->next = currentNode->next; currentNode->next = newNode; currentNode->next->prev = newNode; return; } currentNode = currentNode->next; } } void insertAtEnd(int data){ node* currentNode = head; while (currentNode->next != NULL){ currentNode = currentNode->next; } node* newNode = new node; newNode->data = data; currentNode->next = newNode; newNode->prev = currentNode; } void display(){ node* currentNode = new node; currentNode = head; while (currentNode->next != NULL){ cout << currentNode->data << " "; currentNode = currentNode->next; } cout << currentNode->data << " "; cout << endl; } void delHead(){ node* temp = head; head = head->next; delete temp; } void delTail(){ node* currentNode = new node; currentNode = head; while (currentNode->next != NULL){ currentNode = currentNode->next; } delete currentNode; } void del(int data){ node* currentNode = new node; currentNode = head; node* prevNode = newNode; prevNode = NULL; while(currentNode->data != data){ prevNode = currentNode; currentNode = currentNode->next; } currentNode->next->prev = prevNode; prevNode->next = currentNode->next; delete currentNode; } void delBefore (int data){ node* currentNode = new node; currentNode = head; while (currentNode->data != data){ currentNode = currentNode->next; } node* temp = new bode; temp = currentNode->prev; temp->prev->next = currentNode; currentNode->prev = temp->prev; delete temp; } void delAfter (int data){ node* currentNode = new node; currentNode = head; while (currentNode->data != data){ currentNode = currentNode->next; } node* temp = new node; temp = currentNode->next; currentNode->next = temp->next; temp->next->prev = temp->prev; delete temp; } }; int main(){ doublylinkedList ll(5); ll.insertAtEnd(10); ll.insertAtEnd(30); ll.insertAtEnd(70); ll.insertAtEnd(40); cout << "Linked List is: "; ll.display(); ll.insertAfter(30, 25); cout << "After using insert after: "; ll.display(); ll.insertBefore(30, 35); cout << "After using insert before: "; ll.display(); return 0; }
Markdown
UTF-8
1,506
3.140625
3
[]
no_license
# Notes app *** ### Tecnologias utilizadas: 1. Javascript 2. Node.js 3. Express.js *** ## Pasos para la instalación: ``` $ git clone git@github.com:ayrtoncravero/notes.git $ cd notes $ npm install (Instalacion de dependecias) $ npm run dev (Ejecutar el servidor) ``` - El servidor esta disponible en 'http://localhost:3000/' ``` - Configuracion de base de datos: 1- Acceder a Mysql: $ mysql -uroot -p 2- Correr el siguiente comando para crear la base de datos: $ CREATE DATABASE notes; 3- Seleccionar la base de datos creada: $ USE notes; 4- Crear tabla users: $ CREATE TABLE users( id INT(11) NOT NULL, username VARCHAR(16) NOT NULL, password VARCHAR(60) NOT NULL, fullname VARCHAR(100) NOT NULL ); 5- Agregar clave primaria: $ ALTER TABLE users ADD PRIMARY KEY (id); 6- Agregar id auto incremental: $ ALTER TABLE users MODIFY id INT(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 2; 7- Crear tabla notes: $ CREATE TABLE notes( id INT(11) NOT NULL, title VARCHAR(150) NOT NULL, description TEXT, user_id INT(11), created_at timestamp NOT NULL DEFAULT current_timestamp, CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ); 8- Agregar clave primaria: $ ALTER TABLE notes ADD PRIMARY KEY (id); 9- Agregar id auto incremental: $ ALTER TABLE notes MODIFY id INT(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 2; ``` *** ## Información extra: - Este proyecto fue desarrollado para el aprendizaje de Node.js, Express.js y Mysql.
PHP
UTF-8
908
2.9375
3
[]
no_license
<?php namespace Irate\Core; use \PDO; use Irate\System; /** * Base model */ abstract class Library { // Instance of the request class protected $request; // Instance of the security class protected $security; // Instance of the db class protected $db; // Instance of the email class protected $email; // Instance of the session class protected $session; public function __construct() { // Set all class instances from System $this->db = System::$db; $this->request = System::$request; $this->security = System::$security; $this->email = System::$email; $this->session = System::$session; $this->instantiate(); } /** * Function that will run immediately after construct * so the actual model class doesn't need to run the constructor * and mess with the class var settings. */ public function instantiate() { } }
C++
UTF-8
270
2.84375
3
[]
no_license
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size()<=1) return 0; int res=0; for(int i=1;i<prices.size();i++){ res+=(prices[i]>prices[i-1]?prices[i]-prices[i-1]:0); } return res; } };
Markdown
UTF-8
7,235
2.8125
3
[]
no_license
--- title: "17.1 术语和定义" slug: "术语和定义" hidden: false createdAt: "2018-12-14T15:21:51.034Z" updatedAt: "2019-12-13T03:20:32.013Z" --- [block:api-header] { "title": "术语和定义(BCX-NHAS-1808标准相关术语和定义)" } [/block] ## 分布记账 distributed ledger 也称分布式分类账、共享分类账、DLT等,是一种在多个账本间通过网络同步机制同步、共享数字信息的信息记录方式。在分布记账式中,没有中心数据存储或管理者,账本间通过P2P连接通信,数据通过共识方式完成校验并达成一致,各账本保存完全相同的数据。 ## 共识 consensus 指一种通过多数赞成法对事务、数据的决策方式和决策过程。共识一般包括通过共识完成一个决策以及完成这一决策的过程。 ## 去中心化游戏 decentralized game 指软件主体逻辑、代码存放在分布记账式网络中,并由分布记账式网络驱动的游戏软件类型,中心服务对此类游戏来说不是必须,游戏主要逻辑甚至全部逻辑由分布记账式网络中的智能合约决定。 ## 智能合约 smart contract 一种具备图灵完备性的脚本,通过分布记账式网络中的合约虚拟机运行,实现运行事务逻辑、网络数据交互、信息传递等功能。 ## 区块链 blockchain 通过密码学加密分布式账本事务数据并串接事务数据的数据记录方式,每一组事务数据即一个区块,每一个区块包含前一个区块的加密散列、时间戳等,具备难以篡改的特性,区块链通常使用默克尔证明完成块链校验。 ## 同质数字资产 homogenous digital assets 一种应用于分布记账式网络中的数字资产类型,资产实例间没有区别,可在计量单位与类型相同时合并计数,其数量可按照设定的精度拆分。 ## 非同质数字资产 non-homogenous digital assets 一种应用于分布记账式网络中的数字资产类型,资产实例具备唯一性,具备除唯一标识外不同的数据项及内容,同一类型的非同质资产实例也无法直接合并且不可分割。 ## 世界观 word view 一种用于区分游戏故事设定、角色/道具/规则设定和效用范围的标识。 ## 认证过程 authentication procedure 认证过程指业务实体与数字资产间进行权限确认的过程,以及业务实体与分布记账式网络间建立信任关系的过程。 ## 数字签名 digital signature 一种通过公私钥算法保障身份信息具备不可抵赖性的验证机制,在去中心分布记账式网络中,通常使用基于ECC的公私钥算法,本文所使用的数字签名符合《中华人民共和国电子签名法》第十三条关于电子签名可靠性的要求。 ## 去中心数据库 decentralized database 在去中心分布记账式网络中,数据以结构化方式在所有账本上存储相同的副本,其存储可被抽象为一个分布式的去中心数据库,合约或其他业务实体可通过申明在分布式网络中的数据表存放其结构化数据。 ## 基础标识 basic identity 本文所述非同质数字资产数据中基本信息的标识,是由资产发布者定义的、符合分布记账式网络要求的、具有全网唯一性的标识。主要用于数字资产的识别、认证、读取和修改等场景。 ## 域标识 session identity 本文所述非同质数字资产扩展数据的区域标识,是由合约发布者定义的、符合分布记账式网络要求的、具有全网唯一性的标识。主要用于特定游戏世界、舞台的数字资产扩展数据识别、认证、读取和修改等场景。 ## 固有数据区域 inherent datafield 用于描述本标准非同质数字资产基本信息的数据区域,包括唯一ID、基础属性、世界观等信息,由基础标识划分。 ## 扩展数据区域 extensible data field 用于描述本标准非同质数字资产游戏世界、舞台等信息的数据区域,包含相关游戏、合约的业务数据,不同游戏世界/合约可访问的数据区域由域标识划分。 ## 行为权限 active privilege 指数字资产的可执行行为权限,如一定范围内的可编辑、可操作权限,包括资产扩展数据区域中指定域的修改、资产的发送、转出等。 ## 所有者权限 owner privilege 指数字资产的所有者权限,用于标识一个账户对该资产的所有权,其优先级高于行为权限,除行为权限覆盖的范围外,具备删除扩展数据区域中指定域的权限。 ## 数据结构 data structure 指分布记账式网络中数据存储、流通的特定数据模式,包括但不限定于:点对点传输、账本单位数据、数字资产数据、智能合约数据、中间数据等。 ## 业务实体 service provider 具有提供业务的对象,包括外部操作接口、具备访问权限的合约、用户接口等。 ## 跨网络映射 cross-net mapping 指具备特定数据结构的数字资产数据,能够通过业务实体完成向不同的分布记账式网络映射的能力。 [block:api-header] { "title": "缩略语和符号(BCX-NHAS-1808标准缩略语和符号)" } [/block] ## 缩略语 [block:parameters] { "data": { "h-0": "名称", "h-1": "解释", "0-0": "IP( Internet Protocol)", "0-1": "互联网协议,又译网际协议", "1-0": "HTTP( Hyper Text Transfer Protocol)", "1-1": "超文本传输协议", "2-0": "P2P( peer-to-peer)", "2-1": "点对点网络,一种无中心服务器、依靠用户群(peers)交换信息的互联网体系", "3-0": "RPC( Remote Procedure Call)", "3-1": "一种用于完成远程过程调用的计算机通信协议", "4-0": "ECC( Elliptic Curve Cryptography)", "4-1": "一种建立非对称加密的密钥算法,基于椭圆曲线数学", "5-0": "AES( Advanced Encryption Standard)", "5-1": "高级加密标准,又称Rijndael加密法,一种广泛应用于对称加密的区块加密标准", "6-0": "BP (Block Producer)", "6-1": "出块者,指打包区块数据并同步至其他账本的参与者", "7-0": "OP( Operation)", "7-1": "操作,指对资产数据的一个不可分割(原子)动作", "8-0": "MS (Multisignature)", "8-1": "多重签名,指签名对象需由多个参与者共同完成方可视为完整签名的一种复数授权确认方式" }, "cols": 2, "rows": 9 } [/block] ## 符号 [block:parameters] { "data": { "h-0": "名称", "h-1": "解释", "0-0": "ERC 20", "1-0": "ERC 721", "1-1": "以太坊不可替代性通证标准(non-fungible tokenstandard)", "0-1": "以太坊智能同质数字资产合约标准", "2-0": "ERC 875", "2-1": "基于ERC 721的一种精简的以太坊不可替代性通证标准", "3-0": "ERC 1155", "3-1": "一种以太坊的非同质数字资产合约标准,支持在一个合约内定义多个资产类型", "4-0": "ERC 998", "4-1": "一种以太坊的非同质数字资产合约标准,支持非同质数字资产之间的组合嵌套" }, "cols": 2, "rows": 5 } [/block]
C#
UTF-8
2,476
2.5625
3
[]
no_license
namespace Util.Webs.EasyUi.Buttons { /// <summary> /// 弹出窗口按钮 /// </summary> public interface IDialogButton : IButtonBase<IDialogButton> { /// <summary> /// 设置弹出窗口网址 /// </summary> /// <param name="url">弹出窗口网址</param> IDialogButton Url( string url ); /// <summary> /// 设置弹出窗口标题 /// </summary> /// <param name="title">弹出窗口标题</param> IDialogButton Title( string title ); /// <summary> /// 设置弹出窗口底部按钮 /// </summary> /// <param name="buttonDivId">弹出窗口底部按钮区域div的id</param> IDialogButton Buttons( string buttonDivId ); /// <summary> /// 设置弹出窗口图标class /// </summary> /// <param name="iconClass">弹出窗口图标class</param> IDialogButton DialogIcon( string iconClass ); /// <summary> /// 设置弹出窗口尺寸 /// </summary> /// <param name="width">弹出窗口宽度</param> /// <param name="height">弹出窗口高度</param> IDialogButton DialogSize( int width,int height ); /// <summary> /// 允许弹出窗口最大化 /// </summary> /// <param name="allow">true为允许最大化</param> IDialogButton Maximizable( bool allow = true ); /// <summary> /// 设置弹出窗口关闭回调函数 /// </summary> /// <param name="callback">弹出窗口关闭回调函数,范例:func</param> IDialogButton OnClose( string callback ); /// <summary> /// 设置弹出窗口初始化事件 /// </summary> /// <param name="callback">初始化回调函数,接收option参数,返回false跳出执行</param> IDialogButton OnInit( string callback ); /// <summary> /// 关闭弹出窗口 /// </summary> IDialogButton CloseDialog(); /// <summary> /// 显示编辑窗口 /// </summary> IDialogButton ShowEditDialog(); /// <summary> /// 显示详细窗口 /// </summary> IDialogButton ShowDetailDialog(); /// <summary> /// 显示编辑窗口 - 树 /// </summary> /// <param name="treeId">树控件Id</param> IDialogButton ShowEditDialogByTree( string treeId = "tree" ); } }
Python
UTF-8
5,967
3.375
3
[]
no_license
import random import math import itertools import operator from heuristics import NearestInsertion, NearestNeighbour import collections import copy def cartesian_distance(a, b): "a and b should be tuples, computes distance between two cities" return math.sqrt((a.x - b.x)**2 + (a.y - b.y)**2) def compute_distances_matrix(locations): "returns array with distances for given points" return [[cartesian_distance(a, b) for a in locations] for b in locations] def random_permutation(iterable, r=None): "returns new tuple with random permutation of iterable" pool = tuple(iterable) r = len(pool) if r is None else r return list(random.sample(pool, r)) def single_path_cost(path, distances): "returns total distance of path" path = list(path) path = path + path[:1] return sum(distances[ path[i] ][ path[i + 1] ] for i in range(len(path) - 1)) def hamming_distance_with_info(a, b): "return number of places and places where two sequences differ" assert len(a) == len(b) ne = operator.ne differ = list(map(ne, a, b)) return sum(differ), differ def hamming_distance(a, b): dist, info = hamming_distance_with_info(a, b) return dist class TSPSolver(): def __init__(self, points): "points is list of objects of type City" self.weights = compute_distances_matrix(points) self.indexes = range(len(points)) self.population = [] self.light_intensities = [] self.best_solution = None self.best_solution_cost = None self.n = None self.first_heuristic = NearestNeighbour(points) self.second_heuristic = NearestInsertion(points) def f(self, individual): # our objective function? lightness? "objective function - describes lightness of firefly" return single_path_cost(individual, self.weights) def determine_initial_light_intensities(self): "initializes light intensities" self.light_intensities = [self.f(x) for x in self.population] def generate_initial_population(self, number_of_individuals, heuristics_percents,): "generates population of permutation of individuals" first_heuristic_part_limit = int(heuristics_percents[0] * number_of_individuals) second_heuristic_part_limit = int(heuristics_percents[1] * number_of_individuals) random_part_limit = number_of_individuals - first_heuristic_part_limit - second_heuristic_part_limit first_heuristic_part = self.first_heuristic.generate_population(first_heuristic_part_limit) second_heuristic_part = self.second_heuristic.generate_population(second_heuristic_part_limit) random_part = [random_permutation(self.indexes) for i in range(random_part_limit)] self.population = random_part + first_heuristic_part + second_heuristic_part self.absorptions = [] for i in range(len(self.population)): self.absorptions.append(random.random() * 0.9 + 0.1) def check_if_best_solution(self, index): new_cost = self.light_intensities[index] if new_cost < self.best_solution_cost: self.best_solution = copy.deepcopy(self.population[index]) self.best_solution_cost = new_cost def find_global_optimum(self): "finds the brightest firefly" index = self.light_intensities.index(min(self.light_intensities)) self.check_if_best_solution(index) def move_firefly(self, a, b, r): "moving firefly a to b in less than r swaps" number_of_swaps = random.randint(0, r - 2) distance, diff_info = hamming_distance_with_info(self.population[a], self.population[b]) while number_of_swaps > 0: distance, diff_info = hamming_distance_with_info(self.population[a], self.population[b]) random_index = random.choice([i for i in range(len(diff_info)) if diff_info[i]]) value_to_copy = self.population[b][random_index] index_to_move = self.population[a].index(value_to_copy) if number_of_swaps == 1 and self.population[a][index_to_move] == self.population[b][random_index] and self.population[a][random_index] == self.population[b][index_to_move]: break self.population[a][random_index], self.population[a][index_to_move] = self.population[a][index_to_move], self.population[a][random_index] if self.population[a][index_to_move] == self.population[b][index_to_move]: number_of_swaps -= 1 number_of_swaps -= 1 self.light_intensities[a] = self.f(self.population[a]) def rotate_single_solution(self, i, value_of_reference): point_of_reference = self.population[i].index(value_of_reference) self.population[i] = collections.deque(self.population[i]) l = len(self.population[i]) number_of_rotations = (l - point_of_reference) % l self.population[i].rotate(number_of_rotations) self.population[i] = list(self.population[i]) def rotate_solutions(self, value_of_reference): for i in range(1, len(self.population)): self.rotate_single_solution(i, value_of_reference) def I(self, index, r): return self.light_intensities[index] * math.exp(-1.0 * self.absorptions[index] * r**2) def run(self, number_of_individuals=100, iterations=200, heuristics_percents=(0.0, 0.0, 1.0), beta=0.7): "gamma is parameter for light intensities, beta is size of neighbourhood according to hamming distance" # hotfix, will rewrite later self.best_solution = random_permutation(self.indexes) self.best_solution_cost = single_path_cost(self.best_solution, self.weights) self.generate_initial_population(number_of_individuals, heuristics_percents) value_of_reference = self.population[0][0] self.rotate_solutions(value_of_reference) self.determine_initial_light_intensities() self.find_global_optimum() #print(self.best_solution_cost) individuals_indexes = range(number_of_individuals) self.n = 0 neighbourhood = beta * len(individuals_indexes) while self.n < iterations: for j in individuals_indexes: for i in individuals_indexes: r = hamming_distance(self.population[i], self.population[j]) if self.I(i, r) > self.I(j, r) and r < neighbourhood: self.move_firefly(i, j, r) self.check_if_best_solution(i) self.n += 1 return self.best_solution_cost
Python
UTF-8
1,338
2.90625
3
[]
no_license
import pandas as pd import numpy as np import pickle from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler base = pd.read_csv('credit-data.csv') previsores = base.iloc[:, 1:4].values classe = base.iloc[:, 4].values impute = SimpleImputer() impute = impute.fit(previsores[:, 1:4]) previsores[:, 1:4] = impute.transform(previsores[:, 1:4]) scaler = StandardScaler() previsores = scaler.fit_transform(previsores) svm = pickle.load(open('svm_finalizado.sav', 'rb')) random_forest = pickle.load(open('random_forest_finalizado.sav', 'rb')) mlp = pickle.load(open('neural_network.sav', 'rb')) r_svm = svm.score(previsores, classe) r_rf = random_forest.score(previsores, classe) r_mlp = mlp.score(previsores, classe) novo_registro = [[50000, 40, 5000]] novo_registro = np.asarray(novo_registro) # -1 não pega linhas # vai trabalhar apenas com colunas # melhor consistencia dos resultados # é necessario que ele fique nesse formato para fazer o escalonamento # caso nao esteja, irá zerar todos os valores novo_registro = novo_registro.reshape(-1, 1) novo_registro = scaler.fit_transform(novo_registro) # voltando ao formato original novo_registro = novo_registro.reshape(-1, 3) r_svm = svm.predict(novo_registro) r_rf = random_forest.predict(novo_registro) r_mlp = mlp.predict(novo_registro)
Markdown
UTF-8
11,599
3.328125
3
[]
no_license
# Determine Sample Size for an A/B Test ### What is a “Sample Size”? [[Statistics How To]][Sample Size in Statistics (How to Find it): Excel, Cochran’s Formula, General Tips] A sample size is a **part of the population** chosen for a survey or experiment. For example, you might take a survey of dog owner’s brand preferences. You won’t want to survey all the millions of dog owners in the country (either because it’s too expensive or time consuming), so you take a sample size. That may be several thousand owners. The sample size is a representation of all dog owner’s brand preferences. If you choose your sample wisely, it will be a good representation. Table of Contents: * [0. When Error can Creep in](https://github.com/HsiangHung/Machine_Learning_Note/tree/master/Statistics/evaluate_sample_size#0-when-error-can-creep-in) * [1. How to Find a Sample Size in Statistics](https://github.com/HsiangHung/Machine_Learning_Note/tree/master/Statistics/evaluate_sample_size#1-how-to-find-a-sample-size-in-statistics) * [1.A Large population](https://github.com/HsiangHung/Machine_Learning_Note/tree/master/Statistics/evaluate_sample_size#1a-large-population) * [1.B Samll population - modification for the Cochran Formula](https://github.com/HsiangHung/Machine_Learning_Note/tree/master/Statistics/evaluate_sample_size#1b-samll-population---modification-for-the-cochran-formula) * [1.C Examples](https://github.com/HsiangHung/Machine_Learning_Note/tree/master/Statistics/evaluate_sample_size#1c-examples) * [2. Page View Example, Required Statistical Power](https://github.com/HsiangHung/Machine_Learning_Note/tree/master/Statistics/evaluate_sample_size#2-page-view-example-required-statistical-power) * [3. Sample Size vs Conversion Rate and Minimum Detectable Effect](https://github.com/HsiangHung/Machine_Learning_Note/tree/master/Statistics/evaluate_sample_size#3-sample-size-vs-conversion-rate-and-minimum-detectable-effect) ## 0. When Error can Creep in When you only survey a **small** sample of the population, uncertainty creeps in to your statistics. If you can only survey a certain percentage of the true population, you can never be 100% sure that your statistics are a complete and accurate representation of the population. This uncertainty is called sampling error and is usually measured by a confidence interval. For example, you might state that your results are at a **90% confidence level**. That means if you were to **repeat** your survey over and over, **90% of the time your would get the results within the interval**. ## 1. How to Find a Sample Size in Statistics A sample is a percentage of the total population in statistics. You can use the data from a sample to make inferences about a population as a whole. For example, the standard deviation of a sample can be used to approximate the standard deviation of a population. Finding a sample size can be one of the most challenging tasks in statistics and depends upon many factors including the size of your original population. ### 1.A Large population Assume we have large enough populations. The margin of error is given by <a href="https://www.codecogs.com/eqnedit.php?latex=e&space;=&space;Z&space;\sqrt{\frac{p(1-p)}{n_0}}&space;=&space;Z&space;\sqrt{\frac{pq}{n_0}}" target="_blank"><img src="https://latex.codecogs.com/gif.latex?e&space;=&space;Z&space;\sqrt{\frac{p(1-p)}{n_0}}&space;=&space;Z&space;\sqrt{\frac{pq}{n_0}}" title="e = Z \sqrt{\frac{p(1-p)}{n_0}} = Z \sqrt{\frac{pq}{n_0}}" /></a> Then given **confidence level** and **margin of error**, reversely the sample size needed per variation can be estimated by cochran formula [[Statistics How To]][Sample Size in Statistics (How to Find it): Excel, Cochran’s Formula, General Tips]: <a href="https://www.codecogs.com/eqnedit.php?latex=n_0&space;=&space;\frac{Z^2&space;pq}{e^2}" target="_blank"><img src="https://latex.codecogs.com/gif.latex?n_0&space;=&space;\frac{Z^2&space;pq}{e^2}" title="n_0 = \frac{Z^2 pq}{e^2}" /></a> Suppose we are doing a study on the inhabitants of a **large** town, and want to find out how many households serve breakfast in the mornings. We don’t have much information on the subject to begin with, so we’re going to assume that half of the families serve breakfast: this gives us **maximum variability. So p = 0.5**. Now let’s say we want 95% confidence, and at least 5%—plus or minus—precision [[Statistics How To]][Sample Size in Statistics (How to Find it): Excel, Cochran’s Formula, General Tips]. A 95 % confidence level gives us Z values of 1.96, per the normal tables, so we get round((1.96/0.05) * (1.96/0.05) * 0.5 * 0.5 ) + 1 = 385 So a random sample of 385 households in our target population should be enough to give us the confidence levels we need. ### 1.B Samll population - modification for the Cochran Formula If the population we’re studying is **small**, we can modify the sample size we calculated in the above formula by using this equation [[Statistics How To]][Sample Size in Statistics (How to Find it): Excel, Cochran’s Formula, General Tips], [[Survey Monkey]][Sample size calculator]: <a href="https://www.codecogs.com/eqnedit.php?latex=n&space;=\frac{n_0}{1&plus;\frac{n_0-1}{N}}" target="_blank"><img src="https://latex.codecogs.com/gif.latex?n&space;=\frac{n_0}{1&plus;\frac{n_0-1}{N}}" title="n =\frac{n_0}{1+\frac{n_0-1}{N}}" /></a> Here `n0` is Cochran’s sample size recommendation, **N is the population size**, and `n` is the new, adjusted sample size. In our earlier example, `n0=385` and if there were just 1000 households in the target population, we would calculate 385 / (1 + ( 384 / 1000 )) = 278 So for this smaller population, all we need are 278 households in our sample; a substantially smaller sample size. This is the size **one your variations** needs to be. So for your email send, if you have one control and one variation, you'll need to double this number. If you had a control and two variations, you'd triple it. (And so on.) [[Ginny Mineo]][How to Determine Your A/B Testing Sample Size & Time Frame] Here are the calculators from [survey system](https://www.surveysystem.com/sscalc.htm) and [survey monkey](https://www.surveymonkey.com/mp/sample-size-calculator/). ### 1.C Examples #### Given a confidence level and width, unknown population standard deviation Example question: 41% of Jacksonville residents said that they had been in a hurricane. How many adults should be surveyed to estimate the true proportion of adults who have been in a hurricane, with a 95% confidence interval 6% wide? z-score for 95% confidence interval is 1.96. The margin of error is given by the half width: 6% / 2 = 0.03. Gven percentage. p = 41% = 0.41, so q = 1-p = 0.59. If you aren’t given phat, use p = q = 50%. So the (1.96/0.03) * (1.96/0.03) * 0.40 * 0.59 = 1033 1,033 people to survey. #### Given a confidence level and width, known population standard deviation <a href="https://www.codecogs.com/eqnedit.php?latex=n&space;=&space;\Big(&space;\frac{Z_{\alpha&space;/2}&space;\sigma}{e}&space;\Big)^2" target="_blank"><img src="https://latex.codecogs.com/gif.latex?n&space;=&space;\Big(&space;\frac{Z_{\alpha&space;/2}&space;\sigma}{e}&space;\Big)^2" title="n = \Big( \frac{Z_{\alpha /2} \sigma}{e} \Big)^2" /></a> Example question: Suppose we want to know the average age of an Florida State College student, plus or minus 0.5 years. We’d like to be 99% confident about our result. From a previous study, we know that the standard deviation for the population is 2.9. (2.58 * 2.9 / 0.5) * (2.58 * 2.9 / 0.5) = 223 ## 2. Page View Example, Required Statistical Power [Udacity](https://www.youtube.com/watch?v=WnQoZzxas-g&t=15s) shows the page view example to calculate sample size. Here we assume population is large enough (for internet, it is true), but we demand statistical power. Assume the conversion rate is about 10%, and we want to run an A/B test. The minimum **effetc size** (practical significance level) to observe is 2%, such that the confidence interval is 8%-12%. Given significance level 5% and statistical power 80%, we can use another [online calculator](https://www.evanmiller.org/ab-testing/sample-size.html), and the interface looks like ![](images/abtest_online_calculator.png) Note the `absolute` is selected to make 8%-12% confidence interval. The online calculator shows at least we need sample size of 3,623 page views per variation (in each group) to see significant results in the AB test. ## 3. Sample Size vs Conversion Rate and Minimum Detectable Effect Predicting how many users we need depends on a few factors, such as how big we think the difference will be between variants, how many variants there are, and what the conversion rates are. **The larger the difference between variants, the more confident you can be that the results are statistically significant with fewer samples.** Here is a table of roughly how many users **per variant** (including baseline) we recommend using at the start of your test [[Apptimize]][How Many Users Do I Need for My A/B Test? Calculate Sample Size and Run Times]: | | Low conversion rates (5%) | Medium conversion rates (15%) | High conversion rates (70%) | | --- | --- | --- | --- | | 10% lift between variants | 30,244 | 9,002 | 684 | | 20% lift between variants | 7,663 | 2,276 | 173 | | 50% lift between variants | 1,273| 375 | | The above numbers are obatined by the [online calculator](https://www.evanmiller.org/ab-testing/sample-size.html) setting 80% power and 5% significance level, and `Relative` in Minimum Detectable Effect. ### Runtimes you can calculate about how long you will need to run your test to see conclusive results [[Apptimize]][How Many Users Do I Need for My A/B Test? Calculate Sample Size and Run Times]: Duration (weeks) = (Nv · Nu ) / (p · M/4 ) * Nv = number of variants * Nu = number of users needed per variant (from the above table) * p = fraction of users in this test (e.g., if this test runs on 5% of users, p = 0.05) * M = MAU (monthly active users) For instance, say you have two variants (baseline, plus one other), 100,000 MAUs, a current conversion rate of 10%, and an expected effect size of 20% (you expect the conversion rate of the new variant to be 12%). Then, if you run the test on 20% of your users, you will probably see conclusive results in about a week and a half. ## Reference * [How Many Users Do I Need for My A/B Test? Calculate Sample Size and Run Times]: https://apptimize.com/blog/2014/01/how-many-users-time/ [[Apptimize] How Many Users Do I Need for My A/B Test? Calculate Sample Size and Run Times](https://apptimize.com/blog/2014/01/how-many-users-time/) * [How to Determine Your A/B Testing Sample Size & Time Frame]: https://blog.hubspot.com/marketing/email-a-b-test-sample-size-testing-time [[Ginny Mineo] How to Determine Your A/B Testing Sample Size & Time Frame](https://blog.hubspot.com/marketing/email-a-b-test-sample-size-testing-time) * [Sample size calculator]: https://www.surveymonkey.com/mp/sample-size-calculator/ [[Survey Monkey] Sample size calculator](https://www.surveymonkey.com/mp/sample-size-calculator/) * [Sample Size in Statistics (How to Find it): Excel, Cochran’s Formula, General Tips]: https://www.statisticshowto.com/probability-and-statistics/find-sample-size/ [[Statistics How To] Sample Size in Statistics (How to Find it): Excel, Cochran’s Formula, General Tips](https://www.statisticshowto.com/probability-and-statistics/find-sample-size/)
C
UTF-8
4,013
3.171875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #if defined(__APPLE__) #include <mach/mach_time.h> #endif // Structure for thread struct thread_data { // Shared value double volatile *p_s; // Lock variable s pthread_mutex_t *p_s_lock; // Number of iterations long int nb_iter; // Number of threads int nb_thread; }; // Thread function void *my_thread_process(void* threadarg) { long int i, j; register double x, y, z; register long int localsum = 0; struct thread_data* my_data; unsigned int rand_state; my_data = (struct thread_data*) threadarg; rand_state = rdtsc(); // Generate random values for (i=0; i<(my_data->nb_iter)/(my_data->nb_thread); i++) { x = (double) rand_r(&rand_state) / RAND_MAX; y = (double) rand_r(&rand_state) / RAND_MAX; z = x*x + y*y; if (z <= 1.0) localsum++; } // Thread asserting the lock on s pthread_mutex_lock(my_data->p_s_lock); // Change the value of s *(my_data->p_s) += localsum ; // Remove the lock pthread_mutex_unlock(my_data->p_s_lock); return NULL; } // Random time cycle int rdtsc() { __asm__ __volatile__("rdtsc"); } int main (int argc, char** argv) { // Total number of hits // long int type since may be over 2^32 long int nb_iter; long int i,j; // Number of threads int nb_process; double pi = 0; #if defined(__APPLE__) // Time elapsed uint64_t t1, t2; float duration; // Get the timebase info mach_timebase_info_data_t info; mach_timebase_info(&info); #elif defined(__linux__) struct timeval chrono1, chrono2; int micro, second; #endif // Posix and time variables struct thread_data* ptr; // the shared variable volatile double s=0; pthread_mutex_t s_lock; pthread_t* ptr_tid; pthread_attr_t attr; void *ret; // Check number of arguments if (argc != 3) { printf("Error: specify arguments as number of threads and iterations\n"); exit(1); } // Assign arguments nb_process = atoi(argv[1]); nb_iter = atol(argv[2]); // Check divisibility if (nb_iter % nb_process != 0) { printf("Error: number of iterations not divisible by number of threads\n"); exit(1); } // nb_process pthreads allocation ptr_tid = (pthread_t*) calloc(nb_process, sizeof(pthread_t)); ptr = (struct thread_data*) calloc(nb_process, sizeof(struct thread_data)); // Initialize the lock variable pthread_mutex_init(&s_lock, NULL); #if defined(__APPLE__) // Initialize time process t1 = mach_absolute_time(); #elif defined(__linux__) // Initialize time process gettimeofday(&chrono1, NULL); // Loop pthreads creation #endif for (i=0; i<nb_process; i++) { ptr[i].p_s = &s; ptr[i].p_s_lock = &s_lock; ptr[i].nb_thread = nb_process; ptr[i].nb_iter = nb_iter; pthread_attr_init(&attr); pthread_create(&ptr_tid[i], &attr, my_thread_process,&ptr[i]); } // Join nb_process pthreads for (j=0; j<nb_process; j++) pthread_join(ptr_tid[j], &ret); #if defined(__APPLE__) // Finished time t2 = mach_absolute_time(); // Time elapsed duration = t2 - t1; // Convert to seconds duration *= info.numer; duration /= info.denom; duration /= 1000000000; #elif defined(__linux__) // Finished time gettimeofday(&chrono2, NULL); // Compute ellapsed time micro = chrono2.tv_usec - chrono1.tv_usec; if (micro < 0) { micro += 1000000; second = chrono2.tv_sec - chrono1.tv_sec - 1; } else second = chrono2.tv_sec - chrono1.tv_sec; #endif // Pi value pi = s/nb_iter; pi *= 4; // Output printf("# Estimation of Pi = %1.8f\n", pi); printf("# Number of tries = %ld\n", nb_iter); #if defined(__APPLE__) printf("# Elapsed Time = %d seconds %d micro\n", (int)duration, (int)((duration-(int)(duration))*1000000)); #elif defined(__linux__) printf("# Elapsed Time = %d seconds %d micro\n", second, micro); #endif return 0; }
Python
UTF-8
2,200
3.390625
3
[]
no_license
import matplotlib import matplotlib.pyplot as plt import numpy as np import json import os #visualization for the artist followers ordered increasingly and average track price #get artist follower count try: dir = os.path.dirname(__file__) full_path = os.path.join(dir,"data.json") in_file = open(full_path, 'r') data = in_file.read() lst_of_dictionary = json.loads(data) in_file.close() except: print("Problem reading the input file") lst_of_dictionary = {} artist_follower_count = [] for d in lst_of_dictionary: followers = d["followers"] artist = d["name"] artist_follower_count.append((artist, followers)) #sort follower count increasingly followers_sorted = sorted(artist_follower_count, key= lambda x: x[1]) #obtain just artist names in that order for the graph artist_sorted = [] for t in followers_sorted: artist_sorted.append(str(t[0])) #get artist average track price try: dir = os.path.dirname(__file__) full_path = os.path.join(dir,"average_track_price_per_artist.txt") in_file = open(full_path, 'r') data = in_file.read() except: print("Problem reading the input file") #get the text file into a usaable formation track_price = [] split_data = data.strip().split("\n") for line in split_data: info = line.strip().split(",") track_price.append((info[0], info[1])) #sort the track prices the same as the artists were sorted - the values of track price and follower count will line up for each artist track_sorted = [] for artist in artist_sorted: for track in track_price: if track[0] in artist: track_sorted.append(float("%.3f" % float(track[1]))) #setting up line graph fig, ax = plt.subplots() ax.plot(artist_sorted, track_sorted, color = "#952748", linewidth = 3) ax.set_facecolor("#ffe7ee") plt.xticks(rotation=20, family='monospace', weight="semibold", size="small") ax.set_xlabel("Artists (increasing in order of follower count)") ax.set_ylabel("Average Track Price", fontname="monospace") ax.set_title("Average Track Price vs. Artist Follwer Count", fontname="monospace", weight="heavy", size=20) ax.grid() #save the figure fig.savefig("trackprice_vis.png") plt.show()
Markdown
UTF-8
4,123
2.953125
3
[ "MIT" ]
permissive
Logistic Regression -baseline classification model model = LogisticRegression() classifiers come with a .predict_proba, which gives the predicted probability of both outcomes so .predict will give you the models answer, and .predict_proba will give you the reason behind the answer .score returns accuracy in classifiers. That's correct_predictions/total_predictions sklearn has cross_val_score(model,x,y,cv=number of crossval groups), which seems to cross validate the training data category encoder -OneHotEncoder will take categorical features and give each of the different observations their own column represented as booleans Feature importance A really cool graph showing feature importance log_reg.fit(X_train_imputed, y_train) coefficients = pd.Series(log_reg.coef_[0], X_train_encoded.columns) plt.figure(figsize=(10,10)) coefficients.sort_values().plot.barh(color='grey'); Scalers scalers put the numerical features into the same range MinMaxScaler() StandardScaler() Pipeline combines all that shit like category encoders, scalers, and even the model into one thing. make_pipeline() there's also pipeline() but make_pipeline() is simpler Baselines and Validation Baseline is the thing youre measuring against. It's like your made up standard that you gotta beat. One baseline that you can do in time features is say that the value will be the same as it was the day/hour/minute/etc. before To get a baseline for classifiers, find your majority class aka whichever there is more of y_train.value_counts(normalize=True) majority_class = y_train.mode()[0] y_pred = [majority_class] * len(y_val) majority_class = y_train.mode()[0] y_pred = [majority_class] * len(y_val) ROC AUC will tell you how much better you are than guessing roc_auc_score(y_val,y_pred) DO THINGS FAST X_train.isnull().sum().sort_values() look for leakage with shallow trees DecisionTreeClassifier(x,y,max_depth=1) Leakage is stuff from the future. I guess features that give too much info. from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(max_depth=2) tree.fit(X_train_numeric, y_train) y_pred_proba = tree.predict_proba(X_val_numeric)[:,1] #[:,1] <-gives only the positive predictions roc_auc_score(y_val,y_pred_proba) import graphviz from sklearn.tree import export_graphviz dot_data = export_graphviz(tree, out_file=None, feature_names=X_train_numeric.columns, class_names=['No', 'Yes'], filled=True, impurity=False, proportion=True) graphviz.Source(dot_data) OneHotEncoder is good for low cardinality: few unique features. 10 is low log regression is a good baseline too. classification metrics: accuracy: (true pos + true neg)/(pred neg + pred post) pred is the true and false combined. precision:True pos/(false pos+ true pos) recall: true pos/ all pos. all pos is true pos and false neg f1: 2*precision*recall/(precision+recall). higher is better rocauc confusion matrix y_pred_proba = cross_val_predict(pipeline, X_train, y_train, cv=3, n_jobs=-1, method='predict_proba')[:,1] from sklearn.metrics import classification_report, confusion_matrix threshold = 0.5 y_pred = y_pred_proba >= threshold print(classification_report(y_train, y_pred)) confusion_matrix(y_train, y_pred) pd.DataFrame(confusion_matrix(y_train, y_pred), columns=['Predicted Negative', 'Predicted Positive'], index=['Actual Negative', 'Actual Positive']) imbalanced classes: to deal with imbalance, we give things weight. goes quite well visually. the fewer things weigh more so that there is balance on the scale. n_samples = 1000 (number of data points) weights = (0.95, 0.05) class_sep = 0.8 (don't know what this is) X, y = make_classification(n_samples=n_samples, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1, weights=weights, class_sep=class_sep, random_state=0) class_weight = None model = LogisticRegression(solver='lbfgs', class_weight=class_weight)
PHP
UTF-8
3,614
2.53125
3
[]
no_license
<?php /** * Created by IntelliJ IDEA. * User: Bill * Date: 8/02/2016 * Time: 11:02 AM * Code to communicate with the RESTfm service to connect to FM and query if any meta records are incomplete * (answers field is empty or null) using Value_Required_Failed_cn field of [WEB] Project Meta Fields layout */ include_once dirname(__DIR__) .DIRECTORY_SEPARATOR ."request-config.php"; //Now include the order.db.php file to remove hardcoded values from that file include_once($fmfiles ."order.db.php"); //init this JSON array container so it can be used almost anywhere $dataErrorRecordMaster = array(); if(isset($_POST['pk'])){ $requestPk = $_POST['pk']; $log->debug("Status on Request was changed to Submitted so check if all Required Meta records have answers"); }else{ $log->error("No PK Sent from calling page"); $dataErrorRecordMaster['error'] = true; $dataErrorRecordMaster['message'] = "No PK Sent from calling page"; echo json_encode($dataErrorRecordMaster); exit(); } //Now build an HTTP client using cUrl commands $requestPkFieldName = "_fk_Request_pk_ID"; $encodeQuery = $requestPkFieldName ."=" .$requestPk; $errorField = "Value_Required_Fail_cn"; $encodeLayoutName = urlencode("[WEB] Project Meta Fields"); $databaseName = "PRO_ORDER"; $orderUrl = $restFMPath .$databaseName ."/layout/" .$encodeLayoutName .".json?RFMsF1=" .$requestPkFieldName ."&RFMsV1" ."=" .$requestPk ."&RFMsF2=" .$errorField ."&RFMsV2=1"; $log->debug("URL: " .$orderUrl); //Pro_Order username password cUrl will encrypt the credentials $orderUsername = $DB_USER; $orderPassword = $DB_PASS; $opts = array( 'http'=>array( 'method'=>'GET', 'header' => "Authorization: Basic " . base64_encode("$orderUsername:$orderPassword")) ); $context = stream_context_create($opts); //1. Using curl get the JSON data back from PHP RESTfm call //Using @ symbnol to suppress Warniing message and to capture the return message //RESTfm has confused data errors No Records Found with HTTP error $data = @file_get_contents($orderUrl, false, $context); //$data = file_get_contents($orderUrl, false, $context); //2. If we have found an error test for which error (serious or just no documents found) if($data === false){ if(in_array("X-RESTfm-FM-Status: 401", $http_response_header)){ $log->debug("Returned 401 not found error"); echo null; // send an empty null back to receiver exit(); }else{ $error = error_get_last(); $log->error("http error code3: " .$http_response_header[4]); $log->error("Now has @ symbol HTTP request failed. Error was: " . $error['message']); $dataErrorRecordMaster['error'] = true; $dataErrorRecordMaster['message'] = $error['message']; echo json_encode($dataErrorRecordMaster); exit(); } } //3. Decode the JSON returned $decodedJson = json_decode($data); $log->debug("Last JSON Error: " .json_last_error() ." Message " .json_last_error_msg()); //4. Access the data element of the JSON array (FM records in JSON) $dataRecords = $decodedJson->{'data'}; $dataRecordIndex = 1; foreach($dataRecords as $records) { $dataErrorRecord = array(); foreach ($records as $key => $value) { if($key == "Deliverable_Description_ct"){ $dataErrorRecord["Deliverable_Description_ct"] = $value; } if($key == 'Order_n'){ $dataErrorRecord['Order_n'] = $value; } } $dataErrorRecordMaster[$dataRecordIndex] = $dataErrorRecord; $dataRecordIndex++; } echo json_encode($dataErrorRecordMaster); exit(); ?>
Markdown
UTF-8
1,015
3.046875
3
[]
no_license
# Events and event handlers - 자바스크립트는 html, css 변경 외에도 이벤트에 반응하기 위해 만들어짐 - click, resize, submit, before, 등등 ``` const title = document.querySelector("#title"); function handleResize(){ console.log("I have been resized") } window.addEventListener("resize", handleResize); ``` - 자바스크립트는 코드에서 명시한 이벤트를 받기 위해 대기하고 있음 - handleResize : () 없이 사용하기 되면 함수를 내가 필요한 시점에 부르겠다는 것 -> 이 경우 resize되었을 때 부름 - handleResize() : ()와 함께 사용하게 되면 함수를 지금 직시 시행하라는 것 -> 이 경우 resize 되지 않아도 바로 시행함 - 이벤트를 다룰 함수를 만들 때마다 event, e 등의 인자를 자바스크립트는 자동으로 받아옴 ``` const title = document.querySelector("#title"); function handleClick(){ title.style.color = "blue"; } title.addEventListener("click", handleClick); ```
JavaScript
UTF-8
1,701
2.8125
3
[]
no_license
import { useState, useEffect } from "react"; import { v4 as uuidv4 } from "uuid"; import Item from "./components/Item"; import Spinner from "./components/Spinner"; function App() { const [items, setItems] = useState([]); const [newitem, setNewItem] = useState({ id: uuidv4(), title: "", }); const getitems = async () => { if (localStorage.getItem("items")) { setItems(JSON.parse(localStorage.getItem("items"))); } else { const res = await fetch("https://fakestoreapi.com/products?limit=3"); const result = await res.json(); setItems(result); } }; const readNewItem = (e) => { setNewItem({ ...newitem, title: e.target.value, }); }; const addNewItem = (e) => { e.preventDefault(); setItems([...items, newitem]); localStorage.setItem("items", JSON.stringify([...items, newitem])); setNewItem({ id: uuidv4(), title: "", }); }; useEffect(() => { getitems(); }, []); return ( <div className="App-container"> <div className="main-container"> <div className="form-container"> <h1>products list</h1> <form onSubmit={addNewItem}> <input type="text" name="title" value={newitem.title} placeholder="new item" onChange={readNewItem} /> <button type="submit">add</button> </form> </div> <main> {items.length > 0 ? ( items.map((item) => <Item item={item} key={item.id} />) ) : ( <Spinner /> )} </main> </div> </div> ); } export default App;
Go
UTF-8
1,218
3.359375
3
[]
no_license
package algorithms import "sort" func twoSum(nums []int, target int) []int { numSorted := make([]int, len(nums)) for i, num := range nums { numSorted[i] = num } sort.Ints(numSorted) numFirst, numSec := 0, 0 found := false for i, num := range numSorted { if num < 0 { if numSorted[len(numSorted)-1] > target { numTarget := target - num for iNext := len(numSorted) - 1; iNext >= 0; iNext-- { numNext := numSorted[iNext] if numNext < numTarget { break } else if numNext == numTarget { found = true numFirst = num numSec = numNext break } } } } else { numTarget := target - num for _, numNext := range numSorted[i+1:] { if numNext > numTarget { break } else if numNext == numTarget { found = true numFirst = num numSec = numNext break } } } if found { break } } iFirst, iSec := -1, -1 for i, num := range nums { if iFirst == -1 && num == numFirst { iFirst = i continue } if iSec == -1 && num == numSec { iSec = i continue } if iFirst != -1 && iSec != -1 { break } } if iFirst > iSec { iFirst, iSec = iSec, iFirst } return []int{iFirst, iSec} }
C#
UTF-8
1,865
3.703125
4
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DayOfTheProgrammer { class Program { static void Main(string[] args) { int year = 2017; string date = dayOfProgrammer(year); Console.WriteLine("result: date " + date); } // Complete the dayOfProgrammer function below. static string dayOfProgrammer(int year) { DateTime dateTime = new DateTime(); bool leapYear = true; // check if year belongs to Julian if (year < 1919) { //Console.WriteLine("year is Julian"); if(leapYear) { //Console.WriteLine("Julian leap year"); dateTime = new DateTime(year, 9, 12); } else { dateTime = new DateTime(year, 9, 13); } } if(year >= 1919) { //Console.WriteLine("year is Gregorian"); if (leapYear) { //Console.WriteLine("Gregorian leap year"); dateTime = new DateTime(year, 9, 12); } else { //Console.WriteLine("in Gregorian non-leap year"); dateTime = new DateTime(year, 9, 13); } } //Console.WriteLine(dateTime); // Console.WriteLine(dateTime.ToString("dd.MM.yyyy")); return dateTime.ToString("dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture); } } }
Ruby
UTF-8
5,487
2.90625
3
[ "MIT", "Ruby" ]
permissive
# frozen_string_literal: true require "active_model/validations/resolve_value" module ActiveModel module Validations class LengthValidator < EachValidator # :nodoc: include ResolveValue MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :too_short, :too_long] def initialize(options) if range = (options.delete(:in) || options.delete(:within)) raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range) options[:minimum] = range.min if range.begin options[:maximum] = (range.exclude_end? ? range.end - 1 : range.end) if range.end end if options[:allow_blank] == false && options[:minimum].nil? && options[:is].nil? options[:minimum] = 1 end super end def check_validity! keys = CHECKS.keys & options.keys if keys.empty? raise ArgumentError, "Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option." end keys.each do |key| value = options[key] unless (value.is_a?(Integer) && value >= 0) || value == Float::INFINITY || value == -Float::INFINITY || value.is_a?(Symbol) || value.is_a?(Proc) raise ArgumentError, ":#{key} must be a non-negative Integer, Infinity, Symbol, or Proc" end end end def validate_each(record, attribute, value) value_length = value.respond_to?(:length) ? value.length : value.to_s.length errors_options = options.except(*RESERVED_OPTIONS) CHECKS.each do |key, validity_check| next unless check_value = options[key] if !value.nil? || skip_nil_check?(key) check_value = resolve_value(record, check_value) next if value_length.public_send(validity_check, check_value) end errors_options[:count] = check_value default_message = options[MESSAGES[key]] errors_options[:message] ||= default_message if default_message record.errors.add(attribute, MESSAGES[key], **errors_options) end end private def skip_nil_check?(key) key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil? end end module HelperMethods # Validates that the specified attributes match the length restrictions # supplied. Only one constraint option can be used at a time apart from # +:minimum+ and +:maximum+ that can be combined together: # # class Person < ActiveRecord::Base # validates_length_of :first_name, maximum: 30 # validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind" # validates_length_of :fax, in: 7..32, allow_nil: true # validates_length_of :phone, in: 7..32, allow_blank: true # validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name' # validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters' # validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me." # validates_length_of :words_in_essay, minimum: 100, too_short: 'Your essay must be at least 100 words.' # # private # def words_in_essay # essay.scan(/\w+/) # end # end # # Constraint options: # # * <tt>:minimum</tt> - The minimum size of the attribute. # * <tt>:maximum</tt> - The maximum size of the attribute. Allows +nil+ by # default if not used with +:minimum+. # * <tt>:is</tt> - The exact size of the attribute. # * <tt>:within</tt> - A range specifying the minimum and maximum size of # the attribute. # * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>. # # Other options: # # * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation. # * <tt>:allow_blank</tt> - Attribute may be blank; skip validation. # * <tt>:too_long</tt> - The error message if the attribute goes over the # maximum (default is: "is too long (maximum is %{count} characters)"). # * <tt>:too_short</tt> - The error message if the attribute goes under the # minimum (default is: "is too short (minimum is %{count} characters)"). # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> # method and the attribute is the wrong size (default is: "is the wrong # length (should be %{count} characters)"). # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, # <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate # <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message. # # There is also a list of default options supported by every validator: # +:if+, +:unless+, +:on+, and +:strict+. # See ActiveModel::Validations::ClassMethods#validates for more information. def validates_length_of(*attr_names) validates_with LengthValidator, _merge_attributes(attr_names) end alias_method :validates_size_of, :validates_length_of end end end
C++
UTF-8
10,241
2.65625
3
[]
no_license
#include <digitalWriteFast.h> #include <eRCaGuy_Timer2_Counter.h> #include <Servo.h> // ============================== // CONSTANTS // ============================== #define DEBUG 1 #define NR_CHANNEL_LIST 5 #define MIN_ANGLE_DIFF 2 // Channel threshold values for joysticks and toggle switches #define CH_STICK_MIN 1000 #define CH_STICK_MAX 1950 #define CH_SWITCH_LOW 1200 #define CH_SWITCH_HIGH 1800 // Pin and interrupt numbers for an Arduino Mega 2560 // Channel 1: right horizontal #define CH1_PIN 2 #define CH1_INTERRUPT 0 // Channel 2: left vertical #define CH2_PIN 3 #define CH2_INTERRUPT 1 // Channel 3: right vertical #define CH3_PIN 18 #define CH3_INTERRUPT 5 // Channel 4: left horizontal #define CH4_PIN 19 #define CH4_INTERRUPT 4 // Channel 5: left switch #define CH5_PIN 20 #define CH5_INTERRUPT 3 // Channel 6: right switch #define CH6_PIN 21 #define CH6_INTERRUPT 2 // Output pins // Servo 1 #define SERVO1_PIN 22 #define SERVO1_DEFAULT 90 #define SERVO1_MIN 0 #define SERVO1_MAX 180 // Servo 2 #define SERVO2_PIN 23 #define SERVO2_DEFAULT 90 #define SERVO2_MIN 9 #define SERVO2_MAX 163 // Servo 3 #define SERVO3_PIN 50 #define SERVO3_DEFAULT 90 #define SERVO3_MIN 9 #define SERVO3_MAX 163 // LED 1 #define LED1_PIN 52 #define LED1_DEFAULT LOW // LED 2 #define LED2_PIN 53 #define LED2_DEFAULT LOW // SWITCH #define SWITCH_PIN 39 // ============================== // VARIABLES // ============================== // Channel interrupt variables volatile unsigned long lastInterrupt; volatile unsigned long ch1Timer; volatile int ch1Status[NR_CHANNEL_LIST]; volatile int ch1Counter; volatile unsigned long ch2Timer; volatile int ch2Status[NR_CHANNEL_LIST]; volatile int ch2Counter; volatile unsigned long ch3Timer; volatile int ch3Status[NR_CHANNEL_LIST]; volatile int ch3Counter; volatile unsigned long ch4Timer; volatile int ch4Status[NR_CHANNEL_LIST]; volatile int ch4Counter; volatile unsigned long ch5Timer; volatile int ch5Status[NR_CHANNEL_LIST]; volatile int ch5Counter; volatile unsigned long ch6Timer; volatile int ch6Status[NR_CHANNEL_LIST]; volatile int ch6Counter; boolean hasResetOutputs = false; // Servos Servo servo1; Servo servo2; Servo servo3; // ============================== // MAIN // ============================== void setup() { // Setup eRCaGuy_Timer2_Counter timer2.setup(); #if DEBUG > 0 Serial.begin(9600); #endif setupReceiver(); setupServos(); setupLeds(); setupInputs(); resetOutputs(); } void loop() { // Check if transmitter is active boolean transmitter_active = checkActivity(); #if DEBUG > 0 String statusString = getStatusString(); Serial.print("Active: "); Serial.print(transmitter_active); Serial.print(", "); Serial.print(statusString); #endif if (transmitter_active) { hasResetOutputs = false; digitalWrite(LED1_PIN, LOW); // Translate the current value to a percentage and change it to a valid value (>= 0 & <= 100) float percentage = (float)(getChannelValue(ch1Status, ch1Counter) - CH_STICK_MIN) / (CH_STICK_MAX - CH_STICK_MIN); if (percentage > 100.0) { percentage = 100.0; } if (percentage < 0.0) { percentage = 0.0; } // Calculate angle based on percentage int angle = (int)round(SERVO1_MIN + percentage * (SERVO1_MAX - SERVO1_MIN)); servoWrite(servo1, angle); #if DEBUG > 0 Serial.print(", S1: "); Serial.print(angle); Serial.print(", "); Serial.print(percentage); #endif // Translate the current value to a percentage and change it to a valid value (>= 0 & <= 100) percentage = (float)(getChannelValue(ch2Status, ch2Counter) - CH_STICK_MIN) / (CH_STICK_MAX - CH_STICK_MIN); if (percentage > 100.0) { percentage = 100.0; } if (percentage < 0.0) { percentage = 0.0; } // Calculate angle based on percentage angle = (int)round(SERVO2_MIN + percentage * (SERVO2_MAX - SERVO2_MIN)); servoWrite(servo2, angle); #if DEBUG > 0 Serial.print(", S2: "); Serial.print(angle); Serial.print(", "); Serial.print(percentage); #endif // Translate the current value to a percentage and change it to a valid value (>= 0 & <= 100) percentage = (float)(getChannelValue(ch3Status, ch3Counter) - CH_STICK_MIN) / (CH_STICK_MAX - CH_STICK_MIN); if (percentage > 100.0) { percentage = 100.0; } if (percentage < 0.0) { percentage = 0.0; } // Calculate angle based on percentage angle = (int)round(SERVO3_MIN + percentage * (SERVO3_MAX - SERVO3_MIN)); servoWrite(servo3, angle); #if DEBUG > 0 Serial.print(", S3: "); Serial.print(angle); Serial.print(", "); Serial.print(percentage); #endif int value = digitalRead(SWITCH_PIN); digitalWrite(LED2_PIN, value); } else { digitalWrite(LED1_PIN, HIGH); resetOutputs(); } #if DEBUG > 0 Serial.println(""); #endif } // ============================== // SETUP // ============================== void setupReceiver() { pinMode(CH1_PIN, INPUT); attachInterrupt(CH1_INTERRUPT, ch1_interrupt, CHANGE); pinMode(CH2_PIN, INPUT); attachInterrupt(CH2_INTERRUPT, ch2_interrupt, CHANGE); pinMode(CH3_PIN, INPUT); attachInterrupt(CH3_INTERRUPT, ch3_interrupt, CHANGE); pinMode(CH4_PIN, INPUT); attachInterrupt(CH4_INTERRUPT, ch4_interrupt, CHANGE); pinMode(CH5_PIN, INPUT); attachInterrupt(CH5_INTERRUPT, ch5_interrupt, CHANGE); pinMode(CH6_PIN, INPUT); attachInterrupt(CH6_INTERRUPT, ch6_interrupt, CHANGE); } void setupServos() { servo1.attach(SERVO1_PIN); servo2.attach(SERVO2_PIN); servo3.attach(SERVO3_PIN); } void setupLeds() { pinMode(LED1_PIN, OUTPUT); pinMode(LED2_PIN, OUTPUT); } void setupInputs() { pinMode(SWITCH_PIN, INPUT); } // ============================== // RESET // ============================== void resetOutputs() { if (! hasResetOutputs) { servo1.write(SERVO1_DEFAULT); servo2.write(SERVO2_DEFAULT); servo3.write(SERVO3_DEFAULT); digitalWrite(LED1_PIN, LED1_DEFAULT); digitalWrite(LED2_PIN, LED2_DEFAULT); hasResetOutputs = true; } } // ============================== // HELP FUNCTIONS // ============================== boolean checkActivity() { // Check the value of the channels which send the status of the switches // to see if the transmitter is active int ch5Value = getChannelValue(ch5Status, ch5Counter); int ch6Value = getChannelValue(ch6Status, ch6Counter); return !((ch5Status == 0 & ch6Status == 0) | (CH_SWITCH_LOW < ch5Value & ch5Value < CH_SWITCH_HIGH & CH_SWITCH_LOW < ch6Value & ch6Value < CH_SWITCH_HIGH)); } int getChannelValue(volatile int* channelStatus, volatile int& channelCounter) { // Calculates the value of a channel by taking the weighted average of the NR_CHANNEL_LIST // last measurements, giving a higher weight to more recent measurements int value = 0; // Don't allow interrupts uint8_t SREG_old = SREG; cli(); // Iterate over the status list for (int i = 0; i < NR_CHANNEL_LIST; i++) { value += (i + 1) * channelStatus[(channelCounter + i) % NR_CHANNEL_LIST]; } // Allow interrupts again SREG = SREG_old; // Return the average return (2 * value) / (NR_CHANNEL_LIST * (NR_CHANNEL_LIST + 1)); } String getStatusString() { String ss = "CH1: "; ss += getChannelValue(ch1Status, ch1Counter); ss += ", CH2: "; ss += getChannelValue(ch2Status, ch2Counter); ss += ", CH3: "; ss += getChannelValue(ch3Status, ch3Counter); ss += ", CH4: "; ss += getChannelValue(ch4Status, ch4Counter); ss += ", CH5: "; ss += getChannelValue(ch5Status, ch5Counter); ss += ", CH6: "; ss += getChannelValue(ch6Status, ch6Counter); return ss; } void servoWrite(Servo& servo, int angle) { // Write the angle to the given servo if the difference with the current angle is large enough if (abs(servo.read() - angle) > MIN_ANGLE_DIFF) { servo.write(angle); } } // ============================== // ISR // ============================== // Interrupt service routines for reading the status of the channels void ch1_interrupt() { // Use timer2 to get the current time // get_count returns the count in 0.5 microseconds lastInterrupt = timer2.get_count()/2; // digitalReadFast instead of digitalRead for faster ISRs // This function needs a constant instead of a variable as parameter // => ISR for each channel instead of one function if (digitalReadFast(CH1_PIN) == HIGH) { // If high, save current time ch1Timer = lastInterrupt; } else { // If low, calculate length of high pulse ch1Status[ch1Counter] = (volatile int)(lastInterrupt - ch1Timer); // Increase counter to always replace the oldest measurement ch1Counter = (ch1Counter + 1) % NR_CHANNEL_LIST; } } void ch2_interrupt() { lastInterrupt = timer2.get_count()/2; if (digitalReadFast(CH2_PIN) == HIGH) { ch2Timer = lastInterrupt; } else { ch2Status[ch2Counter] = (volatile int)(lastInterrupt - ch2Timer); ch2Counter = (ch2Counter + 1) % NR_CHANNEL_LIST; } } void ch3_interrupt() { lastInterrupt = timer2.get_count()/2; if (digitalReadFast(CH3_PIN) == HIGH) { ch3Timer = lastInterrupt; } else { ch3Status[ch3Counter] = (volatile int)(lastInterrupt - ch3Timer); ch3Counter = (ch3Counter + 1) % NR_CHANNEL_LIST; } } void ch4_interrupt() { lastInterrupt = timer2.get_count()/2; if (digitalReadFast(CH4_PIN) == HIGH) { ch4Timer = lastInterrupt; } else { ch4Status[ch4Counter] = (volatile int)(lastInterrupt - ch4Timer); ch4Counter = (ch4Counter + 1) % NR_CHANNEL_LIST; } } void ch5_interrupt() { lastInterrupt = timer2.get_count()/2; if (digitalReadFast(CH5_PIN) == HIGH) { ch5Timer = lastInterrupt; } else { ch5Status[ch5Counter] = (volatile int)(lastInterrupt - ch5Timer); ch5Counter = (ch5Counter + 1) % NR_CHANNEL_LIST; } } void ch6_interrupt() { lastInterrupt = timer2.get_count()/2; if (digitalReadFast(CH6_PIN) == HIGH) { ch6Timer = lastInterrupt; } else { ch6Status[ch6Counter] = (volatile int)(lastInterrupt - ch6Timer); ch6Counter = (ch6Counter + 1) % NR_CHANNEL_LIST; } }
PHP
UTF-8
1,646
2.59375
3
[]
no_license
<?php /** * 微博热度趋势 */ class WeiboTrendAction extends CAction { public function run($period, $id) { if (! in_array ( $period, array ( '24', '48', 'week' ) )) { header ( 'Content-type: application/json' ); echo json_encode ( array ( 'error' => '参数错误' ) ); return; } $end_date = date ( 'Y-m-d' ); switch ($period) { case 24 : $start_date = date ( 'Y-m-d', strtotime ( $end_date ) ); break; case 48 : $start_date = date ( 'Y-m-d', strtotime ( $end_date ) - 86400 ); break; case 'week' : $start_date = date ( 'Y-m-d', strtotime ( $end_date ) - 86400 * 6 ); break; } $end_date = date ( 'Y-m-d', strtotime ( $end_date ) + 86400 ); $weibo_model = new WeiboModel (); $data = $weibo_model->query_weibo_trend_by_id ( $id, $start_date, $end_date ); if (! empty ( $data )) { foreach ( $data as $key => $value ) { $xaxis [] = $key; $forward_array [] = $value ['forward_count']; $comment_array [] = $value ['comment_count']; } $result ['xAxis'] = array ( 'categories' => $xaxis ); $result ['series'] = array ( array ( 'name' => '转发量', 'data' => $forward_array ), array ( 'name' => '评论量', 'data' => $comment_array ) ); $json = json_encode ( array ( 'success' => true, 'result' => $result ) ); } else { $json = json_encode ( array ( 'success' => true, 'result' => array ( 'xAxis' => array (), 'series' => array () ) ) ); } header ( 'Content-type: application/json' ); echo $json; return; } }
JavaScript
UTF-8
4,506
2.921875
3
[]
no_license
function addWelcomeTab(){ if (window.localStorage.length == 0) { let welcome = { title : 'Welcome!', text : `Each project you create will have it's own tab! You can add projects by clicking the green plus at the top! Each project can have its own tasks to be added below. Each tasks can have notes to give you a more specific look. Done with a task? Check it off! Don't need a task? Click it off. You can do the same thing with projects. If you've complete it, check it off. Don't need it anymore? Remove it. What are you waiting for? Start managing!`, complete: false, tasks : { 'Add a project' : { title : 'Add a project', text : 'To add a project, click the green plus at the top of display!', complete : false, priority: "!", id : 'jskdhtfaCXWE' }, 'Add a task' : { title : 'Add a task', text : 'To add a task, click the green plus in the task section to the left!', complete : false, priority: "!", id : 'seljkhrkjhDFSDF' }, 'Complete a task' : { title : 'Complete a task', text : `To mark a task completed, click the circle to the left of it! The same can be done with projects, by clicking in the top left corner of their tab!`, complete : false, priority: "!", id : 'seljkhrkdfdfjhDFSDF' }, 'Clearing all projects' : { title : 'Clearing all projects', text : `If at any point you'd like to clear all your projects, click the "clear all" button in the top left corner of the page. But be careful, your projects and progress will be permanently removed!`, complete : false, priority: "!", id : 'dfklhjdfjhfe' } } } window.localStorage.setItem('Welcome!',JSON.stringify(welcome)) } else { console.log('Welcome Back!') } } function makeExistingTabsClickable(){ let titleTab = document.getElementsByClassName('title-tab') for (let i = 0; i < titleTab.length; i++){ titleTab[i].addEventListener('click',function(e){ makeTabClickable(this) }) } } function makeExistingTitlesCompleteable(){ let tasks = document.getElementsByClassName('title-tab') for (let i = 0; i < tasks.length; i++){ tasks[i].childNodes[0].addEventListener('click',function(e){ makeTitlesCompletable(this) }) } } function makeExistingTasksHoverable(){ let tasks = document.getElementsByClassName('task') let notes = document.getElementsByClassName('note') for (let i = 0; i < tasks.length; i++){ tasks[i].addEventListener('mouseover',function(e){ let taskID = this.getAttribute('taskID') let noteID = document.getElementsByClassName('noteID' + taskID)[0] for (let x = 0; x < notes.length; x++){ notes[x].classList.remove('active-note') } noteID.classList.add('active-note') }) } } function makeExistingTasksCompleteable(){ let tasks = document.getElementsByClassName('task') for (let i = 0; i < tasks.length; i++){ tasks[i].childNodes[0].addEventListener('click',function(e){ let taskCheck = this.childNodes[0] let taskParent = this.parentNode if (taskCheck.classList.length == 3){ taskCheck.classList.remove('taskComplete') taskParent.childNodes[1].style['color'] = 'black' } else { taskCheck.classList.add('taskComplete') taskParent.childNodes[1].style['color'] = 'green' } }) } } function makeExistingBoardFunctional(){ makeExistingTabsClickable() makeExistingTasksHoverable() makeExistingTasksCompleteable() makeExistingTitlesCompleteable() } export {addWelcomeTab, makeExistingBoardFunctional}
Python
UTF-8
651
2.65625
3
[]
no_license
import consts import glob, os from docx2pdf import convert import time import document if __name__ == '__main__': # update_player_data() # call every once in a while to keep this up to date filename = 'week' + str(consts.WEEK()) + 'results' print("Removing any previous files") for f in glob.glob("*.docx"): os.remove(f) for f in glob.glob("*.pdf"): os.remove(f) time.sleep(5) print("Creating new docx file") document.create_docx(filename + '.docx') time.sleep(2.5) print("Converting new docx file to a PDF file") if os.path.exists(filename + '.docx'): convert(filename + '.docx')
PHP
UTF-8
535
2.546875
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <?php try { $bdd = new PDO('mysql:host=localhost:3307;dbname=dsi22_g1_2019;charset=utf8', 'root', ''); } catch (Exception $e) { die('Erreur : ' . $e->getMessage()); } $info= $bdd->query('DELETE * FROM students WHERE id:=num LIMIT 1'); ?> </body> </html>
Python
UTF-8
360
2.546875
3
[]
no_license
import requests from m5stack import lcd r = requests.get('http://www.example.com') def test_requests_http_example(): r = requests.get('http://www.example.com') if (r[0] != 200): lcd.print('error found during fetching www.example.com with requests lib\n') else: lcd.print('test request to www.example.com done\n') test_requests_http_example()
Shell
UTF-8
848
2.640625
3
[]
no_license
#!/bin/bash cd /var/lib/jenkins/jobs/Caramel/jobs/ cd "AM traffic Test Suits" cd builds buildnumber=$(echo `ls -lrt | grep lastSuccessfulBuild | cut -d" " -f14`) cd $buildnumber rm -rf /home/jenkins/testcase/AmTrafficReport grep -n "tests total\|test total" log | cut -d":" -f1 > /home/jenkins/testcase/file3 for i in `cat /home/jenkins/testcase/file3` do head -$i log | tail -3 >> /home/jenkins/testcase/AmTrafficReport echo "-----------------------------------------------------------------------------------------------------" >> /home/jenkins/testcase/AmTrafficReport done cat /home/jenkins/testcase/AmTrafficReport | mail -s "AM Traffic Test Suit Report for build - $buildnumber" "rakumar@radisys.com,sakumar@radisys.com,OrgFE-CCMP-Dev@radisys.com,OrgFE-OVSDev@radisys.com,OrgFE-NPU-EZDRV-Dev@radisys.com,OrgITRelTeam@radisys.com,schaudhu@radisys.com" #cat /home/jenkins/testcase/AmTrafficReport | mail -s "AM Report for build - $buildnumber" "sakumar@radisys.com"
C#
UTF-8
10,468
3.09375
3
[]
no_license
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using DBLibrary.DAO; using DBLibrary.Entities; namespace GamesLibrary.ConnectFour { /// <summary> /// Handles the logic and the validation for the game. /// </summary> public class ConnectFour : Game { ConnectBot bot; ConnectPlayer player; GameBoard board; bool win = false; /// <summary> /// Constructor for the connect four class, sets game ID to CON /// </summary> /// <param name="bot">ConnectBot that the player will play against</param> /// <param name="player">ConnectPlayer that the player will use</param> /// <param name="board">Board that will keep track of the tiles</param> public ConnectFour(ConnectBot bot, ConnectPlayer player, GameBoard board) { this.bot = bot; this.player = player; this.board = board; GameID = "CON"; } /// <summary> /// Sets the board to the default values /// </summary> public void NewGame() { board.Reset(); } /// <summary> /// Modifies the GameResult to indicate who won the game, push is a tie. /// </summary> /// <param name="owner">Symbolizes who won the game</param> public void EndGame(int owner) { ResultDAO dao = new ResultDAO(ConfigurationManager.ConnectionStrings["myConn"].ConnectionString); if (owner == 1) { this.GameResult = DBLibrary.GameResult.PLAYERWIN; dao.AddResult(new Result("CON", player.PlayerID, 1)); } else if (owner == 2) { this.GameResult = DBLibrary.GameResult.AIWIN; dao.AddResult(new Result("CON", player.PlayerID, 0)); } else { this.GameResult = DBLibrary.GameResult.PUSH; } } /// <summary> /// Checks if 4 tiles are conencted on the board. /// </summary> /// <param name="owner">owner of the tiles, will be either 1 or 2</param> /// <param name="board">board to check the tiles of</param> /// <returns>integer to show who won, returns 2 if a tie</returns> public int CheckWin(int owner, GameBoard board) { bool win = false; int count = 0; //checking vertical connections for (int x = 0; x < 6; x++) { for (int y = 0; y < 7; y++) { if (board.OpenCells[x, y] == owner) { count++; if (count == 4) { win = true; break; } } else { count = 0; } } if (count == 4) break; else count = 0; } count = 0; //checking horizontal connections for (int y = 0; y < 7; y++) { for (int x = 0; x < 6; x++) { if (board.OpenCells[x, y] == owner) { count++; if (count == 4) { win = true; break; } } else { count = 0; } } if (count == 4) break; else count = 0; } //checking the diagonals from top left to bottom right count = 0; for (int i = 0; i < 6; i++) { if (board.OpenCells[i, i] == owner) { count++; if (count == 4) { win = true; } } else { count = 0; } } if (board.OpenCells[0, 1] == owner && board.OpenCells[1, 2] == owner && board.OpenCells[2, 3] == owner && board.OpenCells[3, 4] == owner) { win = true; } else if (board.OpenCells[0, 2] == owner && board.OpenCells[1, 3] == owner && board.OpenCells[2, 4] == owner && board.OpenCells[3, 5] == owner) { win = true; } else if (board.OpenCells[0, 3] == owner && board.OpenCells[1, 4] == owner && board.OpenCells[2, 5] == owner && board.OpenCells[3, 6] == owner) { win = true; } else if (board.OpenCells[1, 0] == owner && board.OpenCells[2, 1] == owner && board.OpenCells[3, 2] == owner && board.OpenCells[4, 3] == owner) { win = true; } else if (board.OpenCells[1, 2] == owner && board.OpenCells[2, 3] == owner && board.OpenCells[3, 4] == owner && board.OpenCells[4, 5] == owner) { win = true; } else if (board.OpenCells[1, 3] == owner && board.OpenCells[2, 4] == owner && board.OpenCells[3, 5] == owner && board.OpenCells[4, 6] == owner) { win = true; } else if (board.OpenCells[2, 0] == owner && board.OpenCells[3, 1] == owner && board.OpenCells[4, 2] == owner && board.OpenCells[5, 3] == owner) { win = true; } else if (board.OpenCells[2, 1] == owner && board.OpenCells[3, 2] == owner && board.OpenCells[4, 3] == owner && board.OpenCells[5, 4] == owner) { win = true; } else if (board.OpenCells[2, 2] == owner && board.OpenCells[3, 3] == owner && board.OpenCells[4, 4] == owner && board.OpenCells[5, 5] == owner) { win = true; } else if (board.OpenCells[2, 3] == owner && board.OpenCells[3, 4] == owner && board.OpenCells[4, 5] == owner && board.OpenCells[5, 6] == owner) { win = true; } //checking the diagonals from right to left else if (board.OpenCells[0, 6] == owner && board.OpenCells[1, 5] == owner && board.OpenCells[2, 4] == owner && board.OpenCells[3, 3] == owner) { win = true; } else if (board.OpenCells[0, 5] == owner && board.OpenCells[1, 4] == owner && board.OpenCells[2, 3] == owner && board.OpenCells[3, 2] == owner) { win = true; } else if (board.OpenCells[0, 4] == owner && board.OpenCells[1, 3] == owner && board.OpenCells[2, 2] == owner && board.OpenCells[3, 1] == owner) { win = true; } else if (board.OpenCells[0, 3] == owner && board.OpenCells[1, 2] == owner && board.OpenCells[2, 1] == owner && board.OpenCells[3, 0] == owner) { win = true; } else if (board.OpenCells[0, 3] == owner && board.OpenCells[1, 2] == owner && board.OpenCells[2, 1] == owner && board.OpenCells[3, 0] == owner) { win = true; } else if (board.OpenCells[1, 6] == owner && board.OpenCells[2, 5] == owner && board.OpenCells[3, 4] == owner && board.OpenCells[4, 3] == owner) { win = true; } else if (board.OpenCells[1, 5] == owner && board.OpenCells[2, 4] == owner && board.OpenCells[3, 3] == owner && board.OpenCells[4, 2] == owner) { win = true; } else if (board.OpenCells[1, 4] == owner && board.OpenCells[2, 3] == owner && board.OpenCells[3, 2] == owner && board.OpenCells[4, 1] == owner) { win = true; } else if (board.OpenCells[1, 3] == owner && board.OpenCells[2, 2] == owner && board.OpenCells[3, 1] == owner && board.OpenCells[4, 0] == owner) { win = true; } else if (board.OpenCells[2, 6] == owner && board.OpenCells[3, 5] == owner && board.OpenCells[4, 4] == owner && board.OpenCells[5, 3] == owner) { win = true; } else if (board.OpenCells[2, 5] == owner && board.OpenCells[3, 4] == owner && board.OpenCells[4, 3] == owner && board.OpenCells[5, 2] == owner) { win = true; } else if (board.OpenCells[2, 4] == owner && board.OpenCells[3, 3] == owner && board.OpenCells[4, 2] == owner && board.OpenCells[5, 1] == owner) { win = true; } else if (board.OpenCells[2, 3] == owner && board.OpenCells[3, 2] == owner && board.OpenCells[4, 1] == owner && board.OpenCells[5, 0] == owner) { win = true; } count = 0; for (int x = 0; x < 6; x++) { for (int y = 0; y < 7; y++) { if (board.OpenCells[x, y] != 0) { count++; } else { count = 0; } } } if (count == 42) { return 2; } if (win) { return 1; } else return 0; } } }
Swift
UTF-8
1,776
2.84375
3
[]
no_license
// ViewController.swift // UnitTesting-PowerPlant // Created by Eric Widjaja on 3/10/20. // Copyright © 2020 EricW. All rights reserved. import UIKit class ViewController: UIViewController { //MARK: - IBOutlet @IBOutlet weak var powerPlantTableView: UITableView! //MARK: - Internal Variables var powerPlants = [RecordsWrapper]() { didSet { powerPlantTableView.reloadData() } } // MARK: - Lifecycle Overrides Methods override func viewDidLoad() { super.viewDidLoad() dump(PowerPlant.getPowerPlantData()) //check if all the data is loaded configureTableView() loadData() } //MARK: - Private Methods private func configureTableView() { powerPlantTableView.dataSource = self powerPlantTableView.delegate = self } private func loadData() { powerPlants = PowerPlant.getPowerPlantData() } } // MARK:- UITableViewDelegate Conformance extension ViewController: UITableViewDelegate { } // MARK:- UITableViewDataSource Conformance extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return powerPlants.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "powerPlantCell", for: indexPath) as? PowerPlantTableViewCell else { fatalError("Developer Error: Unexpected class for cell with reuseID countryCell") } let plants = powerPlants[indexPath.row] cell.setUpPowerPlants(with: plants) return cell } }
Java
UTF-8
8,815
2.125
2
[ "curl", "BSD-3-Clause", "OpenSSL", "MIT", "LicenseRef-scancode-openssl", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-ssleay-windows", "JSON", "LicenseRef-scancode-unknown-license-reference", "ISC", "BSL-1.0", "blessing", "Apache-2.0", "NCSA", "BSD-2-Clause", "Libpng", "IJG", "Zlib" ]
permissive
package com.mapabc.mapabcsdk.service.request; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Handler; import android.os.Looper; import android.support.annotation.Keep; import android.support.annotation.NonNull; import android.text.TextUtils; import com.mapabc.mapabcsdk.Mapabc; import com.mapabc.mapabcsdk.okhttp.OkHttpUtils; import com.mapabc.mapabcsdk.okhttp.builder.GetBuilder; import com.mapabc.mapabcsdk.okhttp.callback.StringCallback; import com.mapabc.mapabcsdk.service.ServiceConfig; import com.mapabc.mapabcsdk.service.param.PoiSearchAroundParam; import com.mapabc.mapabcsdk.service.param.PoiSearchIdParam; import com.mapabc.mapabcsdk.service.param.PoiSearchKeywordParam; import com.mapabc.mapabcsdk.service.param.PoiSearchPolygonParam; import okhttp3.Call; public class PoiSearch { private static final String TAG = "Mbgl - PoiSearch"; private Handler handler; // This object is implemented as a singleton @SuppressLint("StaticFieldLeak") private static PoiSearch instance; // The application context private Context context; private String API_BASE_URL =null; @Keep public interface resultCallBack{ /** * 接口返回内容 * * @param */ void onResponse(String response); /** * 错误信息 * * @param error the error message */ void onError(String error); } /* * Constructor */ private PoiSearch(Context context) { this.context = context.getApplicationContext(); this.API_BASE_URL = getApplicationMetaData(context, ServiceConfig.API_METE_NAME); } /** * Get the single instance of offline manager. * * @param context the context used to host the offline manager * @return the single instance of offline manager */ public static synchronized PoiSearch getInstance(@NonNull Context context) { if (instance == null) { instance = new PoiSearch(context); } return instance; } private Handler getHandler() { if (handler == null) { handler = new Handler(Looper.getMainLooper()); } return handler; } /** * poi关键字搜索查询接口 * <p> * 根据关键字搜索查询poi信息 * </p> * * @param callback the callback to be invoked */ public void queryKeyword(@NonNull PoiSearchKeywordParam param,@NonNull final resultCallBack callback) { GetBuilder builder = OkHttpUtils.get().url(API_BASE_URL + "/as/search/poi"); if(!TextUtils.isEmpty(param.getQuery())){ builder.addParams("query",param.getQuery()); } if(!TextUtils.isEmpty(param.getType())){ builder.addParams("type",param.getType()); } if(!TextUtils.isEmpty(param.getRegion())){ builder.addParams("region",param.getRegion()); } builder.addParams("page_size",String.valueOf(param.getPage_size())); builder.addParams("page_num",String.valueOf(param.getPage_num())); builder.addParams("scope",String.valueOf(param.getScope())); builder.addParams("ak", Mapabc.getAccessToken()); builder.addParams("output",param.getOutput()); builder.build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { callback.onError(e.getMessage()); } @Override public void onResponse(String response, int id) { callback.onResponse(response); } }); } /** * poi id搜索查询接口 * <p> * 根据ids搜索查询poi信息 * </p> * * @param callback the callback to be invoked */ public void queryPoiIds(@NonNull PoiSearchIdParam param, @NonNull final resultCallBack callback) { GetBuilder builder = OkHttpUtils.get().url(API_BASE_URL + "/as/search/poiid"); if(null != param.getIds() && param.getIds().size() > 0){ String ids = ""; for (int i = 0; i < param.getIds().size(); i++) { ids += param.getIds().get(i)+","; } builder.addParams("ids",ids); } builder.addParams("ak", Mapabc.getAccessToken()); builder.addParams("output",param.getOutput()); builder.build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { callback.onError(e.getMessage()); } @Override public void onResponse(String response, int id) { callback.onResponse(response); } }); } /** * poi 周边搜索查询接口 * <p> * 根据周边搜索查询poi信息 * </p> * * @param callback the callback to be invoked */ public void queryPoiAround(@NonNull PoiSearchAroundParam param, @NonNull final resultCallBack callback) { GetBuilder builder = OkHttpUtils.get().url(API_BASE_URL + "/as/search/poi"); if(!TextUtils.isEmpty(param.getQuery())){ builder.addParams("query",param.getQuery()); } if(param.getScope() != 0){ builder.addParams("scope",String.valueOf(param.getScope())); } if(param.getPage_size() != 0){ builder.addParams("page_size",String.valueOf(param.getPage_size())); } if(param.getPage_num() != 0){ builder.addParams("page_num",String.valueOf(param.getPage_num())); } if(!TextUtils.isEmpty(param.getLocation())){ builder.addParams("location",param.getLocation()); } if(param.getRadius() != 0){ builder.addParams("radius",String.valueOf(param.getRadius())); } builder.addParams("ak", Mapabc.getAccessToken()); builder.build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { callback.onError(e.getMessage()); } @Override public void onResponse(String response, int id) { callback.onResponse(response); } }); } /** * poi 多边形搜索查询接口 * <p> * 根据多边形搜索查询poi信息 * </p> * * @param callback the callback to be invoked */ public void queryPoiPolygon(@NonNull PoiSearchPolygonParam param, @NonNull final resultCallBack callback) { GetBuilder builder = OkHttpUtils.get().url(API_BASE_URL + "/as/search/poi"); if(!TextUtils.isEmpty(param.getQuery())){ builder.addParams("query",param.getQuery()); } if(!TextUtils.isEmpty(param.getRegionType())){ builder.addParams("regionType",param.getRegionType()); } if(param.getScope() != 0){ builder.addParams("scope",String.valueOf(param.getScope())); } if(param.getPage_size() != 0){ builder.addParams("page_size",String.valueOf(param.getPage_size())); } if(param.getPage_num() != 0){ builder.addParams("page_num",String.valueOf(param.getPage_num())); } if(!TextUtils.isEmpty(param.getBounds())){ builder.addParams("bounds",param.getBounds()); } if(!TextUtils.isEmpty(param.getOutput())){ builder.addParams("output",String.valueOf(param.getOutput())); } builder.addParams("ak", Mapabc.getAccessToken()); builder.build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { callback.onError(e.getMessage()); } @Override public void onResponse(String response, int id) { callback.onResponse(response); } }); } /** * 获取Application下meta配置文件用于设置BaseUrl * @param context * @param key * @return */ @NonNull public String getApplicationMetaData(Context context, String key){ String value=null; try { ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); value = appInfo.metaData.getString(key); //Log.d("Tag", " app key : " + value); // Tag﹕ app key : } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); }finally { return value; } } }
Shell
UTF-8
636
2.90625
3
[ "Apache-2.0" ]
permissive
#!/bin/bash curl -s "https://api.github.com/repos/kubernetes/kubernetes/tags?page=1&per_page=100" |grep name |grep -v '-' |grep -v v0. |awk -F '"' '{print $4}' > ./k8s-version-new.txt i=2 while (($i != 0)); do kversion=`curl -s "https://api.github.com/repos/kubernetes/kubernetes/tags?page=${i}&per_page=100" |grep name |grep -v '-' |grep -v v0. |awk -F '"' '{print $4}'` if [ -n "$kversion" ]; then curl -s "https://api.github.com/repos/kubernetes/kubernetes/tags?page=${i}&per_page=100" |grep name |grep -v '-' |grep -v v0. |awk -F '"' '{print $4}' >> ./k8s-version-new.txt i=$[$i+1] sleep 10 else i=0 fi done
C++
UTF-8
668
3.171875
3
[]
no_license
//This file also starts out empty. //Implement the Turtle class here. #include "turtle.h" #include <iostream> #include <cmath> using namespace std; Turtle::Turtle(double x0, double y0, double dir0) { x1 = x0; y1 = y0; dir = dir0; color = draw::BLACK; tra = 0; } void Turtle::move(double dist) { double x2 = x1 + (dist * cos(dir * (M_PI / 180))); double y2 = y1 + (dist * sin(dir * (M_PI / 180))); draw::setcolor(color); if(tra==0){ draw::line(x1, y1, x2, y2); } x1 = x2; y1 = y2; } void Turtle::turn(double deg) { dir = dir + deg; } void Turtle::setColor(Color c) { color = c; } void Turtle::on() { tra = 0; } void Turtle::off() { tra = 1; }
C
UTF-8
16,355
2.65625
3
[]
no_license
#include "lf_hashmap.h" atom_t hash_new(struct hash **h, int nbpow) { int bucket_max = ((unsigned long) 1 << nbpow); unsigned long bucket_mask = (unsigned long) bucket_max - 1; *h = (struct hash *) aligned_malloc(sizeof(struct hash), LF_ALIGN_DOUBLE_POINTER); if (*h != NULL) { if (!init_hash_table(*h, bucket_max)) return 0; hash_new_element(&(*h)->hl, MAX_HASH_LIST_NUM); hash_new_data_list(&(*h)->dl, MAX_HASH_DATA_NUM); } if (!(*h && (*h)->table && (*h)->hl && (*h)->dl)) { if (*h) { if ((*h)->hl) { hashlist_delete(*h, hash_delete_item_func, NULL); aligned_free((*h)->hl); } if ((*h)->dl) { datalist_delete(*h, hash_delete_data_func, NULL); aligned_free((*h)->dl); } aligned_free(*h); } return 0; } (*h)->bucket_max = bucket_max; (*h)->bucket_mask = bucket_mask; LF_BARRIER_STORE; return 1; } int init_hash_table(struct hash *h, int bucket_max) { assert(h != NULL); struct hash_item *head, *end; atom_t loop, count = 0; h->table = (struct hash_item **) aligned_malloc(sizeof(struct hash_item *) * bucket_max, LF_ALIGN_DOUBLE_POINTER); for (loop = 0; loop < bucket_max; loop++) { head = (struct hash_item *) aligned_malloc(sizeof(struct hash_item), LF_ALIGN_DOUBLE_POINTER); end = (struct hash_item *) aligned_malloc(sizeof(struct hash_item), LF_ALIGN_DOUBLE_POINTER); if (head && end) { head->node_type = HEAD_NODE; end->node_type = END_NODE; h->table[loop] = head; h->table[loop]->next = end; } else { return 0; } } return 1; } /*------------------aligned free memory -----------*/ void hash_free(struct hash *h) { if (h != NULL) { if (h->hl != NULL) { hashlist_delete(h, hash_delete_item_func, NULL); aligned_free(h->hl); } if (h->dl != NULL) { datalist_delete(h, hash_delete_data_func, NULL); aligned_free(h->dl); } if (h->table != NULL) { //#ifndef __MINGW64__ //Now we have a bug in mingw64. printf("free test\n"); hashtable_delete(h, hash_delete_item_func, NULL); printf("free test suc\n"); //#endif aligned_free(*(h->table)); } aligned_free(h); } return; } /* hash delete will be completed soon */ void hashlist_delete(struct hash *h, void (*delete_func)(void *data_item, void *state), void *state) { assert(h->hl != NULL); assert(state == NULL); assert(delete_func != NULL); struct hash_item *ihash; int retry = 0; while (hashlist_pop(h->hl, &ihash, &retry)) { delete_func(ihash, state); } return; } void hashtable_delete(struct hash *h, void (*delete_func)(void *bucket, void *state), void *state) { assert(delete_func != NULL); assert(state == NULL); int bucket_max = h->bucket_max; struct hash_item *bucket, *next; int i; for (i = 0; i < bucket_max; i++) { bucket = h->table[i]; while (bucket) { next = bucket->next; delete_func(bucket, state); bucket = next; } } return; } void datalist_delete(struct hash *h, void (*delete_func)(void *data, void *state), void *state) { assert(h->dl != NULL); assert(state == NULL); assert(delete_func != NULL); struct hash_data *hd; int retry = 0; while (datalist_pop(h->dl, &hd, &retry)) { delete_func(hd, state); } return; } void hash_delete_item_func(void *bucket, void *state) { assert(bucket != NULL); assert(state == NULL); struct hash_item *_bucket = (struct hash_item *) bucket; if (_bucket->data != NULL) aligned_free(_bucket->data); aligned_free(bucket); return; } void hash_delete_data_func(void *data, void *state) { assert(data != NULL); assert(state == NULL); aligned_free(data); return; } /*---------------------aligned free memory over----------*/ atom_t hash_new_element(struct hash_list **hl, atom_t number_elements) { assert(hl != NULL); atom_t rv = 0; struct hash_item *he; atom_t loop, count = 0; *hl = (struct hash_list *) aligned_malloc(sizeof(struct hash_list), LF_ALIGN_DOUBLE_POINTER); if (!init_hashlist(*hl)) return 0; for (loop = 0; loop < number_elements; loop++) { if (hashlist_internal_new_element(*hl, &he)) { hashlist_push(*hl, he); count++; } } if (number_elements == count) { rv = 1; } else { aligned_free(*hl); *hl = NULL; } internal_display_test_name("new item list over\n"); return rv; } atom_t init_hashlist(struct hash_list *hl) { assert(hl != NULL); atom_t rv = 0; hl->he = (struct hash_item *) aligned_malloc(sizeof(struct hash_item), LF_ALIGN_DOUBLE_POINTER); if (hl->he) { hl->item_num = 1; rv = 1; } return rv; } atom_t hashlist_internal_new_element(struct hash_list *hl, struct hash_item **he) { assert(hl != NULL); atom_t rv = 0; *he = (struct hash_item *) aligned_malloc(sizeof(struct hash_item), LF_ALIGN_DOUBLE_POINTER); if (NULL != *he) { abstraction_increment((atom_t *) &hl->item_num); (*he)->node_type = I_NODE; rv = 1; } return (rv); } void hashlist_push(struct hash_list *hl, struct hash_item *he) { LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_item *he_local, *he_original; he_local = he; LF_BARRIER_LOAD; he_original = hl->he; do { he_local->next = he_original; } while (he_local->next != (he_original = (struct hash_item *) abstraction_cas((volatile atom_t *) &hl->he, (atom_t *) he_local, (atom_t *) he_original))); return; } struct hash_item *hashlist_pop(struct hash_list *hl, struct hash_item **he, atom_t *retry) { assert(NULL != hl); assert(NULL != he); LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_item *he_local, *he_cmp; LF_BARRIER_LOAD; he_local = hl->he; do { he_cmp = he_local; if (he_local == NULL || he_local->next == NULL) { *he = NULL; return (*he); } (*retry)++; } while (he_cmp != (he_local = abstraction_cas((volatile atom_t *) &hl->he, (atom_t) he_local->next, (atom_t) he_cmp))); abstraction_sub((atom_t *) &hl->item_num); *he = (struct hash_item *) he_local; return (*he); } /*-------------malloc many data node to a data list,about pop and push-------------*/ atom_t hash_new_data_list(struct data_list **dl, atom_t data_count) { assert(dl != NULL); atom_t rv = 0; LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_data *hd; atom_t loop, count = 0; *dl = (struct data_list *) aligned_malloc(sizeof(struct data_list), LF_ALIGN_DOUBLE_POINTER); if (!init_datalist(*dl)) return 0; for (loop = 0; loop < data_count; loop++) if (hashlist_internal_new_data(*dl, &hd, count)) { hd->val = count; datalist_push(*dl, hd); count++; } if (data_count == count) { rv = 1; } else { aligned_free(*dl); *dl = NULL; } internal_display_test_name("new data list over..."); printf("%u\n", count); fflush(stdout); return rv; } atom_t init_datalist(struct data_list *dl) { assert(dl != NULL); atom_t rv = 0; dl->hd = (struct hash_data *) aligned_malloc(sizeof(struct hash_data), LF_ALIGN_DOUBLE_POINTER); if (dl->hd) { dl->data_count = 1; rv = 1; } return rv; } atom_t hashlist_internal_new_data(struct data_list *dl, struct hash_data **hd, atom_t count) { atom_t rv = 0; assert(dl != NULL); *hd = (struct hash_data *) aligned_malloc(sizeof(struct hash_data), LF_ALIGN_DOUBLE_POINTER); if (NULL != hd) { (*hd)->key = count; (*hd)->val = count; abstraction_increment((atom_t *) &dl->data_count); rv = 1; } LF_BARRIER_STORE; return (rv); } void datalist_push(struct data_list *dl, struct hash_data *hd) { LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_data *hd_local, *hd_original; hd_local = hd; LF_BARRIER_LOAD; hd_original = dl->hd; do { hd_local->next = hd_original; } while (hd_local->next != (hd_original = (struct hash_data *) abstraction_cas((volatile atom_t *) &dl->hd, (atom_t) hd_local, (atom_t) hd_original))); // internal_display_test_name("datalist push over...\n"); return; } struct hash_data *datalist_pop(struct data_list *dl, struct hash_data **hd, atom_t *retry) { LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_item *hd_local, *hd_cmp; assert(NULL != dl); //assert(NULL == (*hd)); //internal_display_test_name("hashmap datalist pop..."); LF_BARRIER_LOAD; hd_local = dl->hd; do { hd_cmp = hd_local; if (hd_local->next == NULL) { *hd = NULL; return (*hd); } (*retry)++; } while (hd_cmp != (hd_local = (struct hash_item *) abstraction_cas((volatile atom_t *) &dl->hd, (atom_t) hd_local->next, (atom_t) hd_cmp))); abstraction_sub((atom_t *) &dl->data_count); *hd = (struct hash_data *) hd_local; return (*hd); } unsigned long hash_lookup(struct hash *h, unsigned long key) { unsigned long bucket_mask = h->bucket_max; int bucket_index = (int) (key & bucket_mask); struct hash_item *bucket; unsigned long val; for (bucket = h->table[bucket_index]; bucket; bucket = bucket->next) if (bucket->data->key == key) { val = bucket->data->val; return val; } return 0; } /* unsigned long hash_insert(struct hash* h, unsigned long key, unsigned long val) { unsigned long bucket_mask = h->bucket_mask; int bucket_index = (int)(key & bucket_mask); struct hash_item* new_item; new_item = (struct hash_item*)malloc(sizeof(struct hash_item)); if (!new_item) { return -1; } new_item->key = key; new_item->value = val; new_item->next = h->table[bucket_index]; h->table[bucket_index] = new_item; return 0; } unsigned long hash_delete(struct hash* h, unsigned long key) { unsigned long bucket_mask = h->bucket_mask; int bucket_index = (int)(key & bucket_mask); struct hash_item *bucket, *prev; unsigned long val; for (prev = NULL, bucket = h->table[bucket_index]; bucket; prev = bucket, bucket = bucket->next) { if (bucket->key == key) { val = bucket->value; if (prev) prev->next = bucket->next; else h->table[bucket_index] = bucket->next; free(bucket); return val; } } return 0; }*/ /*----------------------- add node or replace node or node exist ------------------ */ atom_t lf_hash_add(struct hash *h, struct hash_data *hdata, atom_t *retry, atom_t *add_retry) { LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_item *h_item, *bucket, *h_prev, *prev_next; LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_data *h_data, *hd_cmp; assert(h != NULL); unsigned long bucket_mask = h->bucket_mask; int bucket_index = (int) (hdata->key & bucket_mask); atom_t operation, cas_result = 0; //internal_display_test_name("hashmap add start..."); while (0 == lf_hash_add_new_element_from_hashlist(h, &h_item, retry)); h_prev = bucket = h->table[bucket_index]; //test prev_next = h_prev->next; h_item->data = hdata; assert(h_item != NULL); LF_BARRIER_LOAD; //todo 按照修改双索引的方式插入; do { if (prev_next->node_type == END_NODE || prev_next->data->key > hdata->key) { h_item->next = prev_next; bucket = prev_next; prev_next = (struct hash_item *) abstraction_cas((volatile atom_t *) &h_prev->next, (atom_t) h_item, (atom_t) bucket); if (prev_next == bucket) { operation = HASH_MAP_NODE_ADD; cas_result = 1; } else { //exchange index error; cas_result = 0; } } else if (prev_next->data->key < hdata->key) { h_prev = prev_next; prev_next = prev_next->next; } else { if (hdata->val == prev_next->data->val) { aligned_free(hdata); operation = HASH_MAP_NODE_EXIST; } else { hd_cmp = prev_next->data; do { h_data = hd_cmp; } while (h_data != (hd_cmp = (struct hash_data *) abstraction_cas((volatile atom_t *) &prev_next->data, (atom_t) hdata, (atom_t) h_data))); aligned_free(h_data); operation = HASH_MAP_NODE_REPLACE; } cas_result = 1; } (*add_retry)++; } while (cas_result == 0); if (operation == HASH_MAP_NODE_EXIST || operation == HASH_MAP_NODE_REPLACE) { aligned_free(h_item); } return operation; } int lf_hash_search(struct hash *hs, struct hash_data *hd) { assert(hs != NULL); assert(hd != NULL); int cas_result = 0, operation; LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_item *bucket, *h_prev; LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_data *h_data; unsigned long bucket_mask = hs->bucket_mask; int bucket_index = (int) (hd->key & bucket_mask); //internal_display_test_name("hashmap add start..."); h_prev = hs->table[bucket_index]; //test bucket = h_prev->next; LF_BARRIER_LOAD; //todo 查找索引 do { if (bucket->node_type == END_NODE || bucket->data->key > hd->key) { cas_result = 1; operation = HASH_MAP_SEARCH_FAIL; } else if (bucket->data->key < hd->key) { h_prev = bucket; bucket = bucket->next; } else { operation = HASH_MAP_SEARCH_SUCC; cas_result = 1; } } while (cas_result == 0); return operation; } atom_t lf_hash_add_new_element_from_hashlist(struct hash *h, struct hash_item **h_item, atom_t *retry) { //todo get a hash_item from hash_list atom_t rv = 0; assert(h != NULL); assert(h_item != NULL); hashlist_pop(h->hl, h_item, retry); if (*h_item != NULL) { rv = 1; } return rv; } atom_t lf_hash_internal_new_data_from_datalist(struct hash *h, struct hash_data **data, atom_t *retry) { atom_t rv = 0; assert(h != NULL); assert(data != NULL); datalist_pop(h->dl, data, retry); if (*data != NULL) { rv = 1; } return rv; } /* -------------------add over ------------------*/ #pragma warning(disable : 4100) void hashmap_use(struct hash *hs) { assert (NULL != hs); LF_BARRIER_LOAD; return; } //#pragma warning(default : 4100) #pragma warning(disabe : 4100) /*------------------------------ hash remove item ------------------------*/ //todo /* atom_t hash_remove_item(struct hash * h, atom_t key) { LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_item *h_item,*bucket,*h_prev; LF_ALIGN(LF_ALIGN_DOUBLE_POINTER) struct hash_data *h_data; assert(h != NULL); unsigned long bucket_mask = h->bucket_mask; int bucket_index = (int)(hdata->key & bucket_mask); atom_t operation,cas_result = 0; h_prev = bucket = h->table[bucket_index]; bucket = h_prev->next; do { if(bucket == NULL) { break; } if(bucket->data->key == key) { cas_result = abstraction_dcas((volatile atom_t*)h_prev->next,(atom_t*)bucket->next,(atom_t*)bucket); } } while (cas_result == 0); } */ unsigned long lf_hash_delete(struct hash *h, unsigned long key) { }
Java
UTF-8
1,750
2.203125
2
[ "Apache-2.0" ]
permissive
package com.huaweicloud.sdk.aom.v2.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** * Request Object */ public class ShowActionRuleRequest { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "rule_name") private String ruleName; public ShowActionRuleRequest withRuleName(String ruleName) { this.ruleName = ruleName; return this; } /** * 告警规则名称 * @return ruleName */ public String getRuleName() { return ruleName; } public void setRuleName(String ruleName) { this.ruleName = ruleName; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ShowActionRuleRequest that = (ShowActionRuleRequest) obj; return Objects.equals(this.ruleName, that.ruleName); } @Override public int hashCode() { return Objects.hash(ruleName); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ShowActionRuleRequest {\n"); sb.append(" ruleName: ").append(toIndentedString(ruleName)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
Python
UTF-8
233
3.3125
3
[]
no_license
#!/usr/bin/python3 """Determinant is a scalar representation of the volume of the matrix""" import numpy as np from numpy.linalg import det A = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) print(A) B = det(A) print(B)
Markdown
UTF-8
3,581
2.765625
3
[]
no_license
CFT2018 contest: исправление опечаток ========================================== Материалы к соревнованию по исправлению опечаток [CFT2018 contest](https://datasouls.com/c/cft-contest/). ## Описание задачи CFT2018 — соревнование по определению корректности введённых пользователями ФИО и исправлению опечаток в них. Соревнование включает в себя две задачи: - определение корректности введённых ФИО (классификация на 3 класса: корректно `0`, есть опечатки `1`, мусор вместо ФИО `2`); - исправление опечаток во введённых ФИО (только при наличии опечаток). Наличие отчества в ФИО не является обязательным. Мусором считается строк, содержащая не ФИО. ## Формат набора данных Для обучения моделей предоставляется обучающая выборка, содержащая следующие колонки: - `id` — идендификатор (несёт вспомогательную роль) - `fullname` — исходное ФИО из анкеты (может не иметь отчества) - `country` — страна из анкеты - `target` — целевая переменная - `fullname_true` — исправленное ФИО (присутствует только в строках с классом "есть опечатки"). Для оценки качества предоставляется тестовая выборка, в которой колонки `target` и `fullname_true` отсутствуют. ## Формат решения В проверяющую систему необходимо отправить файл с предсказаниями в формате `csv`, содержащий следующие колонки: - `id` - `target` - `fullname_true` (можно не заполнять для строк с предсказаниями класса, отличного от "есть опечатки"). ## Использование открытых данных и библиотек ## Система оценки 1. Для задачи определения корректности введённых ФИО целевая метрика: F1 с макроусреднением (то есть усредняется F1, посчитанный отдельно для каждого класса). 2. Для задачи исправления опечаток, считается точность (доля правильно исправленных ФИО). Подсчёт ведётся только на объектах класса "есть опечатки", при этом корректно исправленная опечатка требует предсказание наличия опечаток (то есть требуется и предсказать класс "есть опечатки", и правильно исправить ФИО). 3. Итоговый результат вычисляется как среднее арифметическое метрик каждой из задач. Функции для вычисления качества можно найти в baseline/scoring.py.
Java
UTF-8
429
2.25
2
[]
no_license
package com.Interface.live; import com.Interface.music.Playable; import com.Interface.music.string.Veena; import com.Interface.music.wind.SaxaPhone; public class Main { public static void main(String[] args) { Playable veena = new Veena(); Playable saxaPhone = new SaxaPhone(); veena.play(); saxaPhone.play(); saxaPhone.play(); veena.play(); veena.play(); } }
Go
UTF-8
1,126
2.859375
3
[]
no_license
package atypes type AFloat32 []float32 func (ai AFloat32) Len() int { return len(ai) } func (ai AFloat32) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AFloat32) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AFloat32) Get(i int) interface{} { return ai[i] } func (ai AFloat32) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AFloat32) Assign(i int, d interface{}){ai[i] = d.(float32)} func (ai AFloat32) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c} type AFloat64 []float64 func (ai AFloat64) Len() int { return len(ai) } func (ai AFloat64) Less(i, j int) bool { return ai[i] < ai[j] } func (ai AFloat64) Swap(i, j int) { ai[i], ai[j] = ai[j], ai[i] } func (ai AFloat64) Get(i int) interface{} { return ai[i] } func (ai AFloat64) LessD(i, j interface{}) bool { return i.(int) < j.(int) } func (ai AFloat64) Assign(i int, d interface{}){ai[i] = d.(float64)} func (ai AFloat64) InsertionB (i, j int){c := append(ai[:j], ai[i]);c = append(c, ai[j:i]...);c = append(c, ai[i+1:]...);ai = c}
Python
UTF-8
787
3
3
[]
no_license
class Solution: def jump(self, nums: List[int]) -> int: """ First solution: O(N^2) time, O(N) space """ jumps = [float('inf')] * len(nums) jumps[0] = 0 for i, n in enumerate(nums): for j in range(1, n+1): if i+j < len(nums): jumps[i+j] = min(jumps[i+j], 1 + jumps[i]) return jumps[-1] def jump(self, nums: List[int]) -> int: """ Second solution: O(N) time, O(1) space """ jumps = 0 c_max = 0 n_max = 0 for i, n in enumerate(nums): n_max = max(n_max, i+n) if i == len(nums)-1: return jumps if i == c_max: jumps += 1 c_max = n_max
TypeScript
UTF-8
568
2.53125
3
[]
no_license
import mongoose, { Schema, Document } from "mongoose"; import { UserI } from './User'; import { ProductI } from './Product'; export interface CartI extends Document { owner: UserI; products: any[]; timestamp: Date; } const CartSchema = new Schema({ owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null }, products: { type: Array, default: [] }, timestamp: { type: Date, default: Date.now() } }) export default mongoose.model<CartI>('Cart', CartSchema);
C#
UTF-8
832
3.4375
3
[]
no_license
// Javier Benajes // Dates for every 7 days using System; using System.IO; class Fechas7dias { public static void Main() { StreamWriter fichero = File.CreateText("tasks.txt"); DateTime fecha = DateTime.Now; string[] meses = { "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" }; int nextYear = DateTime.Now.Year + 1; while (fecha.Year < nextYear) { fichero.WriteLine(fecha.Day.ToString("00") + "-" + meses[fecha.Month - 1].Substring(0, 3) + "-" + fecha.Year.ToString().Substring(2)); fecha = fecha.AddDays(7); } fichero.Close(); Console.WriteLine("tasks.txt created") } }
Python
UTF-8
995
2.984375
3
[]
no_license
import unittest from algo.sort.heap_sort import HeapSortContainer from visualization.console.utils.colors.sort_color_collection import \ SortColorCollection class TestHeapSortContainer(unittest.TestCase): """unit tests for heap sort container""" def setUp(self): """setUp is overridden and is needed for unit tests to run""" self.sort_container = HeapSortContainer() class TestSort(TestHeapSortContainer): """unit tests for heap sort container""" def test_sort(self): """asserts list is sorted""" # Given to_be_sorted = [2, 3, 1, 5, 4] color_collection = SortColorCollection() elements_in_colors = [color_collection.initial_bar_color] * \ len(to_be_sorted) # When self.sort_container.sort(to_be_sorted, elements_in_colors, color_collection, lambda *args: None) # Then self.assertEqual(to_be_sorted, [1, 2, 3, 4, 5])
TypeScript
UTF-8
1,029
3.921875
4
[]
no_license
/* 29 타입스크립트에는 unknown 타입도 있다. unknown 타입은 아직 정해지지 않았다는 의미로, any 타입과 비슷하게 어떤 타입이든 할당할 수 있지만, 다른 타입의 변수에 할당할 때 에러를 발생시킨다는 점이 다르다. any를 쓰는 것보다 unknown을 쓰는게 조금 더 타입을 확실하게 결정하는 방법이고 나중에 타입체크를 하면서 사용하면 된다. */ let unknownVar: unknown; let anyVar: any; let stringVar: string; stringVar = anyVar; // no error // stringVar = unknown; // error if (typeof unknownVar === 'string') { stringVar = unknownVar; // 타입체크 후에는 가능 } /* 30 함수가 리턴할 수 있는 타입에는 never 타입도 있다. void와 다르게, never 타입은 함수가 리턴하지 않는 경우에 리턴 타입으로 사용되며 대표적인 예로 에러를 발생시키는 함수의 경우 never타입을 리턴한다 */ function createError(message: string): never { throw new Error(message); }
Java
UTF-8
574
1.546875
2
[]
no_license
package com.tencent.qcloud.presentation.viewfeatures; import com.tencent.TIMFriendGroup; import com.tencent.TIMUserProfile; import java.util.List; /** * @author wangjingwei * @version 1.0.0 * @date 18/04/11 */ public interface MyFriendGroupInfo extends MvpView { /** * 我的群列表 * @param timFriendGroups */ void showMyGroupList(List<TIMFriendGroup> timFriendGroups); /** * 群成员 * @param groupname * @param timUserProfiles */ void showGroupMember(String groupname,List<TIMUserProfile> timUserProfiles); }
Markdown
UTF-8
925
2.625
3
[]
no_license
# Proof – Ackermann majorises all Primitive Recursive (PR) functions This proof is done in NASA PVS and more or less follows the proofs listed below. This proof was done for the class programming verification at University of Applied Sciences Leipzig. - [Ackermann Function – George Tourlakis](http://www.cs.yorku.ca/~gt/papers/Ackermann-function.pdf) - [Ackermann function is not primitive recursive](http://www.cs.tau.ac.il/~nachumd/term/42019.pdf) - [Termination Lecture 3 - Bigger& Bigger – Jonathan Kalechstain](http://www.cs.tau.ac.il/~nachumd/term/Jonathan.pdf) - [A Machine Checked Proof that Ackermann's Function is not Primitive Recursive – Nora Szasz](https://pdfs.semanticscholar.org/06e4/23ce7aa485caea6a1aeb883a94d2e8dadfa6.pdf) You can run the whole proof with the proveit_gh script. Make sure to change the `PVSPATH` to point to your installation of PVS. To run the proofs run the following command: `./proveit_gh -c pr-ack`
C
UTF-8
2,957
2.671875
3
[]
no_license
#include "performance.h" #include "socket.h" #include "log.h" p_per_ctx p_ctx; void p_init_bandwidth(struct p_bandwidth *p) { p->bytes = 0; p->kbytes = 0; p->mbytes = 0; p->gbytes = 0; } void p_get_time_now(struct timeval *time_val) { gettimeofday(time_val, NULL); } void * p_func(void *args) { unsigned char buf[sizeof(int)]; p_ctx.p_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); struct sockaddr_in addr, client_addr; socklen_t sock_len, client_addr_len; sock_len = sizeof(struct sockaddr_in); inet_aton(p_ctx.host, &addr.sin_addr); addr.sin_port = htons(p_ctx.port); addr.sin_family = AF_INET; if (bind(p_ctx.p_sock, (struct sockaddr *)&addr, sock_len) < 0) { log_f("performance socket init error"); } else { log_f("performance thread init finish"); } while(1) { recvfrom(p_ctx.p_sock, buf, sizeof(int), 0, (struct sockaddr *)&client_addr, &client_addr_len); p_get_time_now(&p_ctx.p_now_time); sendto(p_ctx.p_sock, &p_ctx, sizeof(p_per_ctx), 0, (struct sockaddr *)&client_addr, client_addr_len); } } void p_init(char *host, int port) { p_ctx.host = host; p_ctx.port = port; p_init_bandwidth(&p_ctx.p_total_bandwidth); p_init_bandwidth(&p_ctx.p_original_bandwidth); p_get_time_now(&p_ctx.p_start_time); pthread_create(&p_ctx.p_pid, NULL, p_func, NULL); } void p_bandwidth_add(struct p_bandwidth *p, int add) { p->bytes += add; int left; if (p->bytes >= 1024) { left = p->bytes >> 10; p->bytes = p->bytes % 1024; p->kbytes += left; } if (p->kbytes >= 1024) { left = p->kbytes >> 10; p->kbytes = p->kbytes % 1024; p->mbytes += left; } if (p->mbytes >= 1024) { p->mbytes = p->mbytes % 1024; p->gbytes += left; } } void p_get_performance(char *host, int port) { struct sockaddr_in addr; unsigned char buf[sizeof(int)]; socklen_t sock_len; inet_aton(host, &addr.sin_addr); addr.sin_port = htons(port); addr.sin_family = AF_INET; sock_len = sizeof(addr); p_ctx.p_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); sendto(p_ctx.p_sock, buf, sizeof(int), 0, (struct sockaddr *)&addr, sock_len); recvfrom(p_ctx.p_sock, &p_ctx, sizeof(p_per_ctx), 0, NULL, NULL); printf("Bandwidth total: %dGB %dMB %dKB %dB, original: %dGB %dMB %dKB %dB\n", p_ctx.p_total_bandwidth.gbytes, p_ctx.p_total_bandwidth.mbytes, p_ctx.p_total_bandwidth.kbytes, p_ctx.p_total_bandwidth.bytes, p_ctx.p_original_bandwidth.gbytes, p_ctx.p_original_bandwidth.mbytes, p_ctx.p_original_bandwidth.kbytes, p_ctx.p_original_bandwidth.bytes); printf("Stash size: %lld\n", p_ctx.p_stash_size); printf("Total Time: %ld seconds %ld useconds\n", p_ctx.p_now_time.tv_sec - p_ctx.p_start_time.tv_sec, p_ctx.p_now_time.tv_usec - p_ctx.p_start_time.tv_usec); }
C++
UTF-8
2,927
3.6875
4
[]
no_license
#include<iostream> #include<string> #include<vector> #include<queue> using namespace std; struct TreeNode { int val; struct TreeNode * left; struct TreeNode * right; TreeNode (int x) : val(x), left(NULL), right(NULL) {} }; class Codec { public: //the leetcode way of serialization //ref:https://leetcode.com/discuss/73461/short-and-straight-forward-bfs-java-code-with-a-queue // Encodes a tree to a single string. string serialize(TreeNode* root) { string res; if (!root) return res; queue<struct TreeNode*> q; q.push(root); while (!q.empty()) { struct TreeNode * p = q.front(); q.pop(); if (!p) res += "n "; else res += to_string(p->val) + " "; if (p) { q.push(p->left); q.push(p->right); } } return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if (data.empty()) return NULL; vector<string> tmp; int j = 0; for (int i = 0; i < data.length(); i ++) { if (data[i] == ' ') {//"123 " or "123 456 " string s = data.substr(j, i-j); j = i + 1; tmp.push_back(s); } } queue<struct TreeNode*> q; struct TreeNode * root = new TreeNode(stoi(tmp[0])); q.push(root); for (int i = 1; i < tmp.size(); i ++) { struct TreeNode * p = q.front(); q.pop(); if (tmp[i] != "n") { struct TreeNode * l = new TreeNode(stoi(tmp[i])); p->left = l; q.push(p->left); } if (tmp[++i] != "n") { struct TreeNode * r = new TreeNode(stoi(tmp[i])); p->right = r; q.push(p->right); } } return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root)); void inorder(struct TreeNode * p) { if (!p) return; inorder(p->left); cout << p->val << ' '; inorder(p->right); } int main() { class Codec test; struct TreeNode * p5 = new TreeNode(5); struct TreeNode * p2 = new TreeNode(2); struct TreeNode * p1 = new TreeNode(1); struct TreeNode * p7 = new TreeNode(7); struct TreeNode * p6 = new TreeNode(6); struct TreeNode * p8 = new TreeNode(8); p5->left = p2; p2->left = p1; p5->right = p7; p7->left = p6; p7->right = p8; cout << "in order traversal of the orginal binary tree" << endl; inorder(p5); cout << endl; string res = test.serialize(p5); cout << res << endl; struct TreeNode * root = test.deserialize(res); cout << "in order traversal of the deserialized binary tree" << endl; inorder(root); cout << endl; return 0; }
PHP
UTF-8
2,004
2.84375
3
[]
no_license
<?php namespace Leon\Controller; use InvalidArgumentException; use Leon\Response\HTMLResponse; use ReflectionClass; /** * @author Nick Wakeman <nick@thehiredgun.tech> * @since 2016-10-09 * * @todo save request if not logged in, * @todo then upon login resubmit their request * @todo add twig function to get routes in template * @todo add authentication for API's??? */ abstract class Controller { protected $configuration; protected $db; protected $permission; protected $view; public function __construct() { global $configuration, $db; $this->configuration = $configuration; $this->db = $db; $permissionClass = $this->configuration->getPermission()->getClass(); $this->permission = new $permissionClass(); } public function getIsLoggedIn() { return $this->permission->getIsLoggedIn(); } public function unauthorizedAction() { header("HTTP/1.0 401 Unauthorized"); header("Location: /login"); } public function forbiddenAction() { header("HTTP/1.0 403 Forbidden"); return new HTMLResponse('@Leon/forbidden.index.html.twig'); } public function notFoundAction() { header("HTTP/1.0 404 Not Found"); return new HTMLResponse('@Leon/notFound.index.html.twig'); } public function internalServerErrorAction() { header("HTTP/1.0 500 Internal Server Error"); return new HTMLResponse('@Leon/internalServerError.index.html.twig'); } public function setAlert($type, $message, $dismissable = true) { if (!in_array($type, [ 'success', 'info', 'warning', 'danger' ])) { Throw new InvalidArgumentException('The class name for that alert is not valid'); } $_SESSION['alert'] = [ 'type' => $type, 'message' => $message, 'dismissable' => $dismissable ]; } }
Java
UTF-8
3,928
2.53125
3
[]
no_license
package cl.laPalmera.Manejador; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import org.apache.log4j.Logger; import cl.laPalmera.DTO.FuncionarioDTO; import cl.laPalmera.connection.ConnectionLaPalmera; public class ManejadorFuncionario { private static final Logger LOGGER = Logger.getLogger(ManejadorFuncionario.class); private String rutFuncionario=""; private String nombreFuncionario=""; private String apellidoPaternoFuncionario=""; private String apellidoMaternoFuncionario=""; private String codigoCargo=""; private String codigoArea=""; public ArrayList consultar() { ArrayList<FuncionarioDTO> vec = new ArrayList<FuncionarioDTO>(); try { ConnectionLaPalmera connLaPalmera = new ConnectionLaPalmera(); Connection conn = connLaPalmera.conectionMySql(); if (conn != null) { Statement stmt = conn.createStatement(); String sql = "select * from funcionario where 1 = 1 "; if (!rutFuncionario.equals("")) sql = sql +" and rutFuncionario = '"+rutFuncionario+"'"; if (!nombreFuncionario.equals("")) sql = sql +" and nombreFuncionario = '"+nombreFuncionario+"'"; if (!apellidoPaternoFuncionario.equals("")) sql = sql +" and apellidoPaternoFuncionario = '"+apellidoPaternoFuncionario+"'"; if (!apellidoMaternoFuncionario.equals("")) sql = sql +" and apellidoMaternoFuncionario = '"+apellidoMaternoFuncionario+"'"; if (!codigoCargo.equals("")) sql = sql +" and codigoCargo = '"+codigoCargo+"'"; if (!codigoArea.equals("")) sql = sql +" and codigoArea = '"+codigoArea+"'"; //LOGGER.debug(sql); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { FuncionarioDTO puntero = new FuncionarioDTO(); puntero.setRutFuncionario(rs.getString(1)); puntero.setNombreFuncionario(rs.getString(2)); puntero.setApellidoPaternoFuncionario(rs.getString(3)); puntero.setApellidoMaternoFuncionario(rs.getString(4)); puntero.setCodigoCargo(rs.getString(5)); puntero.setCodigoArea(rs.getString(6)); vec.add(puntero); } stmt.close(); conn.close(); } } catch (Exception e) { LOGGER.error(e,e); } return vec; } public String getApellidoMaternoFuncionario() { return apellidoMaternoFuncionario; } public void setApellidoMaternoFuncionario(String apellidoMaternoFuncionario) { this.apellidoMaternoFuncionario = apellidoMaternoFuncionario; } public String getApellidoPaternoFuncionario() { return apellidoPaternoFuncionario; } public void setApellidoPaternoFuncionario(String apellidoPaternoFuncionario) { this.apellidoPaternoFuncionario = apellidoPaternoFuncionario; } public String getCodigoArea() { return codigoArea; } public void setCodigoArea(String codigoArea) { this.codigoArea = codigoArea; } public String getCodigoCargo() { return codigoCargo; } public void setCodigoCargo(String codigoCargo) { this.codigoCargo = codigoCargo; } public String getNombreFuncionario() { return nombreFuncionario; } public void setNombreFuncionario(String nombreFuncionario) { this.nombreFuncionario = nombreFuncionario; } public String getRutFuncionario() { return rutFuncionario; } public void setRutFuncionario(String rutFuncionario) { this.rutFuncionario = rutFuncionario; } }
C
UTF-8
2,424
3.5625
4
[]
no_license
//############################################################################### /** Liefert eine neue Matrix als Ergebnis aus der Addition zweier gegebener quadratischer Matrizen @param matrix1 Erste Matrix @param matrix2 Zweite Matrix @param dimension Anzahl Zeilen/Spalten der Matrizen @return Zeiger auf erstellte Matrix **/ //############################################################################### int *matrix_ganzzahl_addieren(int *matrix1, int *matrix2, int dimension) { int *matrix = liste_ganzzahl_erstellen(dimension * dimension); for (int i = 0; i < dimension * dimension; i++) { *(matrix + i) = *(matrix1 + i) + *(matrix2 + i); } return matrix; } //############################################################################### /** Liefert eine neue Matrix als Ergebnis aus der Subtraktion zweier gegebener quadratischer Matrizen @param matrix1 Erste Matrix @param matrix2 Zweite Matrix @param dimension Anzahl Zeilen/Spalten der Matrizen @return Zeiger auf erstellte Matrix **/ //############################################################################### int *matrix_ganzzahl_subtrahieren(int *matrix1, int *matrix2, int dimension) { int *matrix = liste_ganzzahl_erstellen(dimension * dimension); for (int i = 0; i < dimension * dimension; i++) { *(matrix + i) = *(matrix1 + i) - *(matrix2 + i); } return matrix; } //############################################################################### /** Liefert eine neue Matrix als Ergebnis aus der Multiplikation zweier gegebener quadratischer Matrizen @param matrix1 Erste Matrix @param matrix2 Zweite Matrix @param dimension Anzahl Zeilen/Spalten der Matrizen @return Zeiger auf erstellte Matrix **/ //############################################################################### int *matrix_ganzzahl_multiplizieren(int *matrix1, int *matrix2, int dimension) { int *matrix = liste_ganzzahl_erstellen(dimension * dimension); // i Zeilen, j Spalten, m Durchlauf for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { for (int m = 0; m < dimension; m++) { *(matrix + (i * dimension) + j) += *(matrix1 + (i * dimension) + m) * *(matrix2 + (m * dimension) + j); } } } return matrix; }
TypeScript
UTF-8
438
2.609375
3
[]
no_license
import axios, { AxiosResponse } from "axios" import { User } from "src/domain/models/GitHub" const BASE_URL = "https://api.github.com" type CallGetMembersRequest = { organizationName: string } export type CallGetMembersResponse = AxiosResponse<User[]> export const callGetMembers = ( params: CallGetMembersRequest ): Promise<CallGetMembersResponse> => { return axios.get(`${BASE_URL}/orgs/${params.organizationName}/members`) }
C#
UTF-8
586
3.40625
3
[]
no_license
using System.Collections.Generic; namespace CollectionHirahy { class MyList : IAddable, IRemoveable, IUseable { public Stack<string> Collection { get; set; } public int Count { get ; set ; } public MyList() { Collection = new Stack<string>(); Count = 0; } public int Add(string item) { Count++; Collection.Push(item); return 0; } public string Remove() { Count--; return Collection.Pop(); } } }
Java
UTF-8
1,826
2.546875
3
[]
no_license
package com.github.wally.wcdbsample.util; import android.content.Context; import com.tencent.wcdb.database.SQLiteDatabase; import com.tencent.wcdb.database.SQLiteOpenHelper; import java.io.File; import java.nio.charset.Charset; /** * Package: com.github.wally.wcdb_sample.util * FileName: SimpleDBHelper * Date: on 2018/8/4 上午11:39 * Auther: zihe * Descirbe: * Email: hezihao@linghit.com */ public class SimpleDBHelper extends SQLiteOpenHelper { private Context mContext; // 数据库 db 文件名称 private static final String DEFAULT_NAME = "sample.db"; // 默认版本号 private static final int DEFAULT_VERSION = 1; public SimpleDBHelper(Context context) { super(context, DEFAULT_NAME, "wally".getBytes(Charset.forName("utf-8")), null, DEFAULT_VERSION, null); this.mContext = context; } @Override public void onCreate(SQLiteDatabase db) { //创建一张表 String sql = "CREATE TABLE IF NOT EXISTS person (\n" + "\t`id` char(32) NOT NULL,\n" + "\t`person_name` varchar(100) DEFAULT NULL,\n" + "\t`sex` varchar(20) DEFAULT NULL,\n" + "\t`age` int(11) DEFAULT NULL,\n" + " `create_time` datetime DEFAULT NULL,\n" + " `update_time` datetime DEFAULT NULL,\n" + " `version` int(11) DEFAULT NULL,\n" + " `delete_flag` int(11) DEFAULT NULL,\n" + " PRIMARY KEY (`id`)\n" + ")"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { dropDataBase(); } public boolean dropDataBase() { File file = mContext.getDatabasePath(DEFAULT_NAME); return SQLiteDatabase.deleteDatabase(file); } }
Java
UTF-8
3,866
2.3125
2
[]
no_license
package com.example.drawer; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.View; import android.widget.Toast; import com.github.paolorotolo.appintro.AppIntro2; import com.github.paolorotolo.appintro.AppIntroFragment; import com.github.paolorotolo.appintro.model.SliderPage; public class AppTutorial extends AppIntro2 { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); SliderPage sliderPage1 = new SliderPage(); sliderPage1.setTitle("Welcome to OrganizeIt!"); sliderPage1.setDescription("OrganizeIt provides you with a platform for you to keep track of anything you need!"); sliderPage1.setImageDrawable(R.drawable.main); sliderPage1.setBgColor(getColor(R.color.colorPrimary)); addSlide(AppIntroFragment.newInstance(sliderPage1)); SliderPage sliderPage2 = new SliderPage(); sliderPage2.setTitle("You Can Create Boards"); sliderPage2.setDescription("Boards work like a project. Think of it as the cover of a book."); sliderPage2.setImageDrawable(R.drawable.createboards); sliderPage2.setBgColor(getColor(R.color.colorPrimary)); addSlide(AppIntroFragment.newInstance(sliderPage2)); SliderPage sliderPage3 = new SliderPage(); sliderPage3.setTitle("Organize Your Boards By Adding Cards!"); sliderPage3.setDescription("Inside each board you can add cards. You can add a list of tasks to a card so you can keep track of the things you want!"); sliderPage3.setImageDrawable(R.drawable.createcards); sliderPage3.setBgColor(getColor(R.color.colorPrimary)); addSlide(AppIntroFragment.newInstance(sliderPage3)); SliderPage sliderPage4 = new SliderPage(); sliderPage4.setTitle("Manage Your Team!"); sliderPage4.setDescription("With OrganizeIt you can add collaborators to your Boards if you are working on something together1"); sliderPage4.setImageDrawable(R.drawable.manageteam); sliderPage4.setBgColor(getColor(R.color.colorPrimary)); addSlide(AppIntroFragment.newInstance(sliderPage4)); SliderPage sliderPage5 = new SliderPage(); sliderPage5.setTitle("You are Ready !"); sliderPage5.setDescription("You are now ready to start using the application! Feel free to explore other awesome features!"); sliderPage5.setImageDrawable(R.drawable.readystartexploring); sliderPage5.setBgColor(getColor(R.color.colorPrimary)); addSlide(AppIntroFragment.newInstance(sliderPage5)); // Bind the background to the intro //setBackgroundResource(R.drawable.ic_launcher_background); } @Override public void onSkipPressed(Fragment currentFragment) { super.onSkipPressed(currentFragment); Toast.makeText(this, "You should have read the tutorial!", Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, Login.class)); finish(); // Do something when users tap on Skip button. } @Override public void onDonePressed(Fragment currentFragment) { super.onDonePressed(currentFragment); finish(); startActivity(new Intent(this, Login.class)); // Do something when users tap on Done button. } @Override public void onSlideChanged(@Nullable Fragment oldFragment, @Nullable Fragment newFragment) { super.onSlideChanged(oldFragment, newFragment); // Do something when the slide changes. } }
Markdown
UTF-8
5,016
3.734375
4
[]
no_license
# -Kaggle-Traveling-Santa-2018---Prime-Paths This repository includes the codes I wrote for the titled competition on Kaggle. >Link to competition: https://www.kaggle.com/c/traveling-santa-2018-prime-paths <br> The core of the approach is **ACO (Ant Colony Optimization)**. > For details, we refer the readers to https://ieeexplore.ieee.org/document/4129846 <br> Notice that ACO was originally designed to solve TSP (Travelling Salesman Problem), where it is required to start and end on the same city. However, it is easy to implement the idea of ACO and generalize the algorithm to allow the starting and ending city to be different. This is the case for the ACO algorithm I wrote for this competition. ## Main issues of implementing ACO directly on the collection of all cities are: 1. The size of the collection of cities is too big to be all processed at the same time. 2. The hyper-paramters of ACO needs to be tuned. To solve issue 1, k-means clustering is applied layer by layer. More precisely, suppose k = 20 is chosen, <br> (1) partition the whole collection of cities into k sub-clusters; <br> (2) for each sub-cluster $S$, if $\text{size}(S)\geq k$, sub-partition $S$ into $\text{roundup}(\text{size}(S)/k)$ sub-clusters; <br> (3) continue (2) until all subclusters have size less than or equal to $k$.<br> Notice that there is a tree structure in the process of establishing the sub-clusters, where the root represents the collection of all cities and for each node, its children are its sub-clusters. To solve issue 2, a naive randomized paramter selection is implemented. Namely, pre-setting a (bounded) range for the hyper-parameters $(\alpha, \beta, \rho, Q)$, then uniformly generate choices of the hyper-parameters inside the range. For each generated hyper-paramters, implement ACO and compare the results to obtain the best result. (**Remark**: At the beginning, **BFO (Bacterial Foraging Optimization)** is planned to be used for paramter tuning. However, I realized that it is not as efficient as expected, so I decided to give up on BFO and naively implement randomized selection.) ## Algorithm (High-Level): 1. Partition the collection of all cities into the tree structure mentioned in 1 above. 2. For each sub-cluster that has sub-clusters, apply ACO, where the distances between sub-clusters are defined as the minimum among the distances between all possible pairs of inter-sub-cluster points. (The computational cost of this distance by brute force is very high. A random walk algorithm on two given point clouds is designed and implemented.) 3. With the results obtained in 2, it remains to apply ACO on "bottom sub-clusters". The resulting path is a "good" path. However, it is still "not good enough" to be competitive in this competition since the "prime city constraint" is not taken into consideration yet. To put the "prime city constraint" into effect, the following "path modifictaion" approach is invented and called **ACC (Ant Colony Correction)**: Set a positive integer $k$, say $k = 20$. 4. For a given path $P$ of length $L$, randomly choose an integer $s$ in $[0,L-k]$. Consider the sub-path $P|{[s,s+k]}$. Now apply ACO on $P|{[s,s+k]}$ (several times); if the best sub-path obtained by ACO is better than $P|{[s,s+k]}$, replace $P|{[s,s+k]}$ by the obtained best path. 5. Continue 4 as many times as desired. We may also change $k$ before continuing 4. ## Issue encountered when implenting 5: At the beginning, the improvement is very substantial; however, after 2 days, there are only very small improvements. My solution is to write parallel agents that modify the path simultaneously. However, it seems the improvement decrease is exponential and not able to be overcome by adding finitely many parallel agents. ## How to run the code Please look at the codes in "(Done) Code-Execute-Final-Test.ipynb" and run the codes therein. ## Final result/Comments: My best result: 1531162.85 <br> Rank-#1 result: 1513747.36 <br> It seems my best result is not too far from the result ranked #1; however, the competition is so competitive(?) that the ranking difference is a bit high. I am also suspecting that there are teams sharing codes/results privately to make the ranking difference exaggerated. I list below the teams which have exactly the same results (I suppose this would happen with probability almost 0(?); namely, they share privately codes/results with probability almost 1(?)): >961 - 963, 912 - 920, 803 - 815, 790 - 794, 779 - 783, 759 - 766, 741 - 748, 728 - 729, 720 - 727, 718 - 719, 665 - 676, 646 - 648, 632 - 635, 628 - 631, 614 - 616, 600 - 604, 558 - 599, 556 - 557, 547 - 549, 540 - 542, 450 - 537, 447 - 448, 442 - 444, 439 - 441, 418 - 432, 415 - 416, 371 - 407, 339 - 370, 336 - 337, 303 - 313, 300 - 302, 282 - 285, 280 - 281, 277 - 279, 271 - 273, 252 - 253, 97 - 98. If one doesn't believe in me, one can visit the following link to have a look: > https://www.kaggle.com/c/traveling-santa-2018-prime-paths/leaderboard
PHP
UTF-8
1,057
2.828125
3
[]
no_license
<?php namespace Cube\CoreBundle\Form\Model; class Register { private $username; private $email; private $plainPassword; /** * @return mixed */ public function getUsername() { return $this->username; } /** * @param mixed $username * @return Register */ public function setUsername($username) { $this->username = $username; return $this; } /** * @return mixed */ public function getEmail() { return $this->email; } /** * @param mixed $email * @return Register */ public function setEmail($email) { $this->email = $email; return $this; } /** * @return mixed */ public function getPlainPassword() { return $this->plainPassword; } /** * @param mixed $plainPassword * @return Register */ public function setPlainPassword($plainPassword) { $this->plainPassword = $plainPassword; return $this; } }
Python
UTF-8
2,093
2.8125
3
[]
no_license
from torch.nn import functional as F from torch import nn import torch from math import sqrt def hidden_layer_init(layer): fan_in = layer.weight.data.size(0) limit = 1 / sqrt(fan_in) return -limit, limit class Actor(nn.Module): def __init__(self, observation_size, action_size, seed, fc1_units=400, fc2_units=300): super().__init__() # Random seed torch.manual_seed(seed) # Layers self.fc1 = nn.Linear(observation_size, fc1_units) self.fc2 = nn.Linear(fc1_units, fc2_units) self.fc3 = nn.Linear(fc2_units, action_size) # Initialize self.reset_parameters() def reset_parameters(self): # Initialize weights and biases self.fc1.weight.data.uniform_(*hidden_layer_init(self.fc1)) self.fc2.weight.data.uniform_(*hidden_layer_init(self.fc2)) # Initialize output layer weights and biases self.fc3.weight.data.uniform_(-3e-3, 3e-3) def forward(self, state): x = self.fc1(state) x = F.relu(x) x = self.fc2(x) x = F.relu(x) return torch.tanh(self.fc3(x)) class Critic(nn.Module): def __init__(self, observation_size, action_size, seed, fc1_units=400, fc2_units=300): super().__init__() # Random seed torch.manual_seed(seed) # Layers self.fc1 = nn.Linear(observation_size, fc1_units) self.fc2 = nn.Linear(fc1_units + action_size, fc2_units) self.fc3 = nn.Linear(fc2_units, 1) # Initialize self.reset_parameters() def reset_parameters(self): # Initialize weights and biases self.fc1.weight.data.uniform_(*hidden_layer_init(self.fc1)) self.fc2.weight.data.uniform_(*hidden_layer_init(self.fc2)) # Initialize output layer weights and biases self.fc3.weight.data.uniform_(-3e-3, 3e-3) def forward(self, state, action): x = self.fc1(state) x = F.relu(x) x = torch.cat((x, action), dim=1) x = self.fc2(x) x = F.relu(x) return self.fc3(x)
Java
UTF-8
4,530
2.25
2
[]
no_license
package com.techology.controller; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.techology.base.BaseController; import com.techology.common.ExcelExport; import com.techology.common.Help; import com.techology.common.RewardExcelUtil; import com.techology.services.CompetitionServices; import com.techology.services.ExcelServices; import com.techology.services.RewardService; /** * 导出报表 * * @author jason * */ @Controller public class ExcelController extends BaseController { // ****************变量定义区**************************************** // ****************注入区**************************************** @Resource private ExcelServices excelServices; @Resource private RewardService rewardService; @Resource private CompetitionServices competitionServices; // ****************页面初始化区**************************************** /** * 导出报表 */ @RequestMapping("exportExcel") public String exportExcel() { setAttr("grade", Help.GRADE); return "Other/exportExcel"; } /** * 复杂表格html模板 * * @return */ /* * @RequestMapping("rewardModel") public String modelReward(){ * setAttr("reward", rewardService.getAll()); return "Other/rewardModel"; } */ // ****************页面提交处理区**************************************** @RequestMapping("exportExcel1") public void exportExcel1(HttpServletResponse response) { ExcelExport excelUtil = new ExcelExport( excelServices.getCompetionTitle(), excelServices.getCompetionContent(), "德州学院大学生科技文化竞赛级别认定、承办单位汇总表", "德州学院大学生科技文化竞赛级别认定、承办单位汇总表", excelServices.getCompetionColumWidth()); try { excelUtil.exportExcel(response); } catch (Exception e) { e.printStackTrace(); } } @RequestMapping("exportExcel2") public void exportExcel2(HttpServletResponse response) { RewardExcelUtil excelUtil = new RewardExcelUtil( excelServices.getRewardColumNames(), excelServices.getRewardData(), "德州学院大学生科技文化竞赛类别等级、奖励规定一览表", "德州学院大学生科技文化竞赛类别等级、奖励规定一览表", excelServices.getRewardColumsWidth()); try { excelUtil.exportExcel(response); } catch (Exception e) { e.printStackTrace(); } } /** * 待修改 * @param response */ @RequestMapping("exportExcel3") public void exportExcel3(HttpServletResponse response) { String years = getAttr("years").toString(); String grade = getAttr("grade").toString(); ArrayList<ArrayList<String>> listData = excelServices .getStudentRecordData(years, grade); if (listData != null) { ExcelExport excelUtil = new ExcelExport( excelServices.getStudentRecordColums(), listData, "德州学院学生获得大学生科技文化竞赛国家级奖励统计表", "德州学院" + years + "年度学生获得大学生科技文化竞赛" + grade + "奖励统计表", excelServices.getStudentRecordColumsWidth()); try { excelUtil.exportExcel(response); } catch (Exception e) { e.printStackTrace(); } } else { try { response.getWriter().print( Help.getScript("暂无数据", "exportExcel.html")); } catch (IOException e) { e.printStackTrace(); } } } @RequestMapping("exportExcel4") public void exportExcel4(HttpServletResponse response) { String years = getAttr("years").toString(); ArrayList<ArrayList<String>> listData = excelServices .getTeacherRecordData(years); if (listData != null) { ExcelExport excelUtil = new ExcelExport( excelServices.getTeacherRecordColums(), listData, "德州学院" + years + "年度教师指导学生获得大学生科技文化竞赛国家级和省级奖励统计表", "德州学院" + years + "年度教师指导学生获得大学生科技文化竞赛国家级和省级奖励统计表", excelServices.getTeacherRecordColumsWidth()); try { excelUtil.exportExcel(response); } catch (Exception e) { e.printStackTrace(); } } else { try { response.getWriter().print( Help.getScript("暂无数据", "exportExcel.html")); } catch (IOException e) { e.printStackTrace(); } } } }
C++
UTF-8
202
2.5625
3
[]
no_license
#include<iostream> #include"List.h" using namespace std; void main() { List a; a.print(); a.add(7); a.insert(2, 1000); a.remove(3); cout << '\n'; List b; a = b; a.print(); system("pause"); }
TypeScript
UTF-8
1,232
2.546875
3
[ "MIT" ]
permissive
import { Injectable } from '@nestjs/common'; import { UserRepository } from '../repositories/userRepository'; import { CreateUserDto } from '../dto/create-user.dto'; import { UserDto } from '../dto/user.dto'; import { ApplicationException } from '../common/exceptions/application.exception'; import { ResponseModel } from '../dto/response-model'; @Injectable() export class UserService { constructor(private userRepository: UserRepository) {} async createUser( createUserDto: CreateUserDto, ): Promise<ResponseModel<UserDto>> { const existUser = await this.userRepository.findUserByEmail( createUserDto.email, ); if (existUser) { throw new ApplicationException(400, 'User has already exist!'); } const passwordHash = createUserDto.password; const user = await this.userRepository.createUser( createUserDto, passwordHash, ); return { status: 'OK', statusCode: 200, data: { id: user._id, email: user.email, firstName: user.firstName, lastName: user.lastName, createdAt: user.createdAt, updatedAt: user.updatedAt, }, }; } getHello(): string { return 'Hello World! (User)'; } }
C#
UTF-8
2,705
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using chefs_dishes.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; namespace chefs_dishes.Controllers { public class ChefController : Controller { //injecting context service private ChefContext dbContext; public ChefController(ChefContext context) { dbContext = context; } [HttpGet("")] public IActionResult Index() { return View("Index"); } [HttpGet("new")] public IActionResult ChefNew(){ return View("ChefNew"); } [HttpPost("addchef")] public IActionResult AddChef(Chef chef){ if(ModelState.IsValid){ // string dob = chef.DOB.ToString("dd/MM/yyyy"); // string now = DateTime.Now.ToString("dd/MM/yyyy"); // if(chef.DOB < DateTime.Now){ dbContext.Add(chef); dbContext.SaveChanges(); return RedirectToAction("Index"); } // else{ // ModelState.AddModelError("DOB", "Date of birth must be in the past"); // return View("ChefNew"); // } // } else{ return View("ChefNew"); } } [HttpGet("dishes")] public IActionResult Dishes(){ List<Dish> DishAndChef = dbContext.dishes.Include(dish => dish.Creator).ToList(); //make sure to turn this into a List. Can use ViewBag as well. return View("Dishes", DishAndChef); } [HttpGet("dishes/new")] public IActionResult AddDish(){ ViewBag.allchefs = dbContext.chefs; return View("DishNew"); } [HttpPost("ProcessDish")] public IActionResult ProcessDish(Dish dish){ if(ModelState.IsValid){ dbContext.Add(dish); dbContext.SaveChanges(); return RedirectToAction("Dishes"); } else{ ViewBag.allchefs = dbContext.chefs; //prepopulate allchefs will help save the NullReference error: foreach(var dish in @ViewBag.allchefs){ return View("DishNew"); } } [HttpGet("chefs")] public IActionResult Chefs(){ ViewBag.ChefwithDish = dbContext.chefs.Include(c => c.CreatedDishes); //make sure to turn this into a List foreach(var chef in ViewBag.ChefwithDish){ var today = DateTime.Today; ViewBag.age = today.Year - chef.DOB.Year; // ViewBag.DishCount = chef.CreatedDishes.Count; } return View("Chefs"); } } }
Python
UTF-8
355
2.765625
3
[]
no_license
from abc import ABC, abstractmethod class Split(ABC): def __init__(self, user): self.user = user self.amount = 0 def getUser(self): return self.user def setUser(self, user): self.user = user def getAmount(self): return self.amount def setAmount(self, amount): self.amount = amount
Java
UTF-8
5,392
2.265625
2
[]
no_license
package fw.supernacho.ru.foxweather.recyclers; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import fw.supernacho.ru.foxweather.MainData; import fw.supernacho.ru.foxweather.R; import fw.supernacho.ru.foxweather.data.DayPrediction; import fw.supernacho.ru.foxweather.data.openweather.Wind; public class WeekViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView textViewDayDate; private ImageView imageViewDayIcon; private TextView textViewDayTemp; private List<DayPrediction> daysList; private DateFormat timeStamp; private TextView textViewPressure; private TextView textViewHumidity; private TextView textViewWindDegreeM; private TextView textViewWindDegreeD; private TextView textViewWindDegreeE; private TextView textViewWindDegreeN; private TextView textViewWindSpeedM; private TextView textViewWindSpeedD; private TextView textViewWindSpeedE; private TextView textViewWindSpeedN; private LinearLayout frameMoreInfo; WeekViewHolder(LayoutInflater inflater, ViewGroup parent) { super(inflater.inflate(R.layout.day_list_item, parent, false)); itemView.setOnClickListener(this); initViews(); frameMoreInfo.setVisibility(View.GONE); daysList = MainData.getInstance().getWeekPrediction().getDaysList(); timeStamp = new SimpleDateFormat("E, dd MMMM", Locale.US); } private void initViews() { textViewDayDate = itemView.findViewById(R.id.text_view_day_date); imageViewDayIcon = itemView.findViewById(R.id.image_view_day_icon); textViewDayTemp = itemView.findViewById(R.id.text_view_day_temp); textViewPressure = itemView.findViewById(R.id.text_view_more_info_pressure_data); textViewHumidity = itemView.findViewById(R.id.text_view_more_info_humidity_data); textViewWindDegreeM = itemView.findViewById(R.id.text_view_more_info_degree_data); textViewWindDegreeD = itemView.findViewById(R.id.text_view_more_info_degree_data_d); textViewWindDegreeE = itemView.findViewById(R.id.text_view_more_info_degree_data_e); textViewWindDegreeN = itemView.findViewById(R.id.text_view_more_info_degree_data_n); textViewWindSpeedM = itemView.findViewById(R.id.text_view_more_info_wind_speed); textViewWindSpeedD = itemView.findViewById(R.id.text_view_more_info_wind_speed_d); textViewWindSpeedE = itemView.findViewById(R.id.text_view_more_info_wind_speed_e); textViewWindSpeedN = itemView.findViewById(R.id.text_view_more_info_wind_speed_n); frameMoreInfo = itemView.findViewById(R.id.frame_more_info); } void bind(int position) { DayPrediction day = daysList.get(position); List<Wind> winds = day.getWinds(); textViewDayDate.setText(timeStamp.format(day.getDayDt() * 1000)); setIcon(day.getDayIcoId()); textViewDayTemp.setText(String.valueOf(day.getStringDayTemp())); textViewPressure.setText(String.valueOf(day.getPressure())); textViewHumidity.setText(String.valueOf(day.getHumidity())); textViewWindDegreeM.setText(String.valueOf(winds.get(0).getDeg())); textViewWindSpeedM.setText(String.valueOf(winds.get(0).getSpeed())); textViewWindDegreeD.setText(String.valueOf(winds.get(1).getDeg())); textViewWindSpeedD.setText(String.valueOf(winds.get(1).getSpeed())); textViewWindDegreeE.setText(String.valueOf(winds.get(2).getDeg())); textViewWindSpeedE.setText(String.valueOf(winds.get(2).getSpeed())); textViewWindDegreeN.setText(String.valueOf(winds.get(3).getDeg())); textViewWindSpeedN.setText(String.valueOf(winds.get(3).getSpeed())); } private void setIcon(int iconId) { int id = iconId / 100; if (iconId == 800) { imageViewDayIcon.setImageResource(R.drawable.weather_icon_sun8001); } else { switch (id) { case 2: imageViewDayIcon.setImageResource(R.drawable.weather_icon_thunder200); break; case 3: imageViewDayIcon.setImageResource(R.drawable.weather_icon_drizzle300); break; case 5: imageViewDayIcon.setImageResource(R.drawable.weather_icon_rain500); break; case 6: imageViewDayIcon.setImageResource(R.drawable.weather_icon_snow600); break; case 7: imageViewDayIcon.setImageResource(R.drawable.weather_icon_mist700); break; case 8: imageViewDayIcon.setImageResource(R.drawable.weather_icon_clouds801); break; } } } @Override public void onClick(View view) { if (frameMoreInfo.getVisibility() == View.GONE) { frameMoreInfo.setVisibility(View.VISIBLE); } else { frameMoreInfo.setVisibility(View.GONE); } } }
Python
UTF-8
1,278
3.296875
3
[]
no_license
from pathlib import Path original_inputs = list(map(int, (Path(__file__).parent / 'day2.input').read_text().split(','))) inputs = original_inputs.copy() inputs[1] = 12 # + 900000 inputs[2] = 2 # + 1 # part 1 def run_ops(): for op_idx in range(int(len(inputs)/4)): if inputs[op_idx * 4] == 99: return inputs[0] else: actual_idx = op_idx * 4 op = inputs[actual_idx] pos1 = inputs[actual_idx + 1] pos2 = inputs[actual_idx + 2] res_pos = inputs[actual_idx + 3] if op == 1: inputs[res_pos] = inputs[pos1] + inputs[pos2] elif op == 2: inputs[res_pos] = inputs[pos1] * inputs[pos2] else: print('something went wrong') print(run_ops()) # part 2 INITIAL_VALUE = 1690717 TARGET_NUM = 19690720 - INITIAL_VALUE NOUN_MULTIPLIER = 900000 # inputs[0] increments by 900000 for every noun increment VERB_MULTIPLIER = 1 # verb increments increases inputs[0] by factor of 1 # b = 1690717 for noun in range(len(original_inputs)): verb = int((TARGET_NUM - noun * NOUN_MULTIPLIER)/VERB_MULTIPLIER) if verb < 0: break elif verb < len(original_inputs): print(noun, verb, 100 * noun + verb)
Python
UTF-8
5,538
3.296875
3
[]
no_license
import psycopg2 import logging # will allow you to track what happens in the application, and identify problems with the code import argparse import sys # set the log output file, and the log level logging.basicConfig(filename="snippets.log", level=logging.DEBUG) logging.debug("Connecting to PostgreSQL") # connect to database from python connection = psycopg2.connect( database = "drinkwater", user = "postgres", password = "lawncare" ) logging.debug("Database connection established.") def put(name,snippet,hide=False): """Store a snippet with an associated name.""" # import pdb; pdb.set_trace() logging.info("Storing snippet {!r}: {!r}".format(name, snippet)) with connection.cursor() as cursor: try: command = "insert into snippets values (%s, %s, %s)" cursor.execute(command, (name, snippet, hide)) except psycopg2.IntegrityError: connection.rollback() command = "update snippets set message=%s, hidden=%s where keyword=%s" cursor.execute(command, (snippet,hide,name)) connection.commit() logging.debug("Snippet stored successfully.") return name, snippet # connection.cursor method: creating a cursor object - allows us to run SQL # commands in Postgres session insert into statement: constructing a string # which contains insert into, with two placeholders for keyword and message # (%s) cursor.execute: running the command on the database, substituting the # snippet keyword and message by passing them as a tuple connection.commit: # saving changes to the database ### GET CHALLENGE ### # Try to implement the get() function # Construct a select statement to retrieve the snippet with a given keyword # Run the statement on the database # Fetch the corresponding row from the database # Run the message from the row def get(name): """Retrieve the snippet with a given keyword""" logging.info("Retrieving snippet {!r}".format(name)) with connection.cursor() as cursor: cursor.execute("select message from snippets where keyword=%s", (name,)) row = cursor.fetchone() logging.debug("Snippet retrieved successfully.") if not row: # If no snippet was found with that name logging.debug("Snippet does not exist") return "404: Snippet Not Found" else: logging.debug("Snippet retrieved successfully.") return row[0] # Snippets Catalog # Create Catalog function: Provides list of keywords to select from def catalog(): """Query keywords from snippets table""" # import pdb; pdb.set_trace() logging.info("Querying the database") with connection.cursor() as cursor: command = "select keyword, message from snippets where hidden=False \ order by keyword ASC" cursor.execute(command) rows = cursor.fetchall() for x in rows: print("the keyworrd is: {}, the message is: {}".format(x[0], x[1])) logging.debug("Query complete") # Create Search function: Search for word within snippet messages def search(word): """Return a list of snippets containing a given word""" logging.info("Searching snippets for {}".format(word)) with connection.cursor() as cursor: cursor.execute( "select * from snippets where hidden=False \ and message like '%{}%'".format(word)) # select * from snippets where hidden=False and message like %insert% rows = cursor.fetchall() for row in rows: print(row) logging.debug("Search complete") def main(): # import pdb; pdb.set_trace() """Main function""" logging.info("Constructing parser") parser = argparse.ArgumentParser(description="Store and retrieve snippets of text") subparsers = parser.add_subparsers(dest="command", help="Available commands") # Subparser for the put command logging.debug("Constructing put subparser") put_parser = subparsers.add_parser("put", help="Store a snippet") put_parser.add_argument("name", help="Name of the snippet") put_parser.add_argument("snippet", help="Snippet text") # Subparser for the get command get_parser = subparsers.add_parser("get", help="Retrieve a snippet") get_parser.add_argument("name", help="Name of the snippet") # Subparser for the catalog command catalog_parser = subparsers.add_parser("catalog", help = "List keywords fron snippet") # Subparser for the search command import pdb; pdb.set_trace() search_parser = subparsers.add_parser("search", help = "Query snippets based on word") search_parser.add_argument("word", help = "word in snippet") arguments = parser.parse_args() # Convert parsed arguments from Namespace to dictionary arguments = vars(arguments) command = arguments.pop("command") if command == "put": name, snippet = put(**arguments) print("Stored {!r} as {!r}".format(snippet, name)) elif command == "get": snippet = get(**arguments) print("Retrieved snippet: {!r}".format(snippet)) elif command == "catalog": catalog() print("Retrieved keywords") # elif command == "search": # string = search(**arguments) # print # print("Search complete") elif command == "search": word = search(**arguments) print() print("Search complete") print("Found {} in these messages".format(word)) if __name__ == "__main__": main()
JavaScript
UTF-8
3,291
3.046875
3
[ "BSD-2-Clause" ]
permissive
// Copyright (c) Microsoft Corporation // All rights reserved. // BSD License // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE // Math_morton.js // Defines the Seadragon2.Math.morton() and reverseMorton() methods. /*global SDMath, SDPoint */ /*jshint strict: false, plusplus: false, bitwise: false */ var /** * Returns the Morton number (z-order) of the 2D point at the * given x- and y-values. * @method morton * @param {number} x The x-value of the 2D point. * @param {number} y The y-value of the 2D point. * @return {number} */ /** * Returns the Morton number (also known as z-order) of the given 2D point. The * point can be a Point instance or an {x,y} point literal. * @method morton&nbsp; * @param {Point} point * @return {number} */ SDMath_morton = SDMath.morton = function (varargs) { var x, y, arg0 = arguments[0], result, position, bit; if (typeof arg0 === "object") { x = arg0.x; y = arg0.y; } else { x = arg0; y = arguments[1]; } result = 0; position = 0; bit = 1; while (bit <= x || bit <= y) { if (bit & x) { result |= 1 << (2 * position + 1); } if (bit & y) { result |= 1 << (2 * position); } position++; bit = 1 << position; } return result; }, /** * Returns the 2D point represented by the given Morton number (z-order). * @method reverseMorton * @param {number} n * @return {Point} */ SDMath_reverseMorton = SDMath.reverseMorton = function (n) { var xBits = [], yBits = [], x = 0, y = 0, i; while (n > 0) { yBits.push(n % 2); n = n >> 1; xBits.push(n % 2); n = n >> 1; } for (i = 0; i < xBits.length; i++) { x += (1 << i) * xBits[i]; } for (i = 0; i < yBits.length; i++) { y += (1 << i) * yBits[i]; } return new SDPoint(x, y); };
Java
UTF-8
503
2.015625
2
[]
no_license
package com.proj.emi.model.base; public class InBody { private String result; // result private String description;// description public String getResult() { return result; } public InBody setResult(String result) { this.result = result; return this; } public String getDescription() { return description; } public InBody setDescription(String description) { this.description = description; return this; } }
Java
UTF-8
1,293
2.125
2
[]
no_license
package com.capgemini.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.capgemini.entities.ServiceRequest; import com.capgemini.entities.ServiceRequestDetail; import com.capgemini.repository.ServiceRequestDetailRepository; import com.capgemini.repository.ServiceRequestRepository; @Service public class AdminServiceImpl implements IAdminService { @Autowired private ServiceRequestDetailRepository srdrepository; @Autowired private ServiceRequestRepository ser_reqrepository; /*@Autowired private ServiceCatalogRepository sercatrepository;*/ @Override public String generateRequestDetails(ServiceRequestDetail serviceRequestDetali) { if(serviceRequestDetali.getService_request()!=null) { ServiceRequest serreq=ser_reqrepository.findById(serviceRequestDetali.getService_request().getService_req_id()).get(); serviceRequestDetali.setService_request(serreq); } /*if(servicerequestdetail.getServicecatalog()!=null) { ServiceCatalog sercat=sercatrepository.findById(servicerequestdetail.getServicecatalog().getService_catalog_id()).get(); servicerequestdetail.setServicecatalog(sercat); }*/ srdrepository.save(serviceRequestDetali); return "Service Details generated!!!"; } }
Python
UTF-8
953
3.015625
3
[]
no_license
from Date import Date from card import Card class VipCard(Card): # Gọi tới constructor của lớp cha (card) def __init__(self, userID, userName, lastDate, allMoney): self.userID = userID self.userName = userName self.firstDate = Date(1,2,2020) self.lastDate = lastDate self.allMoney = allMoney self.yearOfVip = 0 self.bonusPercentMoney = 0 def addMoney(self,money): self.allMoney = money + money*self.bonusPercentMoney return self.allMoney def printAllBasicCardData(self): cardDetail = [self.userID,self.userName,self.lastDate,self.allMoney,self.yearOfVip] return cardDetail def bonusPercentMoneyVip(self): self.bonusPercentMoney = max(self.yearOfVip * 0.02,0.2) return self.bonusPercentMoney def removeAllMoney(self): if getDifference(self.firstDate, self.lastDate) > 365: self.allMoney = 0
C#
UTF-8
36,819
2.515625
3
[ "MIT" ]
permissive
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // #pragma warning disable 0162 #pragma warning disable 0429 using System; using System.Linq; using System.Xml; using System.IO; using System.Reflection; using System.Diagnostics; using System.Threading; using System.Globalization; namespace System.Xml.Serialization.LegacyNetCF { internal struct XmlDeserializationEvents { #if !FEATURE_LEGACYNETCF public XmlNodeEventHandler onUnknownNode; public XmlAttributeEventHandler onUnknownAttribute; public XmlElementEventHandler onUnknownElement; public UnreferencedObjectEventHandler onUnreferencedObject; #endif public object sender; } public class XmlSerializer { //***************************************************************** // Static Data //***************************************************************** private static XmlSerializerNamespaces s_DEFAULT_NAMESPACES; //***************************************************************** // Data //***************************************************************** /// <summary> /// Events that will be fired while deserializing the object /// </summary> private XmlDeserializationEvents _events = new XmlDeserializationEvents(); /// <summary> /// The reflector that gathers info on object /// </summary> private XmlSerializationReflector _reflector; /// <summary> /// The reflection data to be used while serializing /// and deserializing the object. (primary serialization type) /// </summary> private LogicalType _logicalType; /// <summary> /// Describes whether the object should be serialized using Soap section 5 encoding. /// </summary> /// <remarks> /// True for RPC/encoded. /// False for RPC/literal and Document/literal. /// Document/encoded is not an allowed configuration. /// When true, the SoapElementAttribute-style will be noticed /// instead of the XmlElementAttribute-style. /// </remarks> private bool _isEncoded; /// <summary> /// Array of extra types that can be serialized /// </summary> private LogicalType[] _extraTypes; /// <summary> /// The default namespace to use for all the XML elements. /// </summary> private string _defaultNamespace; //***************************************************************** // Constructors //***************************************************************** /// <summary> /// Constructs the XmlSerializer without reflecting over any types. /// </summary> /// <remarks> /// The default constructor. This constructor does not initialize /// the logical type reflection data used to serialize and /// deserialize the data. So, if this constructor is used then the /// reflection data is not collected until the object is serialized. /// If Deserialize is called before the reflection data is collected /// then we attempt to find the logical type using the name and /// namespace of the serialize object. /// </remarks> protected XmlSerializer() { } /// <summary> /// Constructs the XmlSerializer, reflecting over just the one given /// type and any types that are statically referenced from that type. /// </summary> public XmlSerializer(Type type) : this(type, null, null, null, null) { } /// <summary> /// Constructs the XmlSerializer, reflecting over just the one given /// type and any types that are statically referenced from that type. /// </summary> /// <param name="defaultNamespace">The default namespace to use for all the XML elements.</param> public XmlSerializer(Type type, string defaultNamespace) : this(type, null, null, null, defaultNamespace) { } /// <summary> /// Constructs the XmlSerializer, reflecting over just the one given /// type and any types that are statically referenced from that type. /// Reflection overrides may be given. /// </summary> /// <remarks> /// This consturctor allows you to specifiy attribute overrides. The /// overrides will be used to override any attributes found on the /// types inspected by the reflector. /// </remarks> public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, null, null, null) { } /// <summary> /// Constructs the XmlSerializer, reflecting over just the one given /// type and any types that are statically referenced from that type. /// Reflection overrides may be given. /// </summary> public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, null, root, null) { } /// <summary> /// Constructs the XmlSerializer, reflecting over the given /// types and any types that are statically referenced from them. /// Reflection overrides may be given. /// </summary> /// <param name="extraTypes">The additional types the serializer should be /// prepared to encounter during serialization of the primary <paramref name="type"/>.</param> /// <param name="defaultNamespace">The default namespace to use for all the XML elements.</param> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) { if (type == null) throw new ArgumentNullException("type"); if (defaultNamespace == null) defaultNamespace = ""; _events.sender = this; _isEncoded = false; if (root != null) { if (overrides == null) overrides = new XmlAttributeOverrides(); // If we're dealing with a nullable type, we need to set the override // on the generic type argument as well. System.Collections.Generic.List<Type> typesToOverride = new System.Collections.Generic.List<Type>(2); typesToOverride.Add(type); if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type[] args = type.GetGenericArguments(); if (args.Length > 0) { // just in case they passed in typeof(Nullable<>) with no generic arg typesToOverride.Add(args[0]); } } foreach (Type t in typesToOverride) { XmlAttributes attrs = overrides[t]; if (attrs != null) { attrs.XmlRoot = root; } else { attrs = new XmlAttributes(); attrs.XmlRoot = root; // Preserve any XmlType that may be declared on the type itself, // since by providing this XmlRoot override, we prevent any declared // XmlTypeAttribute from being reflected. object[] declaredAttributes = t.GetTypeInfo().GetCustomAttributes(typeof(XmlTypeAttribute), false).ToArray(); if (declaredAttributes.Length > 0) { // The user shouldn't have more than one defined, but just in case he does, // we read the last reflected one, to emulate the behavior of the // TypeAttributes class. attrs.XmlType = (XmlTypeAttribute)declaredAttributes[declaredAttributes.Length - 1]; } overrides.Add(t, attrs); } } } _defaultNamespace = defaultNamespace; _reflector = new XmlSerializationReflector(overrides, defaultNamespace); // Reflect over the main type. Never search over intrinsics so we get a // LogicalType with a RootAccessor whose Namespace property reflects the defaultNamespace. // In fact, any type's RootAccessor.Namespace may not be set correctly given // the defaultNamespace if it was reflected over previously. But since this // is the very first request we make of the m_Reflector, we're going to get // the right one. And this is the only place where that is important. _logicalType = _reflector.FindTypeForRoot(type, _isEncoded, defaultNamespace); // Reflect over the extra types if (extraTypes != null && extraTypes.Length > 0) { _extraTypes = new LogicalType[extraTypes.Length]; for (int typeNDX = 0; typeNDX < extraTypes.Length; ++typeNDX) { _extraTypes[typeNDX] = findTypeByType(extraTypes[typeNDX], defaultNamespace); } } // Reflect over the included types _reflector.ReflectIncludedTypes(); if (true /* AppDomain.CompatVersion >= AppDomain.Orcas */) _reflector.ReflectionDisabled = true; } /// <summary> /// Constructs the XmlSerializer using the XmlTypeMapping parameter /// to initialize the logical type(reflection data) of the object /// that will be serialized/de-serialized. /// </summary> /// <param name="xmlMapping"></param> /// <remarks> /// The XmlTypeMapping parameter has already reflected over the type, /// we just pull the reflection data from the <see cref="XmlTypeMapping"/> object. /// </remarks> public XmlSerializer(XmlTypeMapping xmlMapping) { if (xmlMapping == null) throw new ArgumentNullException("xmlMapping"); _events.sender = this; _reflector = xmlMapping.Reflector; _logicalType = xmlMapping.LogicalType; _isEncoded = xmlMapping.IsSoap; if (true /* AppDomain.CompatVersion >= AppDomain.Orcas */) _reflector.ReflectionDisabled = true; } /// <summary> /// Constructs the XmlSerializer, reflecting over the given /// types and any types that are statically referenced from them. /// </summary> /// <param name="extraTypes">The additional types the serializer should be /// prepared to encounter during serialization of the primary <paramref name="type"/>.</param> public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null) { } /// <summary> /// Creates an array of XmlSerializers. There is one /// XmlSerializer for each Type object in the specified types array. /// </summary> public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) return new XmlSerializer[0]; XmlSerializer[] ret = new XmlSerializer[types.Length]; for (int typeNdx = 0; typeNdx < types.Length; ++typeNdx) { ret[typeNdx] = new XmlSerializer(types[typeNdx]); } return ret; } /// <summary> /// Checks whether this XmlSerializer can begin deserialization at a given XmlElement. /// </summary> /// <remarks> /// It may return false for types that the serializer can deserialize as part of another type. /// </remarks> public virtual bool CanDeserialize(XmlReader reader) { if (_logicalType == null) return false; if (true /* AppDomain.CompatVersion >= AppDomain.Orcas */) { // Check the type passed to the constructor if (_isEncoded) { if (startElementMatchesAccessor(reader, _logicalType.TypeAccessor, false) || startElementMatchesAccessor(reader, _logicalType.TypeAccessor, true)) return true; } else { if (startElementMatchesAccessor(reader, _logicalType.RootAccessor, false)) return true; } bool soap12; XmlSerializationReader serialReader = initXmlSerializationReader(reader, null, out soap12); LogicalType type = serialReader.deriveTypeFromTypeAttribute(reader, null); if (type != null && _logicalType.Type.IsAssignableFrom(type.Type)) { return true; } } else { /* Rogue or earlier */ // Check the type passed to the constructor if (startElementMatchesAccessor(reader, _logicalType.TypeAccessor, false)) return true; // Checking extra types is only something we do for backward compatibility if (_extraTypes != null) { for (int typeNdx = 0; typeNdx < _extraTypes.Length; ++typeNdx) { if (startElementMatchesAccessor(reader, _extraTypes[typeNdx].TypeAccessor, false)) return true; } } LogicalType type = _reflector.FindType(new XmlQualifiedName(reader.Name, reader.NamespaceURI), _isEncoded); if (type != null) { return true; } } return false; } private bool startElementMatchesAccessor(XmlReader reader, Accessor accessor, bool soap12) { Debug.Assert(reader != null, "Null XmlReader"); Debug.Assert(accessor != null, "Null accessor"); if (true /* AppDomain.CompatVersion > AppDomain.Orcas */) { Debug.Assert(accessor.Namespace != null, accessor.Type.Type.FullName + " accessor created with null namespace."); return reader.IsStartElement(accessor.EncodedName, accessor.GetEncodedNamespace(soap12) ?? string.Empty); } else { if (reader.IsStartElement(accessor.EncodedName, accessor.Namespace)) return true; else return reader.LocalName.Equals(accessor.EncodedName); } } #if !FEATURE_LEGACYNETCF /// <summary> /// Serialize an object. /// </summary> public void Serialize(TextWriter textWriter, Object o) { Serialize(textWriter, o, null); } public void Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces) { // Initialize the xml text writer XmlTextWriter xmlWriter = new XmlTextWriter(textWriter); initWriter(xmlWriter); // Serialize object Serialize(xmlWriter, o, namespaces); } public void Serialize(Stream stream, Object o) { Serialize(stream, o, defaultNamespace); } public void Serialize(Stream stream, Object o, XmlSerializerNamespaces namespaces) { // Initialize the xml text writer XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); initWriter(xmlWriter); // Serialize object Serialize(xmlWriter, o, namespaces); } #endif public void Serialize(XmlWriter xmlWriter, Object o) { Serialize(xmlWriter, o, null); } public void Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces) { Serialize(xmlWriter, o, namespaces, null /*EncodingStyle*/); } [System.Security.FrameworkVisibilitySilverlightInternal] public void Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, string encodingStyle) { Debug.Assert(null != _logicalType, "Reflection info not initialized before calling Serialize"); try { bool objIsNotNull = (o != null); Type objType = objIsNotNull ? o.GetType() : null; LogicalType type; if (true /* AppDomain.CompatVersion >= AppDomain.Orcas */) { if (objIsNotNull && !_logicalType.Type.IsAssignableFrom(objType)) throw new InvalidCastException(SR.Format(SR.XmlInvalidCast, objType.FullName, _logicalType.Type.FullName)); type = _logicalType; } else { // Rogue/Whidbey and earlier type = (objIsNotNull && !_logicalType.Type.IsAssignableFrom(objType)) ? findTypeByType(objType, _defaultNamespace) : _logicalType; } // The soap message formatter considers enums to be non-nullable. // The desktop serializes null enums perfectly. So, we need to // flip this bit, so that we can serialize null enums as well. if (type.Type.GetTypeInfo().IsEnum) { type.TypeAccessor.IsNullable = type.RootAccessor.IsNullable = true; } if (objIsNotNull && !_isEncoded) { // Use custom handling if we are serializing a non-null primitive using literal encoding. if (SerializationHelper.IsSerializationPrimitive(type.Type)) { XmlSerializationWriter.SerializePrimitive(o, xmlWriter, type, _defaultNamespace, _isEncoded); xmlWriter.Flush(); return; } // Use custom handling if we are serializing a non-null enumeration using literal encoding. if (type.Type.GetTypeInfo().IsEnum) { XmlSerializationWriter.SerializeEnumeration(o, xmlWriter, type, _defaultNamespace, _isEncoded); xmlWriter.Flush(); return; } } // Initialize the formatter XmlSerializationWriter serialWriter = initXmlSerializationWriter(xmlWriter, encodingStyle); // Initialize the namespaces that will be passed to the serialization writer if (namespaces == null || namespaces.Count == 0) { // Use the default namespaces if the namespaces parameter is null and // the type requires that we use default namespaces namespaces = useDefaultNamespaces(type) ? defaultNamespace : null; } else if (objIsNotNull && typeof(System.Xml.Schema.XmlSchema).IsAssignableFrom(objType)) { // We special case the XmlSchema to consider the Xsd Namespace mapping checkXsdNamespaceMapping(ref namespaces, serialWriter); } // Serialize the object. serialWriter.SerializeAsElement(_isEncoded ? type.TypeAccessor : type.RootAccessor, o, namespaces); // We only flush the stream after writing the object since the user may want // to furthur manipulate the stream once the object is serialized. xmlWriter.Flush(); } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } } #if !FEATURE_LEGACYNETCF /// <summary> /// Deserialize an object /// </summary> public object Deserialize(Stream stream) { XmlTextReader xmlReader = new XmlTextReader(stream); initReader(xmlReader); return Deserialize(xmlReader); } public object Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); initReader(xmlReader); return Deserialize(xmlReader); } #endif public object Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null /*encodingStyle*/); } [System.Security.FrameworkVisibilitySilverlightInternal] public object Deserialize(XmlReader xmlReader, string encodingStyle) { Debug.Assert(null != _logicalType, "Reflection info not initialized before calling Serialize"); try { // Initialize the parser bool soap12; XmlSerializationReader serialReader = initXmlSerializationReader(xmlReader, encodingStyle, out soap12); xmlReader.MoveToContent(); // Get the correct deserializing type LogicalType deserializingType = resolveDeserializingType(xmlReader, serialReader, soap12); // Deserialize the element object deserializedObject; if (_isEncoded && (isNullableWithStructValue(deserializingType) || isComplexObjectValue(deserializingType))) { Type instType = deserializingType.IsNullableType ? deserializingType.NullableValueType.Type : deserializingType.Type; object fixupTarget = SerializationHelper.CreateInstance(instType); serialReader.DeserializeElement(deserializingType.Members, fixupTarget); serialReader.runFixups(); deserializedObject = fixupTarget; } else { ObjectFixup fixup = new ObjectFixup(deserializingType); serialReader.DeserializeElement(deserializingType.TypeAccessor, fixup); serialReader.runFixups(); deserializedObject = fixup.Object; } serialReader.CheckUnreferencedObjects(deserializedObject); return deserializedObject; } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; #if !FEATURE_LEGACYNETCF if (xmlReader is XmlTextReader) { XmlTextReader XmlTextReader = (XmlTextReader)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, XmlTextReader.LineNumber.ToString(NumberFormatInfo.InvariantInfo), XmlTextReader.LinePosition.ToString(NumberFormatInfo.InvariantInfo)), e); } else #endif { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } //***************************************************************** // Helpers //***************************************************************** /// <summary> /// Checks whether the prefix "xs" is defined as the Xsd uri. If it /// has been defined as something other then the Xsd uri and the /// xsd uri has not been mapped to a prefix then maps the Xsd uri to /// a unique prefix. /// </summary> /// <remarks> /// This is a work around specifically for the /// XmlSchema object. /// /// namespaces = The XmlSerializerNamespaces object that holds /// namespace mappings. /// serialWriter = The XmlSerializationWriter that will write out /// the serialized object. This object is used to /// create a unique prefix. /// </remarks> private void checkXsdNamespaceMapping(ref XmlSerializerNamespaces namespaces, XmlSerializationWriter serialWriter) { bool xsdRedefined = false, xsdUriPresent = false; const string XmlSchemaPrefix = "xs"; foreach (XmlQualifiedName qName in namespaces.ToArray()) { if (qName.Name == XmlSchemaPrefix && qName.Namespace != Soap.XsdUrl) xsdRedefined = true; if (qName.Namespace == Soap.XsdUrl) xsdUriPresent = true; } if (xsdRedefined && !xsdUriPresent) namespaces.Add(serialWriter.MakePrefix(), Soap.XsdUrl); } /// <summary> /// Returns true if the LogicalType represents a Nullable<T> type /// and the T is a primitive or enum. /// </summary> private bool isNullableWithStructValue(LogicalType type) { return type.IsNullableType && !SerializationHelper.IsSerializationPrimitive(type.NullableValueType.Type) && !type.NullableValueType.Type.GetTypeInfo().IsEnum; } /// <summary> /// Returns true if the LogicalType represents a complex type /// (struct or reference type). /// </summary> /// <remarks> /// Specifically a type that is not Nullable<T>, not a logical array, /// not a primitive, not an enum, and not a QName. /// </remarks> private bool isComplexObjectValue(LogicalType type) { if (!type.IsNullableType && !SerializationHelper.isLogicalArray(type) && !SerializationHelper.IsSerializationPrimitive(type.Type) && !type.Type.GetTypeInfo().IsEnum && type.CustomSerializer != CustomSerializerType.QName && !SerializationHelper.isBuiltInBinary(type)) return true; return false; } private bool useDefaultNamespaces(LogicalType type) { return (!type.IsNullableType || isNullableWithStructValue(type)) && // Nullable<T> with a struct (!typeof(IXmlSerializable).IsAssignableFrom(type.Type)); // Not an IXmlSerializable } /// <summary> /// Gets the logical type to deserialize. /// </summary> /// <remarks> /// This is done by checking the type attributes on the current start element. /// </remarks> /// <exception cref="InvalidOperationException">Thrown if the type attributes are not present.</exception> private LogicalType resolveDeserializingType(XmlReader reader, XmlSerializationReader serialReader, bool soap12) { if (true /* AppDomain.CompatVersion >= AppDomain.Orcas */) { LogicalType type = serialReader.deriveTypeFromTypeAttribute(reader, null); if (type != null && _logicalType.Type.IsAssignableFrom(type.Type)) { return type; } Accessor accessor = _isEncoded ? _logicalType.TypeAccessor : _logicalType.RootAccessor; if (startElementMatchesAccessor(reader, accessor, soap12)) { return _logicalType; } throw serialReader.CreateUnknownNodeException(); } else { /* Rogue or earlier */ LogicalType type = serialReader.deriveTypeFromTypeAttribute(reader, null); if (type != null) { return type; } if (startElementMatchesAccessor(reader, _logicalType.TypeAccessor, soap12)) { return _logicalType; } type = _reflector.FindType(new XmlQualifiedName(reader.Name, reader.NamespaceURI), _isEncoded); if (type != null) { return type; } return _logicalType; } } #if !FEATURE_LEGACYNETCF /// <summary> /// This method initializes the XmlTextWriter that will be used to /// serialize the object. /// </summary> /// <remarks> /// The SoapMessageFormatter uses an XmlTextWriter and not the /// abstract XmlWriter, so specialized XmlWriters cannot be used. /// Only XmlTextWriters and their children can be used. /// </remarks> void initWriter(XmlWriter xmlWriter) { if (typeof(XmlTextWriter).IsAssignableFrom(xmlWriter.GetType())) { XmlTextWriter writer = xmlWriter as XmlTextWriter; writer.Formatting = Formatting.Indented; writer.Indentation = 2; } } /// <summary> /// This method initializes the XmlTextReader that will be used to /// deserialize the object. /// </summary> void initReader(XmlReader xmlReader) { if (typeof(XmlTextReader).IsAssignableFrom(xmlReader.GetType())) { XmlTextReader reader = xmlReader as XmlTextReader; reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.Normalization = true; } } #endif /// <summary> /// Gets the reflection data (logical type) of a given CLR type. /// </summary> /// <remarks> /// The type is reflected over if it has not been previously, /// provided reflection hasn't been disabled. /// </remarks> private LogicalType findTypeByType(Type type, string defaultNamespace) { System.Diagnostics.Debug.Assert(null != _reflector, "The XmlSerializationReflector has not been initialized."); bool dontCheckIntrinsics = false; if (_isEncoded) { if (_reflector.SoapAttributeOverrides != null && _reflector.SoapAttributeOverrides[type] != null) { dontCheckIntrinsics = _reflector.SoapAttributeOverrides[type].SoapType != null; } } else { if (_reflector.XmlAttributeOverrides != null && _reflector.XmlAttributeOverrides[type] != null) { dontCheckIntrinsics = _reflector.XmlAttributeOverrides[type].XmlRoot != null || _reflector.XmlAttributeOverrides[type].XmlType != null; } } return _reflector.FindType(type, _isEncoded, defaultNamespace, dontCheckIntrinsics ? TypeOrigin.User : TypeOrigin.All); } /// <summary> /// Initializes the XmlSerializationWrter used to serialize the object. /// </summary> private XmlSerializationWriter initXmlSerializationWriter(XmlWriter xmlWriter, string encodingStyle) { System.Diagnostics.Debug.Assert(null != _reflector, "The XmlSerializationReflector has not been initialized."); if (!_isEncoded && encodingStyle != null) throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); bool soap12 = false; verifyEncodingStyle(encodingStyle, out soap12); XmlSerializationWriter serialWriter = new XmlSerializationWriter(xmlWriter, _reflector, soap12); serialWriter.Encoded = _isEncoded; return serialWriter; } /// <summary> /// Initializes the XmlSerializationReader used to deserialize the /// object. /// </summary> private XmlSerializationReader initXmlSerializationReader(XmlReader reader, string encodingStyle, out bool soap12) { System.Diagnostics.Debug.Assert(null != _reflector, "The XmlSerializationReflector has not been initialized."); if (!_isEncoded && encodingStyle != null) throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); verifyEncodingStyle(encodingStyle, out soap12); XmlSerializationReader xmlSerializationReader = new XmlSerializationReader(reader, _events, _reflector, soap12, _isEncoded); return xmlSerializationReader; } /// <summary> /// Ensures that the encodingStyle string is either Soap.Encoding or /// Soap12.Encoding. The soap12 parameter is set to true if the /// encodingStyle string equals Soap12.Encoding. /// </summary> /// <exception cref="InvalidOperationException">Thrown when an encoding style other than SOAP and SOAP 1.2 is specified.</exception> private void verifyEncodingStyle(string encodingStyle, out bool soap12) { if (encodingStyle != null && encodingStyle != Soap.Encoding && encodingStyle != Soap12.Encoding) throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncoding3, encodingStyle, Soap.Encoding, Soap12.Encoding)); soap12 = (encodingStyle == Soap12.Encoding); } private static XmlSerializerNamespaces defaultNamespace { get { if (s_DEFAULT_NAMESPACES == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.Add(Soap.Xsd, Soap.XsdUrl); nss.Add(Soap.Xsi, Soap.XsiUrl); if (s_DEFAULT_NAMESPACES == null) { s_DEFAULT_NAMESPACES = nss; } } return s_DEFAULT_NAMESPACES; } } #if !FEATURE_LEGACYNETCF public event XmlNodeEventHandler UnknownNode { [System.Security.FrameworkVisibilityCompactFrameworkInternal] add { events.onUnknownNode += value; } [System.Security.FrameworkVisibilityCompactFrameworkInternal] remove { events.onUnknownNode -= value; } } public event XmlAttributeEventHandler UnknownAttribute { [System.Security.FrameworkVisibilityCompactFrameworkInternal] add { events.onUnknownAttribute += value; } [System.Security.FrameworkVisibilityCompactFrameworkInternal] remove { events.onUnknownAttribute -= value; } } public event XmlElementEventHandler UnknownElement { [System.Security.FrameworkVisibilityCompactFrameworkInternal] add { events.onUnknownElement += value; } [System.Security.FrameworkVisibilityCompactFrameworkInternal] remove { events.onUnknownElement -= value; } } public event UnreferencedObjectEventHandler UnreferencedObject { [System.Security.FrameworkVisibilityCompactFrameworkInternal] add { events.onUnreferencedObject += value; } [System.Security.FrameworkVisibilityCompactFrameworkInternal] remove { events.onUnreferencedObject -= value; } } #endif [System.Security.FrameworkVisibilitySilverlightInternal] public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { throw new NotSupportedException(); } public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { throw new NotSupportedException(); } public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { throw new NotSupportedException(); } } }
Java
UTF-8
713
3.59375
4
[]
no_license
public class Animal{ private String nombre; private String lugarOrigen; private String color; public Animal(){} public Animal(String nombre, String lugarOrigen, String color){ this.nombre = nombre; this.lugarOrigen = lugarOrigen; this.color = color; } public void hacerSonido(String sonido){ System.out.println("Estoy haciendo un sonido"+sonido); } public void comer(){ System.out.println("Estoy comiendo"); } public void setNombre(String nombre){ this.nombre = nombre; } public String getNombre(){ return nombre; } @Override public String toString(){ return "Animal{nombre = "+nombre+" lugarOrigen = "+lugarOrigen+" color = "+color+"}"; } }
TypeScript
UTF-8
854
2.765625
3
[ "WTFPL" ]
permissive
import mongoose from "mongoose"; // User typings export type UserDocument = mongoose.Document & { first_name: string, last_name: string, email: string, sex: number, city: { id: number, title: string, } country: { id: number, title: string, } photo_100: string, photo_200: string, role: string, }; // User Collection const userSchema = new mongoose.Schema({ first_name: String, last_name: String, email: { type: String, unique: true }, sex: Number, city: { id: Number, title: String, }, country: { id: Number, title: String, }, photo_100: String, photo_200: String, role: String, }, { timestamps: true }); export const User = mongoose.model<UserDocument>("User", userSchema);
Markdown
UTF-8
1,072
2.875
3
[ "MIT" ]
permissive
### Project Overview **Problem Statement** Dream Housing Finance Inc. specializes in home loans across different market segments - rural, urban and semi-urban. Their loan eligibility process is based on customer details provided while filling an online application form. To create a targeted marketing campaign for different segments, they have asked for a comprehensive analysis of the data collected so far. The dataset has details of 614 customers with the following 13 features. - Loan_ID - Gender - Married - Dependents - Education - Self_Employed - Applicant_Income - Coapplicant_Income - Loan_Amount - Loan_Amount_Term - Credit_History - Property_Area - Loan_Status This project involves data analysis using Pandas. ### Learnings from the project After completing this project, I have build better understanding on working with basic and advanced operations of pandas. In this project I have applied following concepts. - Dataframe slicing - Dataframe aggregation - Pivot table operations - Dataframe Grouping - Merging - and other Pandas operations
Markdown
UTF-8
959
3.3125
3
[]
no_license
## 백준 14670 - [병약한 영정](https://www.acmicpc.net/problem/14670) ### 풀이법 1. 배열을 이용하여 약과 증상을 표시. ```JAVA int[] drug = new int[101]; Arrays.fill(drug, -1); for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); int effect = Integer.parseInt(st.nextToken()); int name = Integer.parseInt(st.nextToken()); drug[effect] = name; } int r = Integer.parseInt(br.readLine()); effects: for (int i = 0; i < r; i++) { StringBuilder sb = new StringBuilder(); st = new StringTokenizer(br.readLine()); int l = Integer.parseInt(st.nextToken()); for (int j = 0; j < l; j++) { int effect = Integer.parseInt(st.nextToken()); if (drug[effect] == -1) { System.out.println("YOU DIED"); continue effects; } else { sb.append(drug[effect]); sb.append(" "); } } System.out.println(sb.toString()); } ```
C++
WINDOWS-1250
2,007
2.765625
3
[]
no_license
#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #define __CL_ENABLE_EXCEPTIONS #include <CL\cl.hpp> #include "defines.hpp" #include "CamShift.hpp" using namespace cv; using namespace std; int main() { try { cvNamedWindow("main",CV_WINDOW_NORMAL); //0 is the id of video device.0 if you have only one camera. VideoCapture stream(0); //check if video device has been initialised if (!stream.isOpened()) { cout << "Cannot open camera."; cvDestroyAllWindows(); return EXIT_SUCCESS; } //TODO: przeniesienie caego sterowania CamShiftem do oddzielnej klasy/namepspace, moe do samego CamShift // eby tylko da camshitf.start() i dziaa. CamShift camshift; Mat cameraFrame; stream >> cameraFrame; std::cout << cameraFrame.size() << std::endl; int key; while((key = cvWaitKey(33)) != 27) { while((key = cvWaitKey(33)) != 32) { stream >> cameraFrame; camshift.drawTrackRect(cameraFrame); imshow("main", cameraFrame); if(key == 27) { cvDestroyAllWindows(); return EXIT_SUCCESS; } } std::cout << "Tracking started" << std::endl; camshift.startTracking(cameraFrame); while((key = cvWaitKey(33)) != 32) { stream >> cameraFrame; camshift.process(cameraFrame); imshow("main", cameraFrame); if(key == 27) { cvDestroyAllWindows(); return EXIT_SUCCESS; } } std::cout << "Tracking stopped" << std::endl; camshift.stopTracking(); } cvDestroyAllWindows(); return EXIT_SUCCESS; } catch (cl::Error &e) { std::cerr << "OpenCL error: " << e.what() << ".\n"; } catch (cv::Exception &e) { std::cerr << "OpenCV exception: " << e.what() << ".\n"; } catch (std::exception &e) { std::cerr << "STD exception: "<< e.what() << ".\n"; } catch (...) { std::cerr << "Unhandled exception of unknown type reached the top of main.\n"; } getchar(); return EXIT_FAILURE; }
Java
UTF-8
933
3.546875
4
[]
no_license
import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while(true) { String line = reader.readLine(); if(line.trim().equals("")) { continue; //line = reader.readLine(); } String[] part = line.split(" "); String s = part[0].trim().toLowerCase(); String t = part[1].trim().toLowerCase(); if(Main.isSubSequence(s, t)) { System.out.println("Yes"); } else { System.out.println("No"); } } //reader.close(); } public static boolean isSubSequence(String s, String t) { int i = 0; int j = 0; for(i = 0, j = 0; i < t.length() && j < s.length(); i++) { if(s.charAt(j) == t.charAt(i)) { j++; } } if(j == s.length()) { return true; } return false; } }
Markdown
UTF-8
21,232
2.765625
3
[ "MIT" ]
permissive
# Setting Up a Local Mirror for Composer Packages With Satis by Patkos Csaba 28 Jan Installing all your PHP libraries with Composer is a great way to save time. But larger projects automatically tested and run at each commit to your software version control (SVC) system will take a long time to install all the required packages from the Internet. You want to run your tests as soon as possible through your continuous integration (CI) system so that you have fast feedback and quick reactions on failure. In this tutorial we will set up a local mirror to proxy all your packages required in your project's composer.json file. This will make our CI work much faster, install the packages over the local network or even hosted on the same machine, and make sure we have the specific versions of the packages always available. ### What Is Satis? Satis is the name of the application we will use to mirror the various repositories for our project. It sits as a proxy between the Internet and your composer. Our solution will create a local mirror of a few packages and instruct our composer to use it instead of the sources found on the Internet. Here is an image that says more than a thousand words. Architecture Our project will use composer as usual. It will be configured to use the local Satis server as the primary source. If a package is found there, it will be installed from there. If not, we will let composer use the default packagist.org to retrieve the package. ### Getting Satis Satis is available through composer, so installing it is very simple. In the attached source code archive, you will find Satis installed in the Sources/Satis folder. First we will install composer itself. ``` $ curl -sS https://getcomposer.org/installer | php #!/usr/bin/env php All settings correct for using Composer Downloading... Composer successfully installed to: /home/csaba/Personal/Programming/NetTuts/Setting up a local mirror for Composer packages with Satis/Sources/Satis/composer.phar Use it: php composer.phar ``` Then we will install Satis. ``` $ php composer.phar create-project composer/satis --stability=dev --keep-vcs Installing composer/satis (dev-master eddb78d52e8f7ea772436f2320d6625e18d5daf5) - Installing composer/satis (dev-master master) Cloning master Created project in /home/csaba/Personal/Programming/NetTuts/Setting up a local mirror for Composer packages with Satis/Sources/Satis/satis Loading composer repositories with package information Installing dependencies (including require-dev) from lock file - Installing symfony/process (dev-master 27b0fc6) Cloning 27b0fc645a557b2fc7bc7735cfb05505de9351be - Installing symfony/finder (v2.4.0-BETA1) Downloading: 100% - Installing symfony/console (dev-master f44cc6f) Cloning f44cc6fabdaa853335d7f54f1b86c99622db518a - Installing seld/jsonlint (1.1.1) Downloading: 100% - Installing justinrainbow/json-schema (1.1.0) Downloading: 100% - Installing composer/composer (dev-master f8be812) Cloning f8be812a496886c84918d6dd1b50db5c16da3cc3 - Installing twig/twig (v1.14.1) Downloading: 100% symfony/console suggests installing symfony/event-dispatcher () Generating autoload files ``` ### Configuring Satis Satis is configured by a JSON file very similar to composer. You can use whatever name you want for your file and specify it for usage later. We will use "mirrored-packages.conf". ``` { "name": "NetTuts Composer Mirror", "homepage": "http://localhost:4680", "repositories": [ { "type": "vcs", "url": "https://github.com/SynetoNet/monolog" }, { "type": "composer", "url": "https://packagist.org" } ], "require": { "monolog/monolog": "syneto-dev", "mockery/mockery": "*", "phpunit/phpunit": "*" }, "require-dependencies": true } ``` Let's analyze this configuration file. - `name` - represents a string that will be shown on the web interface of our mirror. - `homepage` - is the web address where our packages will be kept. This does not tell our web server to use that address and port, it is rather just information of a working configuration. We will set up the access to it on that addres and port later. - `repositories` - a list of repositories ordered by preference. In our example, the first repository is a Github fork of the monolog logging libraries. It has some modifications and we want to use that specific fork when installing monolog. The type of this repository is "vcs". The second repository is of type "composer". Its URL is the default packagist.org site. - `require` - lists the packages we want to mirror. It can represent a specific package with a specific version or branch, or any version for that matter. It uses the same syntax as your "require" or "require-dev" in your `composer.json`. - `require-dependencies` - is the final option in our example. It will tell Satis to mirror not only the packages we specified in the "require" section but also all their dependencies. To quickly try out our settings we first need to tell Satis to create the mirrors. Run this command in the folder where you installed Satis. ``` $ php ./satis/bin/satis build ./mirrored-packages.conf ./packages-mirror Scanning packages Writing packages.json Writing web view ``` While the process is taking place, you will see how Satis mirrors each found version of the required packages. Be patient it may take a while to build all those packages. Satis requires that `date.timezone` to be specified in the `php.ini` file, so make sure it is and set to your local timezone. Otherwise an error will appear. ``` [Twig_Error_Runtime] An exception has been thrown during the rendering of a template ("date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set) function. ``` Then we can run a PHP server instance in our console pointing to the recently created repository. PHP 5.4 or newer is required. ``` $ php -S localhost:4680 -t ./packages-mirror/ PHP 5.4.22-pl0-gentoo Development Server started at Sun Dec 8 14:47:48 2013 Listening on http://localhost:4680 Document root is /home/csaba/Personal/Programming/NetTuts/Setting up a local mirror for Composer packages with Satis/Sources/Satis/packages-mirror Press Ctrl-C to quit. [Sun Dec 8 14:48:09 2013] 127.0.0.1:56999 [200]: / [Sun Dec 8 14:48:09 2013] 127.0.0.1:57000 [404]: /favicon.ico - No such file or directory ``` And we can now browse our mirrored packages and even search for specific ones by pointing our web browser to `http://localhost:4680`: MirrorWebpage ### Let's Host It on Apache If you have a running Apache at hand, creating a virtual host for Satis will be quite simple. ``` Listen 4680 <Directory "/path/to/your/packages-mirror"> Options -Indexes FollowSymLinks AllowOverride all Order allow,deny Allow from all </Directory> <VirtualHost *:4680> DocumentRoot "/path/to/your/packages-mirror" ServerName 127.0.0.1:4680 ServerAdmin admin@example.com ErrorLog syslog:user </VirtualHost> ``` We just use a `.conf` file like this, put in Apache's `conf.d` folder, usually `/etc/apache2/conf.d`. It creates a virtual host on the 4680 port and points it to our folder. Of course you can use whatever port you want. ### Updating Our Mirrors Satis can not automatically update the mirrors unless we tell it. So the easiest way, on any UNIX like system, is to just add a cron job to your system. That would be very easy, and just a simple script to execute our update command. ``` #!/bin/bash php /full/path/to/satis/bin/satis build \ /full/path/to/mirrored-packages.conf \ /full/path/to/packages-mirror 修改/full/path/to为自己的绝对路径 #!/bin/bash php /Users/scsidisk/work/ccc/satis/bin/satis build \ /Users/scsidisk/work/ccc/mirrored-packages.conf \ /Users/scsidisk/work/ccc/packages-mirror ``` The drawback of this solution is that it is static. We have to manually update the `mirrored-packages.conf` every time we add another package to our project's `composer.json`. If you are part of a team in a company with a big project and a continuous integration server, you can't rely on people remembering to add the packages on the server. They may not even have permissions to access the CI infrastructure. ### Dynamically Updating Satis Configuration It's time for a PHP TDD exercise. If you just want your code ready and running, check out the source code attached to this tutorial. ``` require_once __DIR__ . '/../../../../vendor/autoload.php'; class SatisUpdaterTest extends PHPUnit_Framework_TestCase { function testBehavior() { $this->assertTrue(true); } } ``` As usual we start with a degenerative test, just enough to make sure we have a working testing framework. You may notice that I have quite a strange looking require_once line, this is because I want to avoid having to reinstall PHPUnit and Mockery for each small project. So I have them in a vendor folder in my NetTuts' root. You should just install them with composer and drop the require_once line altogether. ``` class SatisUpdaterTest extends PHPUnit_Framework_TestCase { function testDefaultConfigFile() { $expected = '{ "name": "NetTuts Composer Mirror", "homepage": "http://localhost:4680", "repositories": [ { "type": "vcs", "url": "https://github.com/SynetoNet/monolog" }, { "type": "composer", "url": "https://packagist.org" } ], "require": { }, "require-dependencies": true }'; $actual = $this->parseComposerConf(''); $this->assertEquals($expected, $actual); } } ``` That looks about right. All the fields except "require" are static. We need to generate only the packages. The repositories are pointing to our private git clones and to packagist as needed. Managing those is more of a sysadmin job than a software developer's. Of course this fails with: ``` PHP Fatal error: Call to undefined method SatisUpdaterTest::parseComposerConf() ``` Fixing that is easy. ``` private function parseComposerConf($string) { } ``` I just added an empty method with the required name, as private, to our test class. Cool, but now we have another error. ``` PHPUnit_Framework_ExpectationFailedException : Failed asserting that null matches expected '{ ... }' ``` So, null does not match our string containing all that default configuration. ``` private function parseComposerConf($string) { return '{ "name": "NetTuts Composer Mirror", "homepage": "http://localhost:4680", "repositories": [ { "type": "vcs", "url": "https://github.com/SynetoNet/monolog" }, { "type": "composer", "url": "https://packagist.org" } ], "require": { }, "require-dependencies": true }'; } ``` OK, that works. All tests are passing. ``` PHPUnit 3.7.28 by Sebastian Bergmann. Time: 15 ms, Memory: 2.50Mb OK (1 test, 1 assertion) ``` But we introduced a horrible duplication. All that static text in two places, written character by character in two different places. Let's fix it: ``` class SatisUpdaterTest extends PHPUnit_Framework_TestCase { static $DEFAULT_CONFIG = '{ "name": "NetTuts Composer Mirror", "homepage": "http://localhost:4680", "repositories": [ { "type": "vcs", "url": "https://github.com/SynetoNet/monolog" }, { "type": "composer", "url": "https://packagist.org" } ], "require": { }, "require-dependencies": true }'; function testDefaultConfigFile() { $expected = self::$DEFAULT_CONFIG; $actual = $this->parseComposerConf(''); $this->assertEquals($expected, $actual); } private function parseComposerConf($string) { return self::$DEFAULT_CONFIG; } } ``` Ahhh! That's better. ``` function testEmptyRequiredPackagesInComposerJsonWillProduceDefaultConfiguration() { $expected = self::$DEFAULT_CONFIG; $actual = $this->parseComposerConf('{"require": {}}'); $this->assertEquals($expected, $actual); } ``` Well. That also passes. But it also highlights some duplication and useless assignment. ``` function testDefaultConfigFile() { $actual = $this->parseComposerConf(''); $this->assertEquals(self::$DEFAULT_CONFIG, $actual); } function testEmptyRequiredPackagesInComposerJsonWillProduceDefaultConfiguration() { $actual = $this->parseComposerConf('{"require": {}}'); $this->assertEquals(self::$DEFAULT_CONFIG, $actual); } ``` We inlined the `$expected` variable. `$actual` could also be inlined, but I like it better this way. It keeps the focus on what is tested. Now we have another problem. The next test I want to write would look like this: ``` function testARequiredPackageInComposerWillBeInSatisAlso() { $actual = $this->parseComposerConf( '{"require": { "Mockery/Mockery": ">=0.7.2" }}'); $this->assertContains('"Mockery/Mockery": ">=0.7.2"', $actual); } ``` But after writing the simple implementation, we will notice it requires json_decode() and json_encode(). And of course these functions reformat our string and matching strings will be difficult at best. We have to take a step back. ``` function testDefaultConfigFile() { $actual = $this->parseComposerConf(''); $this->assertJsonStringEqualsJsonString($this->jsonRecode(self::$DEFAULT_CONFIG), $actual); } function testEmptyRequiredPackagesInComposerJsonWillProduceDefaultConfiguration() { $actual = $this->parseComposerConf('{"require": {}}'); $this->assertJsonStringEqualsJsonString($this->jsonRecode(self::$DEFAULT_CONFIG), $actual); } private function parseComposerConf($jsonConfig) { return $this->jsonRecode(self::$DEFAULT_CONFIG); } private function jsonRecode($json) { return json_encode(json_decode($json, true)); } ``` We changed our assertion method to compare JSON strings and we also recoded our $actual variable. ParseComposerConf() was also modified to use this method. You will see in a moment how it helps us. Our next test becomes more JSON specific. ``` function testARequiredPackageInComposerWillBeInSatisAlso() { $actual = $this->parseComposerConf( '{"require": { "Mockery/Mockery": ">=0.7.2" }}'); $this->assertEquals('>=0.7.2', json_decode($actual, true)['require']['Mockery/Mockery']); } ``` And making this test pass, along with the rest of the tests, is quite easy, again. ``` private function parseComposerConf($jsonConfig) { $addedConfig = json_decode($jsonConfig, true); $config = json_decode(self::$DEFAULT_CONFIG, true); if (isset($addedConfig['require'])) { $config['require'] = $addedConfig['require']; } return json_encode($config); } ``` We take the input JSON string, decode it, and if it contains a "`require`" field we use that in our Satis configuration file instead. But we may want to mirror all versions of a package, not just the last one. So maybe we want to modify our test to check that the version is "*" in Satis, regardless of what exact version is in `composer.json`. ``` function testARequiredPackageInComposerWillBeInSatisAlso() { $actual = $this->parseComposerConf( '{"require": { "Mockery/Mockery": ">=0.7.2" }}'); $this->assertEquals('*', json_decode($actual, true)['require']['Mockery/Mockery']); } ``` That obviously fails with a cool message: ``` PHPUnit_Framework_ExpectationFailedException : Failed asserting that two strings are equal. Expected :* Actual :>=0.7.2 ``` Now, we need to actually edit our JSON before re-encoding it. ``` private function parseComposerConf($jsonConfig) { $addedConfig = json_decode($jsonConfig, true); $config = json_decode(self::$DEFAULT_CONFIG, true); $config = $this->addNewRequires($addedConfig, $config); return json_encode($config); } private function toAllVersions($config) { foreach ($config['require'] as $package => $version) { $config['require'][$package] = '*'; } return $config; } private function addNewRequires($addedConfig, $config) { if (isset($addedConfig['require'])) { $config['require'] = $addedConfig['require']; $config = $this->toAllVersions($config); } return $config; } ``` To make the test pass we have to iterate over each element of the required packages array and set their version to '*'. See method toAllVersion() for more details. And to speed up this tutorial a little bit, we also extracted some private methods in the same step. This way, parseComoserConf() becomes very descriptive and easy to understand. We could also inline $config into the arguments of addNewRequires(), but for aesthetic reasons I left it on two lines. But what about "`require-dev`" in `composer.json`? ``` function testARquiredDevPackageInComposerWillBeInSatisAlso() { $actual = $this->parseComposerConf( '{"require-dev": { "Mockery/Mockery": ">=0.7.2", "phpunit/phpunit": "3.7.28" }}'); $this->assertEquals('*', json_decode($actual, true)['require']['Mockery/Mockery']); $this->assertEquals('*', json_decode($actual, true)['require']['phpunit/phpunit']); } ``` That obviously fails. We can make it pass with just copy/pasting our if condition in addNewRequires(): ``` private function addNewRequires($addedConfig, $config) { if (isset($addedConfig['require'])) { $config['require'] = $addedConfig['require']; $config = $this->toAllVersions($config); } if (isset($addedConfig['require-dev'])) { $config['require'] = $addedConfig['require-dev']; $config = $this->toAllVersions($config); } return $config; } ``` Yep, that makes it pass, but those duplicated if statements are nasty looking. Let's deal with them. ``` private function addNewRequires($addedConfig, $config) { $config = $this->addRequire($addedConfig, 'require', $config); $config = $this->addRequire($addedConfig, 'require-dev', $config); return $config; } private function addRequire($addedConfig, $string, $config) { if (isset($addedConfig[$string])) { $config['require'] = $addedConfig[$string]; $config = $this->toAllVersions($config); } return $config; } ``` We can be happy again, tests are green and we refactored our code. I think only one test is left to be written. What if we have both "require" and "require-dev" sections in composer.json? ``` function testItCanParseComposerJsonWithBothSections() { $actual = $this->parseComposerConf( '{"require": { "Mockery/Mockery": ">=0.7.2" }, "require-dev": { "phpunit/phpunit": "3.7.28" }}'); $this->assertEquals('*', json_decode($actual, true)['require']['Mockery/Mockery']); $this->assertEquals('*', json_decode($actual, true)['require']['phpunit/phpunit']); } ``` That fails because the packages set by "require-dev" will overwrite those of "require" and we will have an error: ``` Undefined index: Mockery/Mockery ``` Just add a plus sign to merge the arrays, and we are done. ``` private function addRequire($addedConfig, $string, $config) { if (isset($addedConfig[$string])) { $config['require'] += $addedConfig[$string]; $config = $this->toAllVersions($config); } return $config; } ``` Tests are passing. Our logic is finished. All we left to do is to extract the methods into their own file and class. The final version of the tests and the SatisUpdater class can be found in the attached source code. We can now modify our cron script to load our parser and run it on our composer.json. This will be specific to your projects' particular folders. Here is an example you can adapt to your system. ``` #!/usr/local/bin/php <?php require_once __DIR__ . '/Configuration.php'; $outputDir = '/path/to/your/packages-mirror'; $composerJsonFile = '/path/to/your/projects/composer.json'; $satisConf = '/path/to/your/mirrored-packages.conf'; $satisUpdater = new SatisUpdater(); $conf = $satisUpdater->parseComposerConf(file_get_contents($composerJsonFile)); file_put_contents($satisConf, $conf); system(sprintf('/path/to/satis/bin/satis build %s %s', $satisConf, $outputDir), $retval); exit($retval); ``` ### Making Your Project Use the Mirror We talked about a lot of things in this article, but we did not mention how we will instruct our project to use the mirror instead of the Internet. You know, the default is packagist.org? Unless we do something like this: ``` "repositories": [ { "type": "composer", "url": "http://your-mirror-server:4680" } ], ``` That will make your mirror the first choise for composer. But adding just that into the composer.json of your project will not disable access to packagist.org. If a package can not be found on the local mirror, it will be downloaded from the Internet. If you wish to block this feature, you may also want to add the following line to the repositories section above: ``` "packagist": false ``` Final Thoughts That's it. Local mirror, with automatic adapting and updating packages. Your colleagues will never have to wait a long time while they or the CI server installs all the requirements of your projects. Have fun.
JavaScript
UTF-8
2,276
2.71875
3
[]
no_license
import Job from "../../models/job.js"; import JobService from "./job-service.js"; let _jobService = new JobService export default class JobController { constructor() { } showJobsButton() { _jobService.getJobs(this.showJobs) } showJobs() { console.log('about to show some Jobs') let jobs = _jobService.jobs let template = "" jobs.forEach(job => { template += ` <div class="col-sm-4 my-1 card"> <div class=""> <div class="card-body"> <h5 class="card-title">${job.jobTitle} - ${job.company} ${job.hours} Created In ${job.rate}</h5> <div class="card-text"> <p>${job.description}</p> <div> <i class="fa fa-fw fa-trash action muted" onclick="app.controllers.jobsController.destroyJob('${job._id}')"></i> </div> </div> </div> </div> </div> ` }) template += `<form onsubmit="app.controllers.jobsController.addJob(event)"> <div class="form-group"> <label for="jobTitle">Job Title</label> <input type="text" name="jobTitle" /> </div> <div class="form-group"> <label for="company">Company:</label> <input type="text" name="company"/> </div> <div class="form-group"> <label for="rate"> Rate:</label> <input type="number" name="rate"/> </div> <div class="form-group"> <label for="hours"> Hours:</label> <input type="number" name="hours"/> </div> <div class="form-group"> <label for="description">Description:</label> <textarea type="text" name="description"></textarea> </div> <button type="submit">Add Job Listing</button> </form>` document.getElementById('main-content').innerHTML = template } addJob(event) { event.preventDefault(); let form = event.target let formData = { company: form.company.value, jobTitle: form.jobTitle.value, hours: form.hours.value, rate: form.rate.value, description: form.description.value } _jobService.addJob(formData, this.showJobs) form.reset() } destroyJob(id) { _jobService.destroyJob(id, this.showJobs) } }
Java
UTF-8
121
1.914063
2
[]
no_license
package com.highcrit.ffacheckers.domain.communication.objects; public interface Event { String getEventName(); }
Go
UTF-8
942
2.96875
3
[]
no_license
package main /* * @lc app=leetcode.cn id=1406 lang=golang * * [1406] 石子游戏 III */ // @lc code=start func stoneGameIII(stoneValue []int) string { prefixSum := make([]int, len(stoneValue)) // aScore := 0 // bScore := 0 for i, v := range stoneValue { if i == 0 { prefixSum[i] = v } else { prefixSum[i] = prefixSum[i-1] + v } } //TODO return "" } func bestMove(arr []int) (int, int) { bestMove := 1 sum := 0 sum1 := arr[0] m := sum1 - maxSum(arr[1:]) sum = sum1 sum2 := arr[0] + arr[1] step2 := sum2 - maxSum(arr[2:]) if step2 > m { bestMove = 2 m = step2 sum = sum2 } sum3 := arr[0] + arr[1] + arr[2] step3 := sum3 - maxSum(arr[3:]) if step3 > m { bestMove = 3 m = step3 sum = sum3 } return bestMove, sum } func maxSum(arr []int) int { m := 0 s := 0 for i := 0; i < 3 && i < len(arr); i++ { s += arr[i] if s > m { m = s } } return m } // @lc code=end //[1,2,3,4,18]
Java
WINDOWS-1252
3,442
1.898438
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-other-permissive", "MIT", "CDDL-1.1", "LicenseRef-scancode-public-domain" ]
permissive
/* * Copyright IBM Corp. 2010 * * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0 * * 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 com.ibm.xsp.extlib.component.layout.bean; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import javax.faces.context.FacesContext; import com.ibm.commons.Platform; import com.ibm.commons.util.io.json.JsonParser; import com.ibm.xsp.extlib.component.layout.OneUIApplicationConfiguration; import com.ibm.xsp.extlib.component.layout.bean.config.OneUIJSONFactory; /** * OneUI Layout Bean */ public class OneUIApplicationBean implements ApplicationBean { public static final String DEFAULT_CONFIGURATION_FILE = "/WEB-INF/OneUIApplication.json"; // $NON-NLS-1$ private static final long serialVersionUID = 1L; private OneUIApplicationConfiguration configuration; public OneUIApplicationBean() { } ////////////////////////////////////////////////////////////////////////////// // Manage search ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Access the configuration ////////////////////////////////////////////////////////////////////////////// public OneUIApplicationConfiguration getConfiguration() { if(configuration==null) { synchronized (this) { if(configuration==null) { this.configuration = parseConfiguration(DEFAULT_CONFIGURATION_FILE); if(configuration==null) { configuration = createDefaultConfiguration(); } } } } return configuration; } protected OneUIApplicationConfiguration createDefaultConfiguration() { OneUIApplicationConfiguration conf = new OneUIApplicationConfiguration(); return conf; } public synchronized void setConfigurationFile(String path) { this.configuration = parseConfiguration(path); if(configuration==null) { configuration = createDefaultConfiguration(); } } protected static OneUIApplicationConfiguration parseConfiguration(String path) { FacesContext ctx = FacesContext.getCurrentInstance(); InputStream is = ctx.getExternalContext().getResourceAsStream(path); if(is!=null) { try { try { Reader reader = new InputStreamReader(is,"UTF-8"); // $NON-NLS-1$ OneUIJSONFactory factory = new OneUIJSONFactory(); return (OneUIApplicationConfiguration)JsonParser.fromJson(factory, reader); } finally { is.close(); } } catch(Exception ex) { Platform.getInstance().log(ex); } } return null; } }
Java
UTF-8
739
1.90625
2
[]
no_license
package com.airplane.db.service; import java.util.List; import com.airplane.db.dto.FlightDTO; import com.airplane.db.dto.PaymentDTO; import com.airplane.db.dto.TicketDTO; public interface TicketService { public List<TicketDTO> listAllCTickets(String email); public List<TicketDTO> listAllfCTickets(String email); public List<TicketDTO> listAllpCTickets(String email); public List<FlightDTO> listAllCFlights(String email); public List<FlightDTO> listAllfCFlights(String email); public List<FlightDTO> listAllpCFlights(String email); public FlightDTO buyTicket(FlightDTO flight, String email, int id, int bid); public List<FlightDTO> listAgent(int id); public List<Integer> getComissions(int id, int months); }
Java
UTF-8
244
1.546875
2
[]
no_license
package net.ajcloud.wansviewplusw.support.http.bean; import java.util.List; /** * Created by mamengchao on 2018/07/11. * Function: 报警列表 */ public class AlarmListBean { public List<AlarmBean> alarms; public String cts; }
Java
UTF-8
825
2.296875
2
[]
no_license
package ca.uqtr.dmi.inf1013.services.impl; import ca.uqtr.dmi.inf1013.model.EducationLevel; import ca.uqtr.dmi.inf1013.repos.EducationLevelRepo; import ca.uqtr.dmi.inf1013.services.EducationLevelService; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class EducationLevelServiceImpl implements EducationLevelService { private EducationLevelRepo educationLevelRepo; public EducationLevelServiceImpl(EducationLevelRepo educationLevelRepo){ this.educationLevelRepo = educationLevelRepo; } @Override public Iterable<EducationLevel> getEducationLevels() { return this.educationLevelRepo.findAll(); } @Override public Optional<String> getEducationLevelFromId(Long id) { return this.educationLevelRepo.getNameById(id); } }
Python
UTF-8
3,447
2.984375
3
[]
no_license
import re from PIL import Image class PhoneLinker: mobile_operator_codes = ( '700', '701', '702', '705', '707', '708', '712', '713', '717', '718', '721', '725', '726', '778', '727', '747', '750', '751', '760', '761', '762', '763', '764', '771', '775', '776', '777', ) regex_str = '|'.join(['({})']*len(mobile_operator_codes)).format(*mobile_operator_codes) regex = re.compile(r'(^|\s)(\+7|8( )?)({})( )?((\d\d\d\d\d\d\d)|(\d\d\d-\d\d-\d\d)|(\d\d\d-\d\d\d\d)|(\d\d\d \d\d \d\d)' r'|(\d\d\d \d\d\d\d))'.format(regex_str), re.I) def __init__(self, text): self.text = text def _find_phones(self) -> tuple: return tuple(self.regex.finditer(self.text)) def href_phones(self): i = 0 output = '' if self._find_phones(): for phone in self._find_phones(): if self.text[phone.start()] == " ": tel_num = self.text[(phone.start()+1):phone.end()] tel_num = self._extract_number(tel_num) output += ''.join((self.text[i:phone.start()+1], '<a href="tel:{}">'.format(tel_num), self.text[(phone.start()+1):phone.end()], '</a>')) else: tel_num = self.text[phone.start():phone.end()] tel_num = self._extract_number(tel_num) output += ''.join((self.text[i:phone.start()], '<a href="tel:{}">'.format(tel_num), self.text[phone.start():phone.end()], '</a>')) i = phone.end() highlighted_text = "".join([output, self.text[phone.end():]]) return highlighted_text return self.text @staticmethod def _extract_number(phone: str) -> str: res = '' for char in phone: if char.isdigit() or char == "+": res += char return res class ImageLinker: regex = re.compile('<img src="/media/django-summernote') _host_addr = 'http://0.0.0.0:2003' def __init__(self, text): self.text = text def link_images(self) -> str: i = 0 output = '' if self._find_images(): for image in self._find_images(): output += ''.join((self.text[i:image.start() + 10], str(self._host_addr), self.text[(image.start() + 10):image.end()])) i = image.end() highlighted_text = "".join([output, self.text[image.end():]]) return highlighted_text return self.text def _find_images(self) -> tuple: return tuple(self.regex.finditer(self.text)) class ThumbnailCreator: @classmethod def get_thumbnail(cls, image_location): print(image_location) image = Image.open('./backend/src/media/{}'.format(image_location)) thumbnail = image.resize([60, 60], Image.ANTIALIAS) image.close() return thumbnail if __name__ == '__main__': # text = '+7702 969-15-95 87759691595' # text = 'fdgf +77750 dfds' # a = PhoneLinker(text).href_phones() # a = PhoneLinker._extract_number('+7702 969-15-95') # print(a) a = '<p>fgghfhgf jhg jhg jhgjhghj&nbsp;&nbsp;<img src="/media/django-summernote/2018-10-27/9f91375d-e00f-4a15-b4f2-9252f5108e1b.png" ' \ 'style="width: 271px;"></p>' print(ImageLinker(a).link_images())
Markdown
UTF-8
5,479
3.03125
3
[]
no_license
% 金融工学 % % $$ \newcommand{\unit}[1]{[\mathrm{#1}]} $$ ## 債券とは 素朴な意味での債券とは,お金を貸したときに返済を約束する証書. しかし,現代の金融市場においては,それ以上の意味がある. - 債券を発効してお金を生み出す - 債券の発行者は,自分の信用をもとにお金を得ることができる - キャッシュフローを受ける権利 - 債券を買った人は債券に書かれている返済計画にのっとって,返済金を受け取ることができる - 買う側はこのキャッシュフロー(いついくら貰えるか)を額面と比較して判断する キャッシュフローをどう評価すればいいか? ## キャッシュフロー - 額面 $F$ - 利払い日 $t_i\unit{year}$ - $t_0=0$ - 満期 $t_m$ - クーポンレート $K\unit{\%/year}$ - クーポンレートが変動するものもある - $L_{i-1}$ (前回の利払い日の金利を参照する) - 長年,金利の基準であった LIBOR は 2021 年 に廃止されるよ - クーポン $C_i=KF(t_i-t_{i-1})$ ### 複利 最終的な価値 $\sum C_i + F$ ではない - 利息で買い増すことができる - ターン数(利払い日の数)だけ,売る or 買う の選択ができる.みんなが同じ評価方法を持っているとすれば,売り買いしても意味がない(自分の評価値と他人の評価値が同じなので差額が無い). 毎回利息で買い増すと,$\sum C_i + F$ 以上の返済が得られる.利払い日の間隔によって最終的な価値が変わってくる! - クーポンレートだけで単純に比較できない - 利払い日が多い方が転化回数(ターン数)が多い=自由度が高い 年 $m$ 回再投資可能で利回り(年率)$R$ な債券に投資すると一年で $$ \left(1+\frac{R}{m}\right)^m $$ 倍になる. 連続的に取引できる場合(数学科に笑われそう) $$ \lim_{m\rightarrow\infty}\left(1+\frac{R}{m}\right)^m=e^R $$ 倍になる. つまり,今の 1 円は 1 年後に$e^R$円になるし,1 年後の 1 円は今の$e^{-R}$ 円. いつの時点での金額を言っているのか気にしてね. 購入時点での証券の価値は $$ \sum C_i \left(1+\frac{R}{m}\right)^{-i} + F \left(1+\frac{R}{m}\right)^{-n} $$ ※ 将来もらえる金額を,今の金額に変換して足し合わせてる ### NPV(正味現在価値)法 $$ NPV = \sum_{i=1}^N \frac{CF(i)}{(1+R)^i} + CF(0) = \sum_{i=0}^N \frac{CF(i)}{(1+R)^i} $$ ※ $CF(0)=-F$ に注意 $NPV>0$ となる投資は利益をもたらす R ($CF(0)$を払うための資金調達コスト)をどう設定するか - 加重平均資本コスト(WACC) - バランスシート ### IRR(内部収益率)法 $NPV=0$ となる $R$ を Internal Rate of Return という.$R$ が資金調達コストより高ければ投資する. ## 金利の期間構造(Term Structure of Interest Rates) 残存期間と利回りの関係 ### イールドカーブ ### ゼロレート ### フォワードレート ## リスク・リターン ### 投資収益率 価格 $P_t$ 配当 $D_t$ に対して,ある期間の算術収益率は $$ R_{t+1} = \frac{P_{t+1}-P_t+D_{t+1}}{P_t} $$ 対数収益率は $$ R^{log}_{t+1}=\log (P_{t+1}+D_{t+1}) - \log P_t \simeq R_{t+1} (R_{t+1} << 1) $$ 収益率は確率変数っぽい 収益率の期待値 → リターン 収益率の標準偏差 → リスク ### 期待効用原理 - 富 $W$ - 効用 $u$ - 得られる満足度 - 富の関数 $u(W)$ - 富が多いほど効用は高い $u'(W)>0$ $E[u(W)]$ を最大化するように行動するだろう 効用関数の形状がリスクへの態度を表す ### ## 現代ポートフォリオ理論 ## デリバティブ 金融商品から「派生」した金融商品(ある金融商品をもとにキャッシュフローが決まる)(現物取引 → 先物取引みたいな) - 先渡契約 - 「(原資産)を(満期)に(先渡価格)で売買する」契約 - 買う側をロング・ポジション,売る側をショート・ポジションという - 契約時にキャッシュが発生しない → 契約は現時点ではゼロとなるように先渡価格を設定する - 先物契約 - 満期で現物の受け渡しをしない - 差金決済(決済時点の購入価格と売却価格の差額をやりとり) - 毎日,値洗いし,差金決済を行う - スワップ - 将来のキャッシュフロー列を交換する - リスクを減らす - 金利スワップ - A は B から固定金利で借り, B は A から変動金利で借りる. - A は B に固定金利で利息を払い,B は A に変動金利で利息を払う. - A が C から変動金利で借りていた場合,B を介して固定金利に変換している. - 元本の交換をしないが,利息の計算に必要なので,想定元本という. - 固定金利のほうがリスクと銀行は思ってる - 通貨スワップ - 円 LIBOR とドル固定金利の交換 - 元本を交換する - しない場合はクーポン・スワップという - ベーシス・スワップ - LIBOR と TIBOR の変換 - 円 LIBOR とドル LIBOR の変換 - 通貨が異なると元本を交換することが多い
Java
UTF-8
2,781
2.578125
3
[]
no_license
package com.javafx.windows; import java.io.File; import java.util.logging.Level; import java.util.logging.Logger; import example_TextReading.ExtractDocxDocument; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.layout.AnchorPane; import javafx.stage.FileChooser; import javafx.stage.Stage; public class PleaseProvideController { Stage stage; ExtractDocxDocument extractor; String path = null, content = null; @FXML private TextArea textArea; @FXML private AnchorPane root; @FXML private Button button; @FXML void clickChooseFileButton(ActionEvent event) throws Exception { FileChooser fileChooser = new FileChooser(); File file = fileChooser.showOpenDialog(null); if (file != null) { path = file.getAbsolutePath(); if (ControlPath(path)) { content = readFile(path); textArea.setText(content); } } if (path != null) { if(ControlPath(path)) { FXMLLoader Loader = new FXMLLoader(); Loader.setLocation(getClass().getResource("ChoosesSenario.fxml")); try { Loader.load(); } catch (Exception e) { Logger.getLogger(PleaseProvideController.class.getName()).log(Level.SEVERE, null, e); } ChooseScenerioController fxmlController = Loader.getController(); fxmlController.getTextFromTextArea(textArea.getText()); Parent p = Loader.getRoot(); Stage stage = new Stage(); Scene scene = new Scene(p); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); stage.setTitle("Show References Screen"); stage.setScene(scene); stage.showAndWait(); }else { FXMLLoader Loader2 = new FXMLLoader(); Loader2.setLocation(getClass().getResource("AlertBox.fxml")); try { Loader2.load(); } catch (Exception e) { Logger.getLogger(AlertBoxController.class.getName()).log(Level.SEVERE, null, e); } AlertBoxController alert = Loader2.getController(); alert.setWarningMessage("Your document is not word file.Please choose word file!"); Parent p2 = Loader2.getRoot(); Stage stage2 = new Stage(); Scene scene2 = new Scene(p2); scene2.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); stage2.setTitle("WARNING"); stage2.setScene(scene2); stage2.showAndWait(); } } } public String readFile(String path) { extractor = new ExtractDocxDocument(); String text = extractor.readDocxDocument(path); return text; } public boolean ControlPath(String path) { if (path.endsWith(".docx")) { return true; } else { return false; } } }
Python
UTF-8
1,985
2.78125
3
[ "BSD-2-Clause-Views" ]
permissive
from bbcode import * import re class Center(BlockReplaceTagNode): """ Centers text. Usage: [code lang=bbdocs linenos=0][center]Text[/center][/code] """ verbose_name = 'Center Text' open_pattern = re.compile(patterns.no_argument % 'center') close_pattern = re.compile(patterns.closing % 'center') def parse(self, as_text=False): if as_text: return self.parse_inner(as_text) return u'<p class="ta-center">%s</p>' % self.parse_inner() class Left(BlockReplaceTagNode): """ Aligns text on the left. Usage: [code lang=bbdocs linenos=0][left]Text[/left][/code] """ verbose_name = 'Align Text Left' open_pattern = re.compile(patterns.no_argument % 'left') close_pattern = re.compile(patterns.closing % 'left') def parse(self, as_text=False): if as_text: return self.parse_inner(as_text) return u'<p class="ta-left">%s</p>' % self.parse_inner() class Right(BlockReplaceTagNode): """ Aligns text on the right. Usage: [code lang=bbdocs linenos=0][right]Text[/right][/code] """ verbose_name = 'Align Text Right' open_pattern = re.compile(patterns.no_argument % 'right') close_pattern = re.compile(patterns.closing % 'right') def parse(self, as_text=False): if as_text: return self.parse_inner(as_text) return u'<p class="ta-right">%s</p>' % self.parse_inner() class Justify(BlockReplaceTagNode): """ Justifies text. Usage: [code lang=bbdocs linenos=0][justify]Text[/justify][/code] """ verbose_name = 'Justify Text' open_pattern = re.compile(patterns.no_argument % 'justify') close_pattern = re.compile(patterns.closing % 'justify') def parse(self, as_text=False): if as_text: return self.parse_inner(as_text) return u'<p class="ta-justify">%s</p>' % self.parse_inner() register(Center) register(Left) register(Right) register(Justify)
Java
UTF-8
1,394
3.5625
4
[]
no_license
import java.util.Scanner; /** * Se quiere realizar un programa que lea por teclado las 5 notas obtenidas por un alumno (comprendidas * entre 0 y 10). A continuación debe mostrar todas las notas, la nota media, la nota más alta que ha * sacado y la menor. */ public class ProMaMiV { //PROMEDIO,MAXIMO,MINIMO = ProMaMiV int[] notas; Scanner scanner; public ProMaMiV(){ notas= new int[5]; scanner = new Scanner(System.in); } public void ejecutar(){ for (int i = 0; i < notas.length; i++) { System.out.println("NOTAS/" + i + "/: "); int nota = scanner.nextInt(); notas[i] = nota; } double suma =0; double promedio; int minimo = 10; int maximo = 0; for (int i = 0; i < notas.length; i++) { System.out.println("NOTAS/" + i + "/: " + notas[i]); suma = suma + notas[i]; if(notas[i] < minimo){ minimo = notas[i]; } if(notas[i] > maximo){ maximo = notas[i]; } } promedio = suma / notas.length; System.out.println("PROMEDIO TOTAL DE NOTAS: " + promedio); System.out.println("MAXIMA NOTA: " + maximo); System.out.println("MINIMA NOTA: " + minimo); } }
Markdown
UTF-8
1,431
2.96875
3
[]
no_license
# Slack Backend API A backend application modeled after Slack, a communication platform for organizations. This application implements Workspapces, Users, Channels, Threads, Direct Messaging, and Images. - **Workspaces**: A workspace is where on organization and its members be organized on and is made up of channels. - **Channels**: Channels are where team members can communicate collective and work together. Team members can communicate on a channel by posting a message and having a discussion via a Thread. Messages in a channel can also have an image attatched to it which is uploaded to an AWS S3 bucket. - **Direct Messaging**: DMs are a way to have a conversation outside of a channel in a workspace in a 1-on-1 scenario or as a group. Made with: Flask, SQLAlchemy, & AWS S3 API Spec can be found [here](https://github.com/jack-y-wang/slack-backend/blob/master/api.md) ## Setup ### Setup virtual env ```python virtualenv venv . venv/bin/activate pip3 install -r requirements.txt ``` ### Setup AWS env [Guide](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) Create the `credentials` and `config` files. By default, their locations are at `~/.aws/credentials` and `~/.aws/cofig` credentials: ```python [default] aws_access_key_id = YOUR_ACCESS_KEY aws_secret_access_key = YOUR_SECRET_KEY ``` config: ```python [default] region=us-west-1 ``` ## Run ``` python3 src/run.py ```
Python
UTF-8
55
2.984375
3
[ "MIT" ]
permissive
import math print(math.sin(1)) print(math.cos(1))
JavaScript
UTF-8
31,136
2.71875
3
[]
no_license
/** * -- jasTools js工具对象 * -- @GF created on 2019/1/21 * * ---- jasTools.base 基础操作方法 * ------ jasTools.base.createuuid 创建uuid * ------ jasTools.base.extend 对象继承 * ------ jasTools.base.rootPath 服务器路径中的项目名称 * ------ jasTools.base.setAppId 设置appId * ------ jasTools.base.getAppid 获取appId * ------ jasTools.base.getParamsInUrl 获取url里的参数 * ------ jasTools.base.setParamsToUrl 向url里添加参数 * ------ jasTools.base.getIdArrFromTree 在树形结构内获取id * ------ jasTools.base.switchToCamelCase 下划线转驼峰 *------ jasTools.base.switchToLowerCaseAndCamelCase 大写转小写,下划线转驼峰 * ------ jasTools.base.systemGuard 用户的应用权限验证 * * ---- jasTools.dialog 弹出框 * ------ jasTools.dialog.open 打开弹出框 * ------ jasTools.dialog.close 关闭弹出框 * * ---- jasTools.mask 覆盖框 * ------ jasTools.mask.open 打开覆盖框 * ------ jasTools.mask.close 关闭覆盖框 * * ---- jasTools.ajax http请求 * ------ jasTools.ajax.get get请求 * ------ jasTools.ajax.post post请求 * ------ jasTools.ajax.postForm post表单请求 * ------ jasTools.ajax.downloadByIframe 下载 * * */ (function (window) { /** * @description 基础操作库 * */ var tools = (function () { /** * @description 创建uuid */ var createuuid = function () { var s = []; var hexDigits = "0123456789abcdef"; for (var i = 0; i < 36; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } s[14] = "4"; s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); s[8] = s[13] = s[18] = s[23] = "-"; var uuid = s.join(""); return uuid; }; /** *日期转换 */ var formatDate = function (oDate, sFormat) { // 入参:date对象,格式化格式 /* * 对Date的扩展,将 Date 转化为指定格式的String * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * 例子: * formatDate(new Date(),"yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423 * formatDate(new Date(),"yyyy-M-d H:m:s.S") ==> 2006-7-2 8:9:4.18 * formatDate(new Date(),"yyyyMMddHHmmssS") ==> 20060702080904423 */ var o = { "M+": oDate.getMonth() + 1, //月份 "d+": oDate.getDate(), //日 "H+": oDate.getHours(), //小时 "m+": oDate.getMinutes(), //分 "s+": oDate.getSeconds(), //秒 "q+": Math.floor((oDate.getMonth() + 3) / 3), //季度 "S": oDate.getMilliseconds() //毫秒 }; if (/(y+)/.test(sFormat)) sFormat = sFormat.replace(RegExp.$1, (oDate.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(sFormat)) sFormat = sFormat.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return sFormat; }; /** * @description 继承对象 * @param target 要被继承的对象 */ var extend = function (target) { for (var i = 1, j = arguments.length; i < j; i++) { var source = arguments[i] || {}; for (var prop in source) { if (source.hasOwnProperty(prop)) { var value = source[prop]; if (value !== undefined) { target[prop] = value; } } } } return target; }; /** * @description 获取url的 * @param target 要被继承的对象 */ var getParamsInUrl = function (url) { var obj = null; if (url) { var arr = url.split('?'); if (arr.length > 1) { var str = arr[1]; var arr2 = str.split('&'); arr2.forEach(function (item) { var _arr = item.split('='); if (_arr.length > 1) { obj = obj ? obj : {}; obj[_arr[0]] = _arr[1]; } }) } } return obj || {}; }; /** * @description 向url上添加 key:value * @param url locoation.href * @param obj 键值对 */ var setParamsToUrl = function (url, obj) { if (!obj || typeof obj !== 'object') { return url } for (var prop in obj) { if (obj.hasOwnProperty(prop)) { var value = obj[prop]; if (value !== undefined) { var str_connenct = url.indexOf('?') === -1 ? '?' : '&'; url += str_connenct + prop + '=' + value; } } } return url; }; /** * 功能描述:获取系统根路径 */ var getRootPath = function () { // 获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath = window.document.location.href; // 获取主机地址之后的目录,如: uimcardprj/share/meun.jsp var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); // 获取主机地址,如: http://localhost:8083 var localhostPaht = curWwwPath.substring(0, pos); // 获取带"/"的项目名,如:/uimcardprj var projectName = pathName.substring(0, pathName.substring(1).indexOf('/') + 1); // 判断是否是前端项目,则设定代理前缀 if (!projectName || projectName === '/jasmvvm' || projectName === '/jasframework' || projectName === '/pages') { return '/jasproxy' } return projectName; // /uimcardprj // return (localhostPaht + projectName + "/"); }; var setAppId = function (appId) { if (!appId) return alert('请传入appId'); localStorage.setItem('appId', appId); }; var getAppId = function () { var id = localStorage.getItem('appId'); if (!id) { alert('未设置AppId') } return id; }; var getIdArrFromTree = function (treeData, nodeId, config) { var pidArr = [nodeId]; var getPId = function (dataArr, id, pid) { for (var i = 0; i < dataArr.length; i++) { var item = dataArr[i]; if (item.id === id) { return pid; } else { if (item.children && item.children.length > 0) { var result = getPId(item.children, id, item.id); if (result) return result; } } } }; var getPPId = function (dataArr, id) { var pid = getPId(dataArr, id, ''); if (pid) { pidArr.push(pid); getPPId(dataArr, pid); } else { return pidArr; } }; getPPId(treeData, nodeId); return pidArr.reverse(); }; var fontSize = function (res) { var clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; if (!clientHeight) return; var fontSize = 100 * (clientHeight / 1080); return res * fontSize; } //字符串下划线转为驼峰 var switchToCamelCase = function (string) { // Support: IE9-11+ return string.replace(/_([a-z])/g, function (all, letter) { return letter.toUpperCase(); }); }; var switchToLowerCaseAndCamelCase = function (string) { // Support: IE9-11+ string = string.toLowerCase(); return string.replace(/_([a-z])/g, function (all, letter) { return letter.toUpperCase(); }); }; var systemGuard = function (config, successcb, failcb) { var params = jasTools.base.getParamsInUrl(location.href.split('#')[0]); var error = 0; var isAppRight = function () { if ((config.appId == params.appId) || !config.appId) { return true; } error = 1; return false; }; var getPlatRoot = function () { var rootPath = ''; var url = jasTools.base.rootPath + '/jasframework/privilege/application/getPlatformContext.do'; $.ajax({ type: "GET", url: url, async: false, data: { token: params.token, appId: config.appId, }, success: function (data, status) { rootPath = data.data; } }); return rootPath; }; var isAppAccessable = function () { var result = false; var myRootPath = getPlatRoot(); if (!myRootPath) { error = 2; return result; } var url = myRootPath + '/jasframework/privilege/application/userAppPermission.do'; $.ajax({ type: "GET", url: url, async: false, data: { token: params.token, appId: params.appId, }, success: function (data, status) { if (data.data == true) { result = true; } } }); error = 3; return result; }; var loginByToken = function () { //http://192.168.100.130:8888/ var url = config.loginHost + '/jasframework/login/loginByTokenAndAppId.do'; $.ajax({ type: "GET", url: url, async: false, data: { token: params.token, appId: params.appId, }, success: function (data, status) { // var userBo = data.user; // var unitName = userBo.unitName; // unitName = unitName.substr(unitName.lastIndexOf(">") + 1, unitName.length); // userBo.unitName = unitName; // localStorage.setItem("user", JSON.stringify(userBo)); successcb && successcb(data); } }); }; if (!params.token || !params.appId) { console.error('未在url中发现token或者appId') return; //不做任何验证 } if (isAppRight()) { if (isAppAccessable()) { successcb && successcb(); return; } } if (error == 1) { alert('前端AppId配置错误') } if (error == 2) { alert('platform.service.address配置错误') } // if (error == 3) { // alert('无进入权限') // } if (typeof failcb == 'function') { return failcb(error); } alert('无进入权限') }; var viewImg = function (src) { if (!window.Image || !window.Viewer) { return alert('缺少必要的资源包'); } var image = new Image(); image.src = src; var viewer = new Viewer(image, { hidden: function () { viewer.destroy(); }, }); viewer.show(); }; var fileUploader = function (params) { var argument = params.argument; var obj = tools.extend({ domId: '', fileType: 'file', //pic businessId: '', businessType: '', maxSize: 500, maxTotalSize: 1000, maxCount: 20, // filePreview: null, // picPreview: null, cbSuccessed: function () {}, cbfailed: function () {} }, params); var html = [ '<jas-file-upload-new ref="upload"', ' :file-type="fileType" ', ' :business-id="businessId" ', ' :business-type="businessType" ', ' :max-size="maxSize" ', ' :max-total-size="maxTotalSize" ', ' :max-count="maxCount" ', ' :file-preview="filePreview" ', ' :pic-preview="picPreview" ', ' @fail="cbfailed" ', ' @success="cbSuccessed">', '</jas-file-upload-new>' ].join(''); var res = Vue.compile(html); var inst = new Vue({ el: obj.domId, data: { fileType: obj.fileType, businessId: obj.businessId, businessType: obj.businessType, maxSize: obj.maxSize, maxTotalSize: obj.maxTotalSize, maxCount: obj.maxCount, filePreview: obj.filePreview, picPreview: obj.picPreview, }, methods: { cbSuccessed: function () { obj.cbSuccessed && obj.cbSuccessed() }, cbfailed: function (a, b, c) { obj.cbfailed && obj.cbfailed(a, b, c) }, upload: function () { this.$refs.upload.uploadFile(); } }, render: res.render, }); // document.body.appendChild(inst.$el); // dialogs.push(inst); return inst; }; var fileLister = function (params) { var argument = params.argument; var obj = tools.extend({ domId: '', fileType: 'file', //pic businessId: '', businessType: '', // filePreview: function () {} // picPreview: function () {} }, params); var picHtml = [ '<jas-pic-list :biz-id="bizId" :biz-type="businessType" :pic-preview="picPreview" :file-preview="filePreview"></jas-pic-list>' ].join(''); var fileHtml = [ '<jas-file-list-new :biz-id="bizId" :biz-type="businessType" :pic-preview="picPreview" :file-preview="filePreview"></jas-file-list-new>' ].join(''); var res = Vue.compile(obj.fileType == 'file' ? fileHtml : picHtml); var inst = new Vue({ el: obj.domId, data: { // fileType: obj.fileType, bizId: obj.businessId, businessType: obj.businessType, filePreview: obj.filePreview, picPreview: obj.picPreview, }, methods: {}, render: res.render, }); // document.body.appendChild(inst.$el); // dialogs.push(inst); return inst; }; var encryption = function (txt) { var _str = txt; var _strLength = _str.length; var _strTarget = ""; for (var i = 0; i < _strLength; i++) { _strTarget += String.fromCharCode(_str.charCodeAt(i) + (_strLength - i)); } return escape(_strTarget); }; /** * @desc 函数防抖 * @param func 函数 * @param wait 延迟执行毫秒数 * @param immediate true 表立即执行,false 表非立即执行 */ var debounce = function (func, wait, immediate) { var timeout; return function () { var context = this; var args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = !timeout; timeout = setTimeout(function () { timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function () { func.apply(context, args) }, wait); } } }; /** * @desc 函数节流 * @param func 函数 * @param wait 延迟执行毫秒数 * @param type 1 表时间戳版,2 表定时器版 */ var throttle = function (func, wait, type) { if (type === 1) { var previous = 0; } else if (type === 2) { var timeout; } return function () { var context = this; var args = arguments; if (type === 1) { var now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } } else if (type === 2) { if (!timeout) { timeout = setTimeout(function () { timeout = null; func.apply(context, args) }, wait) } } } } return { rootPath: getRootPath(), setAppId: setAppId, getAppId: getAppId, createuuid: createuuid, extend: extend, formatDate: formatDate, getParamsInUrl: getParamsInUrl, setParamsToUrl: setParamsToUrl, getIdArrFromTree: getIdArrFromTree, switchToCamelCase: switchToCamelCase, switchToLowerCaseAndCamelCase: switchToLowerCaseAndCamelCase, systemGuard: systemGuard, viewImg: viewImg, fileUploader: fileUploader, fileLister: fileLister, encryption: encryption, encryption: encryption, debounce: debounce, throttle: throttle, fontSize: fontSize }; })(); /** * 模态框相关操作 */ var jasDialog = (function (tools) { var dialogs = []; /** * @description 弹出弹出层 * @param params 参数对象 * @param params.id 参数对象 * @param params.title 参数对象 * @param params.src 参数对象 * @param params.height 参数对象 * @param params.width 参数对象 * @param params.cbForClose 模态框关闭的回调 */ var show = function (params) { var argument = params.argument; var obj = tools.extend({ title: '模态框', src: 'https://www.awesomes.cn/', height: (80 - dialogs.length * 15) + '%', width: (80 - dialogs.length * 15) + '%', visible: true }, params); var html = [ '<jas-iframe-dialog', ' :title="title" ', ' :iframeUrl="iframeUrl" ', ' :height="height" ', ' :width="width" ', ' :visible.sync="visible" ', ' @close="close">', '</jas-iframe-dialog>' ].join(''); var res = Vue.compile(html); var inst = new Vue({ el: document.createElement('div'), data: { title: obj.title, iframeUrl: obj.src, height: obj.height, width: obj.width, visible: obj.visible, }, methods: { close: function () { if (obj.cbForClose) { obj.cbForClose(this.paramForCallback); } var dom = this.$el; dom.parentNode.removeChild(dom); //删除 dialogs.length = dialogs.length - 1; // console.log('关闭了一个dialogs') // this.$destroy(); return; } }, render: res.render, //staticRenderFns: res.staticRenderFns }); document.body.appendChild(inst.$el); dialogs.push(inst); }; /** * @description 关闭最顶上的弹出层 * @param params 参数对象 */ var close = function (param) { var index = dialogs.length - 1; if (index < 0) { console.log('没有可以关闭的dialogs') return; } var inst = dialogs[index]; inst.paramForCallback = param; inst.visible = false; }; return { // dialogs: dialogs, show: show, close: close }; })(tools); var jasMask = (function (tools) { var aMaskInst = []; function Mask(obj) { var that = this; this.init(obj); setTimeout(function () { that.show(); }, 10); } Mask.prototype = { constructor: Mask, init: function (obj) { var that = this; // obj={ // window : window, // src:"", // params:{}, // cbForClose : null // } this.title = obj.title || ''; this.src = obj.src || ''; this.window = obj.window || window; this.params = obj.params || ''; this.cbForClose = obj.cbForClose || function () {}; this.insertDom(); var returnBtn = this.node.querySelector('.mask_return'); returnBtn.onclick = function () { that.close(); } }, insertDom: function () { var html = [ '<div style="height:34px;width:100%;box-sizing:border-box;background:#cee6ff;overflow: hidden;line-height:34px;padding:0 15px;position: absolute;">', ' <span>', this.title, '</span>', ' <span style="float:right;cursor: pointer;color: #409EFF;" class="mask_return">返回</span>', '</div>', '<div style="height:100%;box-sizing: border-box;padding-top:34px;">', ' <iframe src="" frameborder="0" style="height:100%;width:100%;"></iframe>', '</div>', ].join(''); var node = document.createElement('div'); node.style['height'] = 0; node.style['width'] = 0; node.style['background'] = '#fff'; node.style['position'] = 'fixed'; node.style['top'] = '50%'; node.style['left'] = '50%'; node.style['transform'] = 'translate(-50%,-50%)'; node.style['z-index'] = '10'; node.style['transition'] = 'all 0.3s'; node.style['opacity'] = 0; node.innerHTML = html; this.window.document.body.appendChild(node); this.node = node; }, getTrueSrc: function () { if (!this.src || !this.params) { return this.src } return tools.setParamsToUrl(this.src, this.params); }, show: function () { var that = this; this.node.style.height = '100%'; this.node.style.width = '100%'; this.node.style.opacity = '1'; aMaskInst.push(this); setTimeout(function () { var src = that.getTrueSrc(); that.node.querySelector('iframe').src = src; }, 300) }, close: function (param) { var that = this; this.node.style.height = '0'; this.node.style.width = '0'; this.node.style.opacity = '0'; this.cbForClose && this.cbForClose(param); setTimeout(function () { that.node.remove(); aMaskInst.length = aMaskInst.length - 1; }, 300) } } var showMask = function (obj) { var mask = new Mask(obj); } var closeMask = function (param) { var index = aMaskInst.length - 1; if (index < 0) { console.info('没有可以关闭的dialogs') return; } var inst = aMaskInst[index]; inst.close(param); } return { show: showMask, close: closeMask } })(tools); var ajax = (function () { var ajax = function (type, url, params, cb_success, cb_fail, isSync) { for (var key in params) { if (params[key] == undefined) { params[key] = null; } } var data = type === 'POST' ? JSON.stringify(params) : params; var contentType = type === 'POSTFORM' ? ' application/x-www-form-urlencoded' : 'application/json'; var ajaxType = type === 'POSTFORM' ? 'POST' : type; $.ajax({ type: ajaxType || "GET", url: tools.setParamsToUrl(url, { token: localStorage.getItem('token') }), contentType: contentType, data: data, async: !isSync ? true : false,//使用同步的方式,true为异步方式 success: function (data, status) { if (data.status == -1 && data.code == "402") { // token失效或者过期,会返回-1 window.top.Vue.prototype.$confirm('登录信息失效,请重新登录', '提示', { type: 'warning', callback: function (action) { if (action === 'confirm') { window.top.location.href = jasTools.base.rootPath + "/jasmvvm/pages/page-login/login.html"; } } }); return; } if (data.status == -1 && data.code == "excel-400") { // token失效或者过期,会返回-1 window.top.Vue.prototype.$message({ message: '当前查询条件下无数据', type: 'error' }); return; } if (data.status == 1 || data.status == 'ok') { cb_success && cb_success(data); } else if (!data.status && data) { if (data.success == -1) { cb_fail && cb_fail(data); window.top.Vue.prototype.$message({ message: data.msg || data.message || '服务器连接失败,请稍后再试', type: 'error' }); } else { cb_success && cb_success(data); } } else { cb_fail && cb_fail(data); window.top.Vue.prototype.$message({ message: data.msg || data.message || '服务器连接失败,请稍后再试', type: 'error' }); } }, error: function () { cb_fail && cb_fail(data); window.top.Vue.prototype.$message({ message: '服务器连接失败,请稍后再试', type: 'error' }); } }); }; var downloadByIframe = function (type, url, data) { if (!url) return; var config = { url: tools.setParamsToUrl(url, { token: localStorage.getItem('token') }), data: data || {}, method: type || data, } var $iframe = $('<iframe id="down-file-iframe" />'); var $form = $('<form method="' + config.method + '" />'); $form.attr('action', config.url); for (var key in config.data) { $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />'); } $iframe.append($form); $(document.body).append($iframe); $form[0].submit(); $iframe.remove(); }; /** * @description xhr_post方式下载文件 * @param url 请求路径 * @param obj 请求参数 * @param cbsuccess 成功回调 * @param cbfail 失败回调 */ var downloadByPost = function (url, obj, cbsuccess, cbfail) { if (!url) return; url = tools.setParamsToUrl(url, { token: localStorage.getItem('token') }); var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); // 也可以使用POST方式,根据接口 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.responseType = "blob"; // 返回类型blob // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑 xhr.onload = function (param) { // 请求完成 // content-disposition: attachment;filename=custom_desktop.java if (this.status === 200) { // 获取文件名 var filename = 'download.txt'; var sName = xhr.getResponseHeader('content-disposition'); if (sName) { sName.split(';').forEach(function (item) { var arr = item.split('='); if (arr[0] === 'filename') { filename = arr[1]; filename = decodeURIComponent(filename); } }); // 返回200 var blob = this.response; var reader = new FileReader(); reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href reader.onload = function (e) { // 转换完成,创建一个a标签用于下载 var a = document.createElement('a'); a.download = filename; a.href = e.target.result; document.getElementsByTagName('body')[0].appendChild(a); // 修复firefox中无法触发click // $(a).trigger('click'); a.click(); // a.remove(); a.parentNode.removeChild(a); cbsuccess && cbsuccess(xhr); } } else { cbfail && cbfail(param, this); } } else { cbfail && cbfail(param, this); } }; // 发送ajax请求 if (obj) { var sdata = ''; for (var key in obj) { if (obj.hasOwnProperty(key)) { var item = key + '=' + obj[key]; sdata += sdata ? '&' + item : item; } } } xhr.send(sdata); }; return { ajax: ajax, get: ajax.bind(null, 'GET'), post: ajax.bind(null, 'POST'), postForm: ajax.bind(null, 'POSTFORM'), downloadByIframe: downloadByIframe, downloadByPost: downloadByPost, }; })(); var vScroll = (function () { var intId = []; var seeped = 10; var init = function (options) { seeped = options.seeped; $el = options.el; $($el).each(function (i) { intId[i] = createSet($($el)); $($el).hover(function () { clearAll(); }, function () { if (intId[0]) { clearInterval(intId[0]); } intId[i] = createSet($($el)); }); }); }; var createSet = function (_this) { return setInterval(function () { if (_this.find(".marquee").height() <= _this.height()) { clearAll(); } else { marquee(_this); } }, seeped); } var marquee = function (obj) { obj.find(".marquee").animate({ marginTop: '-=1' }, 0, function () { var s = Math.abs(parseInt($(this).css("margin-top"))); var node = $(this).context.childNodes[0].nodeName; if (s >= $(this).find(node)[0].offsetHeight) { $(this).find(node).slice(0, 1).appendTo($(this)); $(this).css("margin-top", 0); } }); }; var clearAll = function (cb) { intId.forEach(function (item) { clearInterval(item); }); if (cb) { cb(); $(".marquee").css("margin-top", 0); } }; return { init: init, clearAll: clearAll } })(); /** * 弹出详情信息相关操作 */ var selfDialog = (function (tools) { var dialogs = []; /** * @description 弹出弹出层 * @param params 参数对象 * @param params.id 参数对象 * @param params.title 参数对象 * @param params.src 参数对象 * @param params.height 参数对象 * @param params.width 参数对象 * @param params.cbForClose 模态框关闭的回调 */ var show = function (params) { var argument = params.argument; console.log(argument); var obj = tools.extend({ title: '模态框', src: 'https://www.awesomes.cn/', height: (80 - dialogs.length * 15) + '%', width: (80 - dialogs.length * 15) + '%', visible: true, isDetail: false, // left: left ? left : "", // right: right ? right : "", // top: top ? top : "", // bottom: bottom ? bottom : "" }, params); var html = [ '<jas-dialog', ' :title="title" ', ' :iframeUrl="iframeUrl" ', ' :height="height" ', ' :width="width" ', ' :visible.sync="visible" ', ' :isDetail = "isDetail" ', ' :left = "left" ', ' :right = "right" ', ' :top = "top" ', ' :bottom = "bottom" ', ' @close="close">', '</jas-dialog>' ].join(''); var res = Vue.compile(html); var inst = new Vue({ el: document.createElement('div'), data: { title: obj.title, iframeUrl: obj.src, height: obj.height, width: obj.width, visible: obj.visible, isDetail: obj.isDetail, left: obj.left, right: obj.right, top: obj.top, bottom: obj.bottom, }, methods: { close: function () { if (obj.cbForClose) { obj.cbForClose(this.paramForCallback); } var dom = this.$el; dom.parentNode.removeChild(dom); //删除 dialogs.length = dialogs.length - 1; // console.log('关闭了一个dialogs') // this.$destroy(); return; } }, render: res.render, //staticRenderFns: res.staticRenderFns }); document.body.appendChild(inst.$el); dialogs.push(inst); }; /** * @description 关闭最顶上的弹出层 * @param params 参数对象 */ var close = function (param) { var index = dialogs.length - 1; if (index < 0) { alert('没有可以关闭的dialogs') return; } var inst = dialogs[index]; inst.paramForCallback = param; inst.visible = false; }; return { // dialogs: dialogs, show: show, close: close }; })(tools); /** * 弹出详情信息相关操作 */ var selfDialogNew = (function (tools) { var dialogs = []; /** * @description 弹出弹出层 * @param params 参数对象 * @param params.id 参数对象 * @param params.title 参数对象 * @param params.src 参数对象 * @param params.height 参数对象 * @param params.width 参数对象 * @param params.cbForClose 模态框关闭的回调 */ var show = function (params) { var argument = params.argument; console.log(argument); var obj = tools.extend({ title: '模态框', src: 'https://www.awesomes.cn/', height: (80 - dialogs.length * 15) + '%', width: (80 - dialogs.length * 15) + '%', visible: true, isDetail: false, }, params); var html = [ '<div class="new-mask"><jas-dialog-new', ' :title="title" ', ' :iframeUrl="iframeUrl" ', ' :height="height" ', ' :width="width" ', ' :visible.sync="visible" ', ' :isDetail = "isDetail" ', ' @close="close">', '</jas-dialog-new></div>' ].join(''); var res = Vue.compile(html); var inst = new Vue({ el: document.createElement('div'), data: { title: obj.title, iframeUrl: obj.src, height: obj.height, width: obj.width, visible: obj.visible, isDetail: obj.isDetail, }, methods: { close: function () { if (obj.cbForClose) { obj.cbForClose(this.paramForCallback); } var dom = this.$el; dom.parentNode.removeChild(dom); //删除 dialogs.length = dialogs.length - 1; return; } }, render: res.render, //staticRenderFns: res.staticRenderFns }); document.body.appendChild(inst.$el); dialogs.push(inst); }; /** * @description 关闭最顶上的弹出层 * @param params 参数对象 */ var close = function (param) { var index = dialogs.length - 1; if (index < 0) { alert('没有可以关闭的dialogs') return; } var inst = dialogs[index]; inst.paramForCallback = param; inst.visible = false; }; return { // dialogs: dialogs, show: show, close: close }; })(tools); window.jasTools = { dialog: jasDialog, selfDialogNew: selfDialogNew, selfDialog: selfDialog, mask: jasMask, base: tools, ajax: ajax, scroll: vScroll }; })(window);
C
UTF-8
498
3.78125
4
[ "MIT" ]
permissive
/* * @Param * int number * findComplement: * Given a positive integer, output its complement number. * @Return * int * Returns the complement (on bits) of the given number * References: * Bitwise operators -> https://en.wikipedia.org/wiki/Bitwise_operations_in_C * Explenation: * The complement number is the number in bits such that, when maken an OR operation * on the bits, you get all 1s * Example * 101 = 5 * 010 = 2 -> this is the comlement of 5 */ int findComplement(int);
Ruby
UTF-8
4,309
2.5625
3
[ "MIT", "CC-BY-SA-4.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true module RuboCop module CodeReuseHelpers # Returns true for a `(send const ...)` node. def send_to_constant?(node) node.type == :send && node.children&.first&.type == :const end # Returns `true` if the name of the receiving constant ends with a given # `String`. def send_receiver_name_ends_with?(node, suffix) return false unless send_to_constant?(node) receiver_name = name_of_receiver(node) receiver_name != suffix && receiver_name.end_with?(suffix) end # Returns the file path (as a `String`) for an AST node. def file_path_for_node(node) node.location.expression.source_buffer.name end # Returns the name of a constant node. # # Given the AST node `(const nil :Foo)`, this method will return `:Foo`. def name_of_constant(node) node.children[1] end # Returns true if the given node resides in app/finders or ee/app/finders. def in_finder?(node) in_directory?(node, 'finders') end # Returns true if the given node resides in app/models or ee/app/models. def in_model?(node) in_directory?(node, 'models') end # Returns true if the given node resides in app/services or ee/app/services. def in_service_class?(node) in_directory?(node, 'services') end # Returns true if the given node resides in app/presenters or # ee/app/presenters. def in_presenter?(node) in_directory?(node, 'presenters') end # Returns true if the given node resides in app/serializers or # ee/app/serializers. def in_serializer?(node) in_directory?(node, 'serializers') end # Returns true if the given node resides in app/workers or ee/app/workers. def in_worker?(node) in_directory?(node, 'workers') end # Returns true if the given node resides in app/controllers or # ee/app/controllers. def in_controller?(node) in_directory?(node, 'controllers') end # Returns true if the given node resides in lib/api or ee/lib/api. def in_api?(node) file_path_for_node(node).start_with?( File.join(ce_lib_directory, 'api'), File.join(ee_lib_directory, 'api') ) end # Returns `true` if the given AST node resides in the given directory, # relative to app and/or ee/app. def in_directory?(node, directory) file_path_for_node(node).start_with?( File.join(ce_app_directory, directory), File.join(ee_app_directory, directory) ) end # Returns the receiver name of a send node. # # For the AST node `(send (const nil :Foo) ...)` this would return # `'Foo'`. def name_of_receiver(node) name_of_constant(node.children.first).to_s end # Yields every defined class method in the given AST node. def each_class_method(node) return to_enum(__method__, node) unless block_given? # class << self # def foo # end # end node.each_descendant(:sclass) do |sclass| sclass.each_descendant(:def) do |def_node| yield def_node end end # def self.foo # end node.each_descendant(:defs) do |defs_node| yield defs_node end end # Yields every send node found in the given AST node. def each_send_node(node, &block) node.each_descendant(:send, &block) end # Registers a RuboCop offense for a `(send)` node with a receiver that ends # with a given suffix. # # node - The AST node to check. # suffix - The suffix of the receiver name, such as "Finder". # message - The message to use for the offense. def disallow_send_to(node, suffix, message) each_send_node(node) do |send_node| next unless send_receiver_name_ends_with?(send_node, suffix) add_offense(send_node, location: :expression, message: message) end end def ce_app_directory File.join(rails_root, 'app') end def ee_app_directory File.join(rails_root, 'ee', 'app') end def ce_lib_directory File.join(rails_root, 'lib') end def ee_lib_directory File.join(rails_root, 'ee', 'lib') end def rails_root File.expand_path('..', __dir__) end end end
C
UTF-8
552
3.359375
3
[]
no_license
// find digits problem // https://www.hackerrank.com/challenges/find-digits/problem?isFullScreen=false&h_r=next-challenge&h_v=zen int findDigits(int n) { int count =0; int rem=0, num =0; num = n; while(n>0){ rem = n%10; //printf("\n %d", rem); //handle the arithmetic exception in case rem = 0 for numbers like 1002 we need to skip and check other values if(rem ==0){ n = n/10; continue; } if(num % rem == 0) count++; n = n/10; } return count; }
C
UTF-8
9,094
3.15625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <limits.h> #include <omp.h> #include <math.h> #define FILENAME "cells" #define MAX_DISTANCES 3466 //number of max distances since values are between -10 and 10 (00,00 .... 34,65) #define MAX_POINTS_PER_BLOCK 10000 // number of points allowed to load each time in order to not exceed 1Mb #define CHAR_PER_POINT 24 // number of chars per line i.e. per point including \n #define CHAR_PER_COORDINATE 8 // 1 sign, 2 before comma, 1 comma, 3 after comma, 1 space or \n //-- Prototypes /////////////////////////////////////////////////// void parseArguments(int argc, char *argv[], char *progname, short unsigned *threads); long convertToInt(char *arg); /* Tries to read from the given file pointer n_chars_to_read characters and parses the coordinates. * If less characters are read, the method prints an error to stderr. * In either case, the really read number of points is returned. * The parsed coordinates are stored in points. */ int read_and_parse_parallel(int n_chars_to_read, short *points, FILE *fp); /* Calculates the distance between all points in the given block. * The block contains number_of_points points and the result is written into distances. */ static inline void distance_within_block(size_t number_of_points, short *points, int *distances); //-- main() /////////////////////////////////////////////////// int main(int argc, char *argv[]) { char *progname; FILE *fp; short unsigned threads; size_t number_of_characters, number_of_fixed_points, blocks; const int max_read_char = MAX_POINTS_PER_BLOCK * CHAR_PER_POINT; //has to be an int, short is too small int distances[MAX_DISTANCES] = { 0 }; //store points as short, 3 * since we store the coordinates for a point after each other //i.e.: x1 y1 z1 x2 y2 z2 ... short int fixed_points[3 * MAX_POINTS_PER_BLOCK]; //get program name if (argc > 0) progname = argv[0]; else { fprintf(stderr, "Error: no program name can be found\n"); exit(EXIT_FAILURE); } parseArguments(argc, argv, progname, &threads); //set max number of threads for omp omp_set_num_threads(threads); if ((fp = fopen(FILENAME, "r")) == NULL) { fprintf(stderr, "Cannot open \"%s\" file to read! Exiting.\n", FILENAME); exit(EXIT_FAILURE); } //get number of points in file //move to file end with offset 0 fseek(fp, 0, SEEK_END); //ftell gives us the current position in the file which is equal to the number of bytes if called at end of file number_of_characters = ftell(fp); blocks = number_of_characters / max_read_char; //check if we have a not full part if (number_of_characters % max_read_char != 0) { blocks++; } //move back to beginning fseek(fp, 0, SEEK_SET); //if there is only one block we can simply load everything at once: if (blocks == 1) { //printf("### ### #### #### #### #### #### ####\n"); //printf("\t\tone block - starting\n"); number_of_fixed_points = read_and_parse_parallel(number_of_characters, fixed_points, fp); distance_within_block(number_of_fixed_points, fixed_points, distances); } else { //printf("### ### #### #### #### #### #### ####\n"); //printf("\t\tmultiple blocks - starting\n"); //read fixed block and calculate distance within this block for (size_t block_i = 0; block_i < blocks; block_i++) { //jump to position in file fseek(fp, block_i * max_read_char, SEEK_SET); number_of_fixed_points = read_and_parse_parallel(max_read_char, fixed_points, fp); distance_within_block(number_of_fixed_points, fixed_points, distances); //now read other block(s) and calculate distances between for (size_t block_j = block_i + 1; block_j < blocks; block_j++) { int chars_in_block = max_read_char; size_t points_in_block = MAX_POINTS_PER_BLOCK; int points_read; if (block_j == blocks - 1 && (number_of_characters % max_read_char != 0)) { //last block and block net full chars_in_block = number_of_characters % max_read_char; points_in_block = chars_in_block % CHAR_PER_POINT; } //we only need 3 * the number of points in a block to store the coordinates short block_points[3 * points_in_block]; points_read = read_and_parse_parallel(chars_in_block, block_points, fp); //calculate distance #pragma omp parallel for reduction(+:distances[:MAX_DISTANCES]) for (size_t i = 0; i < number_of_fixed_points; ++i) { for (size_t j = 0; j < points_read; ++j) { double dx = (fixed_points[3 * i] - block_points[3 * j]); double dy = (fixed_points[3 * i + 1] - block_points[3 * j + 1]); double dz = (fixed_points[3 * i + 2] - block_points[3 * j + 2]); short idx = (short)(sqrt(dx * dx + dy * dy + dz * dz) / 10.0); ++distances[idx]; } } } } } fclose(fp); //printf("finished, now printing values:\n"); for (size_t i = 0; i < MAX_DISTANCES; i++) if (distances[i] != 0) printf("%02lu.%02lu %i\n", i / 100, i % 100, distances[i]); exit(EXIT_SUCCESS); } //-- methods ////////////////////////////////////////////////// int read_and_parse_parallel(int n_chars_to_read, short *points, FILE *fp) { char buffer[MAX_POINTS_PER_BLOCK * CHAR_PER_POINT]; int chars_read = fread(buffer, sizeof(char), n_chars_to_read, fp); if(chars_read != n_chars_to_read) { fprintf(stderr, "Attention: wanted to read %d chars but read %d!\n", n_chars_to_read, chars_read); } int points_read = chars_read / CHAR_PER_POINT; //printf("read %d points, now starting to parse\n", points_read); //we can safely use collapse here since we have no dependencies #pragma omp parallel for collapse(2) for (size_t i = 0; i < points_read; i++) { for (size_t j = 0; j < 3; j++) { size_t k = i * CHAR_PER_POINT + j * CHAR_PER_COORDINATE; points[3 * i + j] = (buffer[k + 1] - '0') * 10000 + (buffer[k + 2] - '0') * 1000 + (buffer[k + 4] - '0') * 100 + (buffer[k + 5] - '0') * 10 + (buffer[k + 6] - '0'); if (buffer[k] == '-') points[3 * i + j] *= -1; } } return points_read; } static inline void distance_within_block(size_t number_of_points, short *points, int *distances) { #pragma omp parallel for reduction(+:distances[:MAX_DISTANCES]) for (size_t i = 0; i < number_of_points; i++) { for (size_t j = i + 1; j < number_of_points; j++) { double dx = points[3 * i] - points[3 * j]; double dy = points[3 * i + 1] - points[3 * j + 1]; double dz = points[3 * i + 2] - points[3 * j + 2]; short idx = (short)(sqrt(dx * dx + dy * dy + dz * dz) / 10.0); ++distances[idx]; } } } void parseArguments(int argc, char *argv[], char *progname, short unsigned *threads) { if (argc != 2) { fprintf(stderr, "Usage: %s -t<threads>\n", progname); exit(EXIT_FAILURE); } int opt; while ((opt = getopt(argc, argv, "t:")) != -1) { switch (opt) { case 't': *threads = convertToInt(optarg); break; default: fprintf(stderr, "Usage: %s -t<threads>\n", progname); exit(EXIT_FAILURE); } } //check for validity of arguments: if (*threads <= 0) { fprintf(stderr, "Error: Given number of threads is invalid/missing!\n"); exit(EXIT_FAILURE); } } long convertToInt(char *arg) { char *endptr; long number; //10 = decimal system, endptr is to check if strtol gave us a number number = strtol(arg, &endptr, 10); if ((errno == ERANGE && (number == LONG_MAX || number == LONG_MIN)) || (errno != 0 && number == 0)) { fprintf(stderr, "Failed to convert input to number!\n"); exit(EXIT_FAILURE); } if (endptr == arg) { fprintf(stderr, "No digits where found!\n"); exit(EXIT_FAILURE); } /* If we got here, strtol() successfully parsed a number */ if (*endptr != '\0') { /* In principle not necessarily an error... */ fprintf(stderr, "Attention: further characters after number: %s\n", endptr); exit(EXIT_FAILURE); } return number; }
Shell
UTF-8
2,441
2.859375
3
[]
no_license
#!/bin/sh -x # 以下脚本文件用在服务器端,对于OPENVPN客户端的下载流量进行限速(即服务器端出流量),带宽单位为kbits/s #定义链路带宽 LinkCeilDownSpeed=30000 #链路最大下载带宽 LinkCeilUploadSpeed=30000 #链路最大上传带宽 LinkRateDownSpeed=6000 #链路保障下载带宽 LinkRateUploadSpeed=6000 #链路保障上传带宽 #定义VPN 用户的最大带宽和保障带宽 UserCeilDownSpeed=6000 #特殊用户最大下载带宽 UserCeilUploadSpeed=6000 #特殊用户最大上传带宽 UserRateDownSpeed=6000 #特殊用户保障下载带宽 UserRateUploadSpeed=6000 #特殊用户保障上传带宽 #定义其他用户的最大带宽合保障带宽 OtherCeilDownSpeed=6000 #其他用户最大下载带宽 OtherCeilUploadSpeed=6000 #其他用户最大上传带宽 OtherRateDownSpeed=6000 #其他用户保障下载带宽 OtherRateUploadSpeed=6000 #其他用户保障上传带宽 #定义限速网卡 EXTDEV=tun0 #定义VPN客户端地址前缀, vpn_address_pre=10.8.0 #定义对多少个OPENVPN客户端IP进行限速,第一个为10.8.0.2 vpn_total_number=20 # 清除接口上的队列及 mangle 表 /usr/sbin/tc qdisc del dev $EXTDEV root 2> /dev/null > /dev/null #以下是上传限速 #------------------------------------------------------------------------------------------- /usr/sbin/tc qdisc add dev $EXTDEV root handle 1: htb default 255 #定义 class /usr/sbin/tc class add dev $EXTDEV parent 1: classid 1:1 htb rate ${LinkRateUploadSpeed}kbit ceil ${LinkCeilUploadSpeed}kbit for((i = 2; i <= $vpn_total_number; i++)) do /usr/sbin/tc class add dev $EXTDEV parent 1:1 classid 1:$i htb rate ${UserRateUploadSpeed}kbit ceil ${UserCeilUploadSpeed}kbit done /usr/sbin/tc class add dev $EXTDEV parent 1:1 classid 1:255 htb rate ${OtherRateUploadSpeed}kbit ceil ${OtherCeilUploadSpeed}kbit #定义匹配VPN客户端地址 for((i = 2; i <= $vpn_total_number; i++)) do /usr/sbin/tc filter add dev $EXTDEV protocol ip parent 1:0 prio 1 u32 match ip dst $vpn_address_pre.$i flowid 1:$i done #定义队列 for((i = 2; i <= $vpn_total_number; i++)) do /usr/sbin/tc qdisc add dev $EXTDEV parent 1:$i handle $i: sfq perturb 10 done /usr/sbin/tc qdisc add dev $EXTDEV parent 1:255 handle 255: sfq perturb 10 echo "`date` 成功执行了6M的限速策略" exit 0
Ruby
UTF-8
113
2.671875
3
[]
no_license
s = 'abc' puts s.public_methods.inspect # https://docs.ruby-lang.org/en/2.6.0/Object.html#method-i-public_method
Markdown
UTF-8
1,896
2.75
3
[ "Apache-2.0" ]
permissive
# 升级 JuiceFS CSI Driver ## CSI Driver v0.10 及以上版本 JuiceFS CSI Driver 从 v0.10.0 开始将 JuiceFS 客户端与 CSI Driver 进行了分离,升级 CSI Driver 将不会影响已存在的 PV。如果你使用的是 CSI Driver v0.10.0 及以上的版本,执行以下命令进行升级: * 如果您使用的是 `nightly` 标签,只需运行 `kubectl rollout restart -f k8s.yaml` 并确保重启 `juicefs-csi-controller` 和 `juicefs-csi-node` pod。 * 如果您已固定到特定版本,请将您的 `k8s.yaml` 修改为要更新的版本,然后运行 `kubectl apply -f k8s.yaml`。 * 如果你的 JuiceFS CSI Driver 是使用 Helm 安装的,也可以通过 Helm 对其进行升级。 ## CSI Driver v0.10 以下版本 ### 小版本升级 升级 CSI Driver 需要重启 `DaemonSet`。由于 v0.10.0 之前的版本所有的 JuiceFS 客户端都运行在 `DaemonSet` 中,重启的过程中相关的 PV 都将不可用,因此需要先停止相关的 pod。 1. 停止所有使用此驱动的 pod。 2. 升级驱动: * 如果您使用的是 `latest` 标签,只需运行 `kubectl rollout restart -f k8s.yaml` 并确保重启 `juicefs-csi-controller` 和 `juicefs-csi-node` pod。 * 如果您已固定到特定版本,请将您的 `k8s.yaml` 修改为要更新的版本,然后运行 `kubectl apply -f k8s.yaml`。 * 如果你的 JuiceFS CSI Driver 是使用 Helm 安装的,也可以通过 Helm 对其进行升级。 3. 启动 pod。 ### 跨版本升级 如果你想从 CSI Driver v0.9.0 升级到 v0.10.0 及以上版本,请参考[这篇文档](upgrade-csi-driver-from-0.9-to-0.10.md)。 ### 其他 对于 v0.10.0 之前的版本,可以不升级 CSI Driver 仅升级 JuiceFS 客户端,详情参考[这篇文档](upgrade-juicefs.md)。 访问 [Docker Hub](https://hub.docker.com/r/juicedata/juicefs-csi-driver) 查看更多版本信息。
Markdown
UTF-8
762
2.75
3
[]
no_license
# letsvote This is a freecodecamp fullstack project. Detailed requirements see: https://www.freecodecamp.org/challenges/build-a-voting-app. This implemented all the user stories. This can be further improved: 1) Only logged in user can vote, and each user can only vote once in a given poll 2) More smooth UIs, esp the index file showing All polls and My polls 3) On All polls/My polls, change search box from enter to search to real time as one types - tried to do this using keyup to track search input box, but seems to generate a lot of actions 4) When openning each poll, add more graphic types (current only bar chart) 5) Mobile enable (d3 charts dont seem to appear using iphone) Then this will be a useful app. For now, just an exercise for learning.
C#
UTF-8
1,717
3.046875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Diagnostics; namespace JUtil { public static class JUtils { // courtesy of http://answers.unity.com/answers/893984/view.html public static T FindComponentInChildWithTag<T>(this GameObject parent, string tag) where T : Component { Transform t = parent.transform; foreach (Transform tr in t) { if (tr.tag == tag) { return tr.GetComponent<T>(); } } return null; } public static Vector2 Rotate(this Vector2 v, float degrees) { float radians = degrees * Mathf.Deg2Rad; float sin = Mathf.Sin(radians); float cos = Mathf.Cos(radians); float tx = v.x; float ty = v.y; return new Vector2(-1*(cos * tx - sin * ty), sin * tx + cos * ty); } public static float BetterSign(float value) { int temp = Mathf.RoundToInt(value); if (temp == 0) return 0f; return Mathf.Sign(value); } public static int BetterSign(int value) { if (value == 0) return 0; return (int)Mathf.Sign(value); } public static void ShowTime(double ticks, string message) { double milliseconds = (ticks / Stopwatch.Frequency) * 1000; double nanoseconds = (ticks / Stopwatch.Frequency) * 1000000000; UnityEngine.Debug.Log(message + "\n " + milliseconds + "ms" + " [" + nanoseconds + "ns]"); } } }