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
PHP
UTF-8
277
2.765625
3
[]
no_license
<?php class Pages extends IndirectObject { protected $pages = []; public function addPage(Page $page) { $this->pages[] = $page; } public function getMap() { return [ 'Type' => '/Pages', 'Kids' => $this->pages, 'Count' => count($this->pages), ]; } }
Markdown
UTF-8
3,662
3.15625
3
[ "MIT" ]
permissive
# `tslib` direct dependency migration # `tslib` 直接依赖项迁移 ## What does this migration do? ## 这种迁移是做什么的? If you have any libraries within your workspace, this migration will convert `tslib` peer dependencies to direct dependencies for the libraries. TypeScript uses the `tslib` package to provide common helper functions used in compiled TypeScript code. The `tslib` version is also updated to `2.0.0` to support TypeScript 3.9. 如果你的工作区中有任何库,此迁移会将它们对 `tslib` 的平级依赖转换为直接依赖。TypeScript 使用 `tslib` 包来提供 TypeScript 编译后代码中使用的常用辅助函数。`tslib` 版本也更新为 `2.0.0` 以支持 TypeScript 3.9。 Before: 之前: <code-example format="json" language="json"> { "name": "my-lib", "version": "0.0.1", "peerDependencies": { "&commat;angular/common": "^9.0.0", "&commat;angular/core": "^9.0.0", "tslib": "^1.12.0" } } </code-example> After: 之后: <code-example format="json" language="json"> { "name": "my-lib", "version": "0.0.1", "peerDependencies": { "&commat;angular/common": "^9.0.0", "&commat;angular/core": "^9.0.0" }, "dependencies": { "tslib": "^2.0.0" } } </code-example> ## Why is this migration necessary? ## 为何这次迁移必不可少? The [`tslib`](https://github.com/Microsoft/tslib) is a runtime library for Typescript. The version of this library is bound to the version of the TypeScript compiler used to compile a library. Peer dependencies do not accurately represent this relationship between the runtime and the compiler. If `tslib` remained declared as a library peer dependency, it would be possible for some Angular workspaces to get into a state where the workspace could not satisfy `tslib` peer dependency requirements for multiple libraries, resulting in build-time or run-time errors. [`tslib`](https://github.com/Microsoft/tslib) 是 Typescript 的运行时库。该库的版本绑定到了用于编译库的 TypeScript 编译器的版本。平级依赖不能准确表达此运行时库与编译器之间的这种关系。如果 `tslib` 仍然声明为库对等依赖项,则某些 Angular 工作区可能会出现工作区无法满足 `tslib` 平级依赖项要求的状态,从而导致构建期或运行期错误。 As of TypeScript 3.9 \(used by Angular v10\), `tslib` version of 2.x is required to build new applications. However, older libraries built with previous version of TypeScript and already published to npm might need `tslib` 1.x. This migration makes it possible for code depending on incompatible versions of the `tslib` runtime library to remain interoperable. 从 TypeScript 3.9(由 Angular v10 使用)开始,需要 `tslib` 版本 2.x 来构建新的应用程序。但是,使用以前的 TypeScript 版本构建并已发布到 npm 的较早的库可能需要 `tslib`。这种迁移使依赖于 `tslib` 运行时库的某个不兼容版本的代码可以保持互操作性。 ## Do I still need `tslib` as a dependency in my workspace `package.json`? ## 我是否仍需要 `tslib` 作为我的工作区 `package.json` 的依赖项? Yes. The `tslib` dependency declared in the `package.json` file of the workspace is used to build applications within this workspace, as well as run unit tests for workspace libraries, and is required. 是。`package.json` 文件中声明的 `tslib` 依赖用于在此工作区内构建应用程序,以及对工作区中的库进行运行单元测试,这是必要的。 <!-- links --> <!-- external links --> <!-- end links --> @reviewed 2022-02-28
Python
UTF-8
295
2.84375
3
[ "MIT" ]
permissive
from pynput.keyboard import Key, Controller import time time.sleep(5) Keyboard = Controller() while True: for letter in "Use it to Surprise NOT HARM": Keyboard.press(letter) Keyboard.release(letter) Keyboard.press(Key.enter) Keyboard.release(Key.enter)
C++
UTF-8
549
3.203125
3
[]
no_license
//Problem 7 #include <conio.h> #include <iostream> using namespace std; int main() { int x, y, sum; cout << "Input first number" << endl; cin >> x; cout << "Input last number" << endl; cin >> y; for ( int number = x; number <= y; number += x ) { sum += number; } cout << "The summation from "<<x<<" to "<<y<<" is " << sum << endl; _getch(); return 0; }
Python
UTF-8
6,852
3.015625
3
[]
no_license
from ArbolAVL.NodoEstudiante import Node import os class AVLTree: def __init__(self): self.root = None #add def add(self, carnet, dpi, nombre, carrera, correo, password, creditos, edad): self.root = self._add(carnet, dpi, nombre, carrera, correo, password, creditos, edad, self.root) def _add(self, carnet, dpi, nombre, carrera, correo, password, creditos, edad, tmp): if tmp is None: return Node( carnet, dpi, nombre, carrera, correo, password, creditos, edad) elif carnet>tmp.carnet: tmp.right=self._add(carnet, dpi, nombre, carrera, correo, password, creditos, edad, tmp.right) if (self.height(tmp.right)-self.height(tmp.left))==2: if carnet>tmp.right.carnet: tmp = self.srr(tmp) else: tmp = self.drr(tmp) else: tmp.left = self._add(carnet, dpi, nombre, carrera, correo, password, creditos, edad, tmp.left) if (self.height(tmp.left)-self.height(tmp.right))==2: if carnet<tmp.left.carnet: tmp = self.srl(tmp) else: tmp = self.drl(tmp) r = self.height(tmp.right) l = self.height(tmp.left) m = self.maxi(r, l) tmp.height = m+1 return tmp def height(self, tmp): if tmp is None: return -1 else: return tmp.height def maxi(self, r, l): return (l,r)[r>l] #rotations def srl(self, t1): t2 = t1.left t1.left = t2.right t2.right = t1 t1.height = self.maxi(self.height(t1.left), self.height(t1.right))+1 t2.height = self.maxi(self.height(t2.left), t1.height)+1 return t2 def srr(self, t1): t2 = t1.right t1.right = t2.left t2.left = t1 t1.height = self.maxi(self.height(t1.left), self.height(t1.right))+1 t2.height = self.maxi(self.height(t2.left), t1.height)+1 return t2 def drl(self, tmp): tmp.left = self.srr(tmp.left) return self.srl(tmp) def drr(self, tmp): tmp.right = self.srl(tmp.right) return self.srr(tmp) #traversals def preorder(self): cadena = self._preorder(self.root) file = open("Estudiantes.dot","w") file.write("digraph G {\n"+cadena+"\n}") file.close() os.system('dot -Tsvg Estudiantes.dot -o Estudiantes.svg') def _preorder(self, tmp): cadena = "" if tmp: #print(tmp.carnet,end = ' ') if tmp.left != None: cadena += str(tmp.carnet)+"[label=\""+str(tmp.carnet)+"\n"+tmp.nombre+"\" shape=box]\n" cadena += str(tmp.left.carnet)+"[label=\""+str(tmp.left.carnet)+"\n"+tmp.left.nombre+"\" shape=box]\n" cadena += str(tmp.carnet)+" -> "+str(tmp.left.carnet)+"\n" if tmp.right != None: cadena += str(tmp.carnet)+"[label=\""+str(tmp.carnet)+"\n"+tmp.nombre+"\" shape=box]\n" cadena += str(tmp.right.carnet)+"[label=\""+str(tmp.right.carnet)+"\n"+tmp.right.nombre+"\" shape=box]\n" cadena += str(tmp.carnet)+" -> "+str(tmp.right.carnet)+"\n" cadena += self._preorder(tmp.left) cadena += self._preorder(tmp.right) return cadena # Buscar def buscar(self,busqueda): return self.__buscar(self.root, busqueda) def __buscar(self, nodo, busqueda): if nodo is None: return None if nodo.carnet == busqueda: return nodo if busqueda < nodo.carnet: return self.__buscar(nodo.left, busqueda) else: return self.__buscar(nodo.right, busqueda) #Validar que el numero de carnet exista en el arbol def verificarEstudiante(self,busqueda): if self.__verificarEstudiante(self.root, busqueda): return True return False def __verificarEstudiante(self, nodo, busqueda): if nodo is None: return False if nodo.carnet == busqueda: return True if busqueda < nodo.carnet: return self.__verificarEstudiante(nodo.left, busqueda) else: return self.__verificarEstudiante(nodo.right, busqueda) # Modificar def modificar(self, carnet, dpi, nombre, carrera, correo, password, creditos, edad): self.__modificar(self.root, carnet, dpi, nombre, carrera, correo, password, creditos, edad) def __modificar(self, nodo, carnet, dpi, nombre, carrera, correo, password, creditos, edad): if nodo is None: return None if nodo.carnet == carnet: nodo.dpi = dpi nodo.nombre = nombre nodo.carrera = carrera nodo.correo = correo nodo.password = password nodo.creditos = creditos nodo.edad = edad if carnet < nodo.carnet: return self.__modificar(nodo.left, carnet, dpi, nombre, carrera, correo, password, creditos, edad) else: return self.__modificar(nodo.right, carnet, dpi, nombre, carrera, correo, password, creditos, edad) #Agregar Lista de años def agregarYears(self, carnet,years): self.__agregarYears(self.root, carnet, years) def __agregarYears(self, nodo, carnet, years): if nodo is None: return None if nodo.carnet == carnet: nodo.years = years if carnet < nodo.carnet: return self.__agregarYears(nodo.left, carnet, years) else: return self.__agregarYears(nodo.right, carnet, years) # Imprimir datos def imprimir(self): print("************* ARBOL *************") self._imprimir(self.root) def _imprimir(self, tmp): if tmp: print("Carnet: "+tmp.carnet) print("DPI: "+tmp.dpi) print("Nombre: "+tmp.nombre) print("Carrera: "+tmp.carrera) print("Correo: "+tmp.correo) print("Password: "+tmp.password) print("Creditos: "+str(tmp.creditos)) print("Edad: "+str(tmp.edad)) tmp.years.mostrarYears() self._imprimir(tmp.left) self._imprimir(tmp.right) #Retornar la lista de años def getYears(self,carnet): return self.__getYears(self.root, carnet) def __getYears(self, nodo, carnet): if nodo is None: return None if nodo.carnet == carnet: return nodo.years if carnet < nodo.carnet: return self.__getYears(nodo.left, carnet) else: return self.__getYears(nodo.right, carnet)
TypeScript
UTF-8
1,434
2.8125
3
[ "BSD-3-Clause" ]
permissive
import { MimeType_, URL_ } from "./datasets"; import { Converter, Convert } from "./converters"; import { DataTypeNoArgs, DataTypeStringArg, TypedConverter } from "./datatypes"; import { identity } from "rxjs"; /** * Datasets without a known mimetype start as just a resolve mimetype and no data. */ export const resolveDataType = new DataTypeNoArgs<void>( "application/x.jupyter.resolve" ); /** * Then, their mimetype is resolved. */ export const resolveMimetypeDataType = new DataTypeStringArg<void>( "application/x.jupyter.resolve", "mimetype" ); /** * Returns a set of possible mimetype for a URL_. */ export type Resolver = (url: URL_) => Set<MimeType_>; export function resolveConverter( resolver: Resolver ): TypedConverter<typeof resolveDataType, typeof resolveMimetypeDataType> { return resolveDataType.createTypedConverter( resolveMimetypeDataType, (_, url) => { const res = new Map<string, Convert<void, void>>(); for (const mimeType of resolver(url)) { res.set(mimeType, identity); } return res; } ); } /** * Creates a converter from a resolver mimetype to a file mimetype. */ export function resolveExtensionConverter( extension: string, mimeType: string ): Converter<void, void> { return resolveConverter((url: URL_) => { if (new URL(url).pathname.endsWith(extension)) { return new Set([mimeType]); } return new Set(); }); }
Java
UTF-8
735
3.28125
3
[]
no_license
import java.util.Arrays; import java.util.Scanner; public class Task4 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x = scanner.nextInt(); int [] array = new int[x]; for (int i = 0; i < array.length; i++) { array[i] = scanner.nextInt(); } int temp; for (int s = 0; s < array.length; s++) { for (int j = 0; j < array.length - 1; j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } System.out.println(Arrays.toString(array)); } }
PHP
UTF-8
1,867
2.625
3
[ "MIT" ]
permissive
<?php namespace TDN\NanaBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\Role\RoleInterface; /** * TDN\NanaBundle\Entity\NanaRoles */ class NanaRoles implements RoleInterface { /** * @var string $name */ private $name; /** * @var string $role */ private $role; /** * @var \Doctrine\Common\Collections\ArrayCollection */ private $groupe; public function __construct() { $this->groupe = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Set name * * @param string $name * @return NanaRoles */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set role * * @param string $role * @return NanaRoles */ public function setRole($role) { $this->role = $role; return $this; } /** * Get role * * @return string */ public function getRole() { return $this->role; } /** * Add groupe * * @param TDN\NanaBundle\Entity\Nana $groupe * @return NanaRoles */ public function addGroupe(\TDN\NanaBundle\Entity\Nana $groupe) { $this->groupe[] = $groupe; return $this; } /** * Remove groupe * * @param TDN\NanaBundle\Entity\Nana $groupe */ public function removeGroupe(\TDN\NanaBundle\Entity\Nana $groupe) { $this->groupe->removeElement($groupe); } /** * Get groupe * * @return Doctrine\Common\Collections\Collection */ public function getGroupe() { return $this->groupe; } }
Markdown
UTF-8
525
3.328125
3
[]
no_license
# 3 Types of Relationships in Database Design #### One-to-One A row in table "1" can can match with row in table "2" and vice versa. This is not commonly use , however this is used for security purposes ! #### One-to-Many A row in table '1' can have many match with row in table '2' , but a row in table '2' can have only one matching row in table '1'. #### Many-to-Many A row in table '1' can have many match with row in table '2' and vice versa.This design is linked with intermediary table(cross-reference table)
C#
UTF-8
468
2.75
3
[]
no_license
using System; using System.Collections.Generic; namespace TrieTests.TrieFolder { public class Node { public char Symbol { get; set; } public bool isWord { get; set; } = false; public List<Node> Descendants { get; set; } = new List<Node>(); public Node(char symbol) { Symbol = symbol; } public override string ToString() { return Symbol.ToString(); } } }
Java
UTF-8
891
2.015625
2
[]
no_license
package com.maoding.yongyoucloud.module.enterprise.dto; import java.util.List; public class EnterpriseDetailDTO { private String result; private String state; private Integer total; private List<EnterpriseDataDTO> details; public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public List<EnterpriseDataDTO> getDetails() { return details; } public void setDetails(List<EnterpriseDataDTO> details) { this.details = details; } }
TypeScript
UTF-8
247
2.9375
3
[]
no_license
class Programadores { private _programadores: Programador[] = []; adiciona(programador: Programador) { this._programadores.push(programador); } paraArray(){ return [].concat(this._programadores); } }
Java
UTF-8
3,436
2.546875
3
[ "Apache-2.0" ]
permissive
package com.theah64.ets.api.servlets; import com.theah64.ets.api.database.tables.BaseTable; import com.theah64.ets.api.database.tables.Companies; import com.theah64.ets.api.database.tables.Employees; import com.theah64.ets.api.models.Company; import com.theah64.ets.api.models.Employee; import com.theah64.ets.api.utils.APIResponse; import com.theah64.ets.api.utils.RandomString; import com.theah64.ets.api.utils.Request; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.annotation.WebServlet; /** * Created by theapache64 on 18/11/16,1:33 AM.if * route: /get_api_key * ------------------- * on_req: company_code,name, imei, fcm_id * on_resp: api_key */ @WebServlet(urlPatterns = {AdvancedBaseServlet.VERSION_CODE + "/get_api_key"}) public class GetAPIKeyServlet extends AdvancedBaseServlet { private static final int API_KEY_LENGTH = 10; private static final int EMP_CODE_LENGTH = 10; @Override protected boolean isSecureServlet() { return false; } @Override protected String[] getRequiredParameters() { return new String[]{Company.KEY_COMPANY_CODE, Employees.COLUMN_NAME, Employees.COLUMN_DEVICE_HASH, Employees.COLUMN_IMEI}; } @Override protected void doAdvancedPost() throws Request.RequestException, BaseTable.InsertFailedException, JSONException, BaseTable.UpdateFailedException { System.out.println("----------------------"); System.out.println("New api request received...."); final String companyCode = getStringParameter(Company.KEY_COMPANY_CODE); final String companyId = Companies.getInstance().get(Companies.COLUMN_CODE, companyCode, Companies.COLUMN_ID, true); if (companyId != null) { final String deviceHash = getStringParameter(Employees.COLUMN_DEVICE_HASH); final String fcmId = getStringParameter(Employees.COLUMN_FCM_ID); final Employees empTable = Employees.getInstance(); Employee emp = empTable.get(Employees.COLUMN_DEVICE_HASH, deviceHash); if (emp != null) { //EMP exist. if (fcmId != null) { //Updating fcm id empTable.update(Employees.COLUMN_ID, emp.getId(), Employees.COLUMN_FCM_ID, fcmId); } } else { //EMP doesn't exist. so create new one. final String name = getStringParameter(Employees.COLUMN_NAME); final String imei = getStringParameter(Employees.COLUMN_IMEI); final String apiKey = RandomString.getNewApiKey(API_KEY_LENGTH); final String empCode = RandomString.getRandomString(EMP_CODE_LENGTH); emp = new Employee(null, name, imei, deviceHash, fcmId, apiKey, companyId, empCode, null, true); final String empId = empTable.addv3(emp); emp.setId(empId); } System.out.println("Employee: " + emp); final JSONObject joData = new JSONObject(); joData.put(Employees.COLUMN_API_KEY, emp.getApiKey()); joData.put(Employees.COLUMN_ID, emp.getId()); //Finally showing api key getWriter().write(new APIResponse("Verified employee", joData).getResponse()); } else { throw new Request.RequestException("Company doesn't exist : " + companyCode); } } }
Java
UTF-8
8,832
1.882813
2
[]
no_license
package com.sinosoft.lis.bq; import org.apache.log4j.Logger; import com.sinosoft.lis.bl.LPContBL; import com.sinosoft.lis.db.LCAppntDB; import com.sinosoft.lis.db.LPAccountDB; import com.sinosoft.lis.db.LPEdorItemDB; import com.sinosoft.lis.db.LPEdorMainDB; import com.sinosoft.lis.pubfun.BqCalBase; import com.sinosoft.lis.pubfun.GlobalInput; import com.sinosoft.lis.pubfun.MMap; import com.sinosoft.lis.pubfun.PubFun; import com.sinosoft.lis.pubfun.PubFun1; import com.sinosoft.lis.schema.LPAccountSchema; import com.sinosoft.lis.schema.LPAppntSchema; import com.sinosoft.lis.schema.LPContSchema; import com.sinosoft.lis.schema.LPEdorItemSchema; import com.sinosoft.lis.schema.LPEdorMainSchema; import com.sinosoft.lis.vschema.LCAppntSet; import com.sinosoft.lis.vschema.LPAccountSet; import com.sinosoft.lis.vschema.LPContSet; import com.sinosoft.lis.vschema.LPEdorItemSet; import com.sinosoft.lis.vschema.LPEdorMainSet; import com.sinosoft.utility.CError; import com.sinosoft.utility.CErrors; import com.sinosoft.utility.Reflections; import com.sinosoft.utility.StrTool; import com.sinosoft.utility.VData; /** * <p> * Title: 缴费信息变更明细 * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2005 * </p> * <p> * Company: Sinosoft * </p> * * @author lizhuo * @version 1.0 */ public class PEdorPCDetailBL { private static Logger logger = Logger.getLogger(PEdorPCDetailBL.class); /** 错误处理类,每个需要错误处理的类中都放置该类 */ public CErrors mErrors = new CErrors(); /** 往后面传输数据的容器 */ private VData mInputData = null; /** 封装要操作的数据,以便一次提交 */ private MMap mMap = new MMap(); /** 往界面传输数据的容器 */ private VData mResult = new VData(); /** 数据操作字符串 */ private String mOperate; private BqCalBase mBqCalBase = new BqCalBase(); /** 全局数据 */ private LPEdorMainSet mLPEdorMainSet = new LPEdorMainSet(); private LPContSchema mLPContSchema = new LPContSchema(); private LPContSet mLPContSet = new LPContSet(); private LPEdorItemSchema mLPEdorItemSchema = new LPEdorItemSchema(); private GlobalInput mGlobalInput = new GlobalInput(); private LPAccountSchema mLPAccountSchema = new LPAccountSchema(); private Reflections ref = new Reflections(); public PEdorPCDetailBL() { } public boolean submitData(VData cInputData, String cOperate) { // 将操作数据拷贝到本类中 mInputData = (VData) cInputData.clone(); mOperate = cOperate; // 得到外部传入的数据,将数据备份到本类中 if (!getInputData()) { return false; } // 数据校验操作 if (!checkData()) { return false; } // 数据准备操作 if (!dealData()) { return false; } mResult.clear(); mResult.add(mBqCalBase); mResult.add(mMap); return true; } /** 获取前台数据 */ private boolean getInputData() { try { mLPEdorItemSchema = (LPEdorItemSchema) mInputData .getObjectByObjectName("LPEdorItemSchema", 0); mGlobalInput = (GlobalInput) mInputData.getObjectByObjectName( "GlobalInput", 0); mLPContSchema = (LPContSchema) mInputData.getObjectByObjectName( "LPContSchema", 0); mLPAccountSchema = (LPAccountSchema) mInputData .getObjectByObjectName("LPAccountSchema", 0); if (mGlobalInput == null || mLPEdorItemSchema == null || mLPContSchema == null || mLPAccountSchema == null) { return false; } } catch (Exception e) { CError.buildErr(this, "接收数据失败"); return false; } return true; } /** * 校验传入的数据的合法性 输出:如果发生错误则返回false,否则返回true */ private boolean checkData() { boolean flag = true; LPEdorItemDB tLPEdorItemDB = new LPEdorItemDB(); if (this.getOperate().equals("UPDATE||MAIN")) { tLPEdorItemDB.setContNo(mLPEdorItemSchema.getContNo()); tLPEdorItemDB.setEdorNo(mLPEdorItemSchema.getEdorNo()); tLPEdorItemDB.setEdorType(mLPEdorItemSchema.getEdorType()); // 获取保全主表数据,节省查询次数 mLPEdorItemSchema.setSchema(tLPEdorItemDB.query().get(1)); // if (!mLPEdorItemSchema.getEdorState().trim().equals("1") && // !mLPEdorItemSchema.getEdorState().trim().equals("3")) // { // // @@错误处理 // CError tError = new CError(); // tError.moduleName = "PEdorIODetailBL"; // tError.functionName = "Preparedata"; // tError.errorMessage = "该保全已经申请确认不能修改!"; // this.mErrors.addOneError(tError); // return false; // } } return flag; } /** * 准备需要保存的数据 */ private boolean dealData() { boolean flag = true; LPContBL tLPContBL = new LPContBL(); if (!tLPContBL.queryLPCont(mLPEdorItemSchema)) { CError.buildErr(this, "查询合同保单信息失败!"); return false; } tLPContBL.setEdorNo(mLPContSchema.getEdorNo()); tLPContBL.setEdorType(mLPContSchema.getEdorType()); // tLPContBL.setContNo(mLPContSchema.getContNo()); tLPContBL.setPayLocation(mLPContSchema.getPayLocation()); // XinYQ Modified on 2007-04-26 : 银保通采用 PayMode 标识, 这里去掉 // tLPContBL.setPayMode(mLPContSchema.getPayLocation()); tLPContBL.setBankCode(mLPContSchema.getBankCode()); tLPContBL.setBankAccNo(mLPContSchema.getBankAccNo()); tLPContBL.setAccName(mLPContSchema.getAccName()); tLPContBL.setModifyDate(PubFun.getCurrentDate()); tLPContBL.setModifyTime(PubFun.getCurrentTime()); mLPContSet.add(tLPContBL.getSchema()); mMap.put(mLPContSet, "DELETE&INSERT"); // 加入Map if (mLPContSchema.getPayLocation().equals("0"))// 银行转帐方式 { LPAccountSet tLPAccountSet = new LPAccountSet(); LPAccountDB tLPAccountDB = new LPAccountDB(); tLPAccountDB.setEdorNo(mLPAccountSchema.getEdorNo()); tLPAccountDB.setEdorType(mLPAccountSchema.getEdorType()); tLPAccountDB.setCustomerNo(mLPAccountSchema.getCustomerNo()); tLPAccountDB.setBankCode(mLPAccountSchema.getBankCode()); tLPAccountDB.setBankAccNo(mLPAccountSchema.getBankAccNo()); if (!tLPAccountDB.getInfo()) { tLPAccountDB.setAccKind("Y"); tLPAccountDB.setAccName(mLPAccountSchema.getAccName()); tLPAccountDB.setOperator(mGlobalInput.Operator); tLPAccountDB.setMakeDate(PubFun.getCurrentDate()); tLPAccountDB.setMakeTime(PubFun.getCurrentTime()); tLPAccountDB.setModifyDate(PubFun.getCurrentDate()); tLPAccountDB.setModifyTime(PubFun.getCurrentTime()); tLPAccountSet.add(tLPAccountDB.getSchema()); mMap.put(tLPAccountSet, "INSERT"); } else { tLPAccountSet.add(tLPAccountDB.getSchema()); mMap.put(tLPAccountSet, "DELETE&INSERT"); } LCAppntDB tLCAppntDB = new LCAppntDB(); LCAppntSet tLCAppntSet = new LCAppntSet(); tLCAppntDB.setContNo(mLPEdorItemSchema.getContNo()); tLCAppntSet = tLCAppntDB.query(); LPAppntSchema tLPAppntSchema = new LPAppntSchema(); ref.transFields(tLPAppntSchema, tLCAppntSet.get(1)); tLPAppntSchema.setEdorNo(mLPEdorItemSchema.getEdorNo()); tLPAppntSchema.setEdorType(mLPEdorItemSchema.getEdorType()); tLPAppntSchema.setAccName(mLPAccountSchema.getAccName()); tLPAppntSchema.setBankAccNo(mLPAccountSchema.getBankAccNo()); tLPAppntSchema.setBankCode(mLPAccountSchema.getBankCode()); mMap.put(tLPAppntSchema, "DELETE&INSERT"); } mLPEdorItemSchema.setEdorState("3"); mMap.put(mLPEdorItemSchema, "UPDATE"); LPEdorMainDB tLPEdorMainDB = new LPEdorMainDB(); tLPEdorMainDB.setContNo(mLPContSchema.getContNo()); tLPEdorMainDB.setEdorNo(mLPEdorItemSchema.getEdorNo()); tLPEdorMainDB.setEdorAcceptNo(mLPEdorItemSchema.getEdorAcceptNo()); if (!tLPEdorMainDB.getInfo()) { if (tLPEdorMainDB.mErrors.needDealError()) { CError.buildErr(this, "查询保单号为" + tLPEdorMainDB.getContNo() + "的保单批单信息时失败!"); return false; } else { LPEdorMainSchema tLPEdorMainSchema = new LPEdorMainSchema(); ref.transFields(tLPEdorMainSchema, mLPEdorItemSchema); String strLimit = PubFun.getNoLimit(mGlobalInput.ManageCom); String strEdorNo = PubFun1.CreateMaxNo("EdorAppNo", strLimit); if (StrTool.compareString(strEdorNo, "")) { CError.buildErr(this, "生成保全批单号错误!"); return false; } tLPEdorMainSchema.setEdorNo(strEdorNo); tLPEdorMainDB.setEdorNo(strEdorNo); tLPEdorMainSchema.setEdorAppNo(strEdorNo); tLPEdorMainSchema.setContNo(mLPContSchema.getContNo()); tLPEdorMainSchema.setUWState("0"); mLPEdorMainSet.add(tLPEdorMainSchema); mMap.put(mLPEdorMainSet, "INSERT"); } } mBqCalBase.setContNo(mLPEdorItemSchema.getContNo()); return flag; } /** * getOperate * * @return String */ private String getOperate() { return mOperate; } /** * getResult * * @return VData */ public VData getResult() { return mResult; } }
TypeScript
UTF-8
499
2.859375
3
[]
no_license
export class UUID { public static newUUID(): string { return this.generateUUID(); } private static generateUUID(): string { return this.generatePart() + this.generatePart() + '-' + this.generatePart() + '-' + this.generatePart() + '-' + this.generatePart() + '-' + this.generatePart() + this.generatePart() + this.generatePart(); } private static generatePart(): string { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } }
Java
UTF-8
818
3.34375
3
[]
no_license
/* * This Java source file was generated by the Gradle 'init' task. */ package SortUsingStream; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Test; import junit.framework.Assert; public class SortServiceTest { /* This project will contain test kata that demonstrate * how to leverage Java 8 Streams to manage Sorting of various Collections */ // First, start with a simple ArrayList with 3 integers and expect a sorted list of string @Test public void SortSimpleArray() { List<Integer> simpleList = new ArrayList<Integer>(); simpleList.add(4); simpleList.add(2); simpleList.add(20); String expected = "2,4,20"; String actual = SortService.sortListAsString(simpleList); assertTrue(expected.equals(actual)); } }
C++
MacCentralEurope
397
2.984375
3
[]
no_license
#pragma once #include "VisiteurVerbe.h" /** conjugue les verbes au participe pass Ex : pour le verbe "danser", on obtient "dans" pour le verbe "grandir", on obtient "grandi" */ class ParticipePasse : public VisiteurVerbe { public: const static char eAccentAigu; // const string visite(const Verbe1erGroupe * verbe) const; const string visite(const Verbe2emeGroupe * verbe) const; };
Markdown
UTF-8
10,510
2.6875
3
[]
no_license
# Lawn Care Simulator (Web, 200pts) ## Problem Lawn Care Simulator is a simple web application to show how the grass is growing. Yeah, ok. It has premium content, but it requires registration. Registration not working and there's no way to log in as we can't register any account. ![Lawn Care Simulator] (https://github.com/bl4de/ctf/blob/master/2015/CSAW_CTF_2015/Lawn_Care_Simulator_web200/lawncare01.png) ## Solution ### Phase 1 - explore .git repository In source code of index.html there's an AJAX request to Git repository (to find current application version). So we can exploit .git folder on remote server. Following SHA-1 Git objects hash, we can find and download source files (not all, unfortunately): Here's tree hash: ``` $ git cat-file -p aa3025bdb15120ad0a2558246402119ce11f4e2e tree 731924d14616f3f95c1d75e822a6a97a69f1a32f author John G <john@lawncaresimulator2015thegame.com> 1442602067 +0000 committer John G <john@lawncaresimulator2015thegame.com> 1442602067 +0000 I think I'll just put mah source code riiiiighhhht here. Perfectly safe place for some source code. ``` And here's tree content: ``` $ git cat-file -p 731924d14616f3f95c1d75e822a6a97a69f1a32f 100644 blob 4bcb0b3cf55c14b033e3d7e0a94b6025f6956ec7 ___HINT___ 100644 blob 43d1df004d9cf95f2c5d83d2db3dcf887c7a9f2f index.html 100644 blob 27d808506876eeb41d6a953ac27f33566216d25f jobs.html 040000 tree 220a9334b01b77d1ac29b7fd3a35c6a18953a96d js 100644 blob 73009145aac48cf1d0e72adfaa093de11f491715 premium.php 100644 blob 8e4852023815dc70761e38cde28aebed9ec038e3 sign_up.php 100644 blob 637c8e963a5fb7080ff639b5297bb10bca491bda validate_pass.php ``` File HINT does not contain anything helpful. But as we can analyze source code of some files and after a few minutes of reading it, we can identify some key points: * registration is NOT working, BUT we can try guess/find already existing username(s): ```php $user = mysql_real_escape_string($_POST['username']); // check to see if the username is available $query = "SELECT username FROM users WHERE username LIKE '$user';"; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); $line = mysql_fetch_row($result, MYSQL_ASSOC); if ($line == NULL){ // Signing up for premium is still in development echo '<h2 style="margin: 60px;">Lawn Care Simulator 2015 is currently in a private beta. Please check back later</h2>'; } else { echo '<h2 style="margin: 60px;">Username: ' . $line['username'] . " is not available</h2>"; } ``` * login is working, but we have to find valid username and try to pass login validation. After succesful login we will be able to get the flag: ```php require_once 'validate_pass.php'; require_once 'flag.php'; if (isset($_POST['password']) && isset($_POST['username'])) { $auth = validate($_POST['username'], $_POST['password']); if ($auth){ echo "<h1>" . $flag . "</h1>"; } else { echo "<h1>Not Authorized</h1>"; } } else { echo "<h1>You must supply a username and password</h1>"; } ``` ### Phase 2 - find username Let's get throug these lines (sign_up.php): ```php $user = mysql_real_escape_string($_POST['username']); // check to see if the username is available $query = "SELECT username FROM users WHERE username LIKE '$user';"; ``` First of all - mysql_real_escape_string() does not allow SQL Injection here. But as we can see, we can try to use special chars for LIKE (% or _), which are NOT ESCAPED by mysql_real_escape_string(). So when we try to register with username eg. '%%', we see this screen: We have existing username, now we have to try to find the password. ![Got username] (https://github.com/bl4de/ctf/blob/master/2015/CSAW_CTF_2015/Lawn_Care_Simulator_web200/lawncare02.png) ### Phase 3 - bruteforce password validation Validation of password looks a little bit tricky at the first look: ```php if (strlen($pass) != strlen($hash)) return False; $index = 0; while($hash[$index]){ if ($pass[$index] != $hash[$index]) return false; # Protect against brute force attacks usleep(300000); $index+=1; } return true; ``` *$hash* is value from DB and *$pass* is MD5 hash of password from login form. First check is the length - if the length of $pass not equals the length of $hash, validation returns false. So even if we spoof login form we still have to send 32 signs (MD5 hash). Then script checks sign by sign if $hash and $pass are equal and it returns false right after first difference. If signs are the same, it waits 0.3 sec before next check. And this is exactly what we need to bruteforce this validation. Assuming that any valid sign took about 0.3 sec break before next sign, we can compare requests time for every single character allowed in MD5 string starting from first character (any hex digit in this case). I've created simple Python script for this. It just creates 32 characters string starting from 0 through f and sending it to the server. Then we can check if there's character which causes a little bit longer response: ```python #!/usr/bin/python import requests import sys headers = { "Referer": "http://54.175.3.248:8089/", "Content-type": "application/x-www-form-urlencoded", "Host": "54.175.3.248:8089" } def send_request(current_password): payload = {"username": "~~FLAG~~", "password": current_password} r = requests.post("http://54.175.3.248:8089/premium.php", headers=headers, data=payload) return r.elapsed.total_seconds() charset = "abcdef0123456789" final_password = sys.argv[1] current_password = "" s = "" for c in charset: current_password = final_password + c + "-" * (31 - len(final_password)) # send payload and check response time, avg from 3 probes print "sending payload with password: {}".format(current_password) t = send_request(current_password) print "time for {} - {}".format(c, t) final_password += s print "\n\ncurrent final password: {} ({} chars)\n\n".format(final_password, len( final_password)) ``` It took some time, but finally I was able to find 10 first characters in MD5 hash of FLAG user password - and when I've sent it I've got the flag. Below are console outputs from sample try after three signs (667) - script shows 4th sign, which is 'e' - timing is ~0.3s more than average, then one of the final try with 667e217666 as the beginning, when times were not changing anymore: ``` $ ./pass_time_check.py 667 sending payload with password: 667a---------------------------- time for a - 1.206054 sending payload with password: 667b---------------------------- time for b - 1.1628 sending payload with password: 667c---------------------------- time for c - 1.123849 sending payload with password: 667d---------------------------- time for d - 1.123673 sending payload with password: 667e---------------------------- time for e - 1.533342 sending payload with password: 667f---------------------------- time for f - 1.123596 sending payload with password: 6670---------------------------- time for 0 - 1.12424 sending payload with password: 6671---------------------------- time for 1 - 1.139995 sending payload with password: 6672---------------------------- time for 2 - 1.209023 sending payload with password: 6673---------------------------- time for 3 - 1.122856 sending payload with password: 6674---------------------------- time for 4 - 1.123731 sending payload with password: 6675---------------------------- time for 5 - 1.124603 sending payload with password: 6676---------------------------- time for 6 - 1.122691 sending payload with password: 6677---------------------------- time for 7 - 1.12402 sending payload with password: 6678---------------------------- time for 8 - 1.123192 sending payload with password: 6679---------------------------- time for 9 - 1.1241 $ ./pass_time_check.py 667e217666 sending payload with password: 667e217666a--------------------- time for a - 3.317382 sending payload with password: 667e217666b--------------------- time for b - 3.274132 sending payload with password: 667e217666c--------------------- time for c - 3.376334 sending payload with password: 667e217666d--------------------- time for d - 3.273846 sending payload with password: 667e217666e--------------------- time for e - 3.274608 sending payload with password: 667e217666f--------------------- time for f - 3.27328 sending payload with password: 667e2176660--------------------- time for 0 - 3.213485 sending payload with password: 667e2176661--------------------- time for 1 - 3.234123 sending payload with password: 667e2176662--------------------- time for 2 - 3.272356 sending payload with password: 667e2176663--------------------- time for 3 - 3.274707 sending payload with password: 667e2176664--------------------- time for 4 - 3.27386 sending payload with password: 667e2176665--------------------- time for 5 - 3.272986 sending payload with password: 667e2176666--------------------- time for 6 - 3.27506 sending payload with password: 667e2176667--------------------- time for 7 - 3.274545 sending payload with password: 667e2176668--------------------- time for 8 - 3.273122 sending payload with password: 667e2176669--------------------- time for 9 - 3.290462 ``` After *667e217666* time of responses stopped to change, so I've decided to try only with this (I've added some random chars to get 32 characters length of the whole hash) - and it was enough: ![Grab the flag] (https://github.com/bl4de/ctf/blob/master/2015/CSAW_CTF_2015/Lawn_Care_Simulator_web200/lawncare03.png) And the flag was: *gr0wth__h4ck!nG!1!1!* (I don't know why it has worked just after 10 characters, but I suppose that there was some kind of pre-validation, which was not visible in the code and CTF organizers were able to determine valid solution a little bit earlier than after all guessed hash.) ## Other solutions Very similar approach from _smoke leet everyday_ team: https://github.com/smokeleeteveryday/CTF_WRITEUPS/tree/master/2015/CSAWCTF/web/lawncaresimulator And totaly different and much more straightforward from _Alpackers_: https://github.com/Alpackers/CTF-Writeups/tree/master/2015/CSAW-CTF/Web/Lawn-Care-Simulator
Java
UTF-8
3,494
2.0625
2
[]
no_license
package com.okar.chatservice; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.okar.app.ICZApplication; import com.okar.entry.Body; import com.okar.entry.Packet; import com.okar.entry.UserBody; import com.okar.receiver.AuthReceiveBroadCast; import com.okar.utils.Constants; import com.works.skynet.base.BaseActivity; import roboguice.inject.InjectView; import static com.okar.utils.Constants.CHAT_SERVICE; import static com.okar.utils.Constants.REV_AUTH_FLAG; import static com.okar.app.ICZApplication.C; /** * Created by wangfengchen on 15/1/15. */ public class LoginActivity extends BaseActivity { @InjectView(R.id.login_edit_username) EditText usernameEt; @InjectView(R.id.login_edit_password) EditText passwordEt; @InjectView(R.id.login_submit) Button submitBtn; @InjectView(R.id.login_2_register) Button toRegisterBtn; private IChatService chatService; private AuthReceiveBroadCast authReceiveBroadCast; private ServiceConnection serConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { chatService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { chatService = IChatService.Stub.asInterface(service); } }; @Override protected void init() { setContentView(R.layout.activity_login); Intent intent = new Intent(CHAT_SERVICE); bindService(intent, serConn, Service.BIND_AUTO_CREATE); authReceiveBroadCast = new AuthReceiveBroadCast(this); IntentFilter filter = new IntentFilter(); filter.addAction(REV_AUTH_FLAG); //只有持有相同的action的接受者才能接收此广播 registerReceiver(authReceiveBroadCast, filter); } @Override protected void onListener() { submitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Packet packet = new Packet(Packet.LOGIN_TYPE); String username = usernameEt.getText().toString(); String password = passwordEt.getText().toString(); packet.body = new UserBody(username, password); C.put(Constants.I_USERNAME, username); C.put(Constants.I_PASSWORD, password); try { chatService.sendPacket(packet); } catch (RemoteException e) { e.printStackTrace(); } } }); toRegisterBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(intent); } }); } @Override protected void onDestroy() { super.onDestroy(); unbindService(serConn); unregisterReceiver(authReceiveBroadCast);//取消广播 } @Override public void onClick(View view) { } }
C++
UTF-8
438
3.421875
3
[]
no_license
/* * * アルゴリズム 再帰関数 * 参考:https://qiita.com/drken/items/23a4f604fa3f505dd5ad * */ #include <iostream> using namespace std; int func(int i){ if(i == 0) return 0; return i + func(i-1); } int main(){ int n; cout << endl; cout << "nまでの値の和を表示します:nの値を入力してください" << endl; cin >> n; cout << n << "までの値の和 : " << func(n) << endl; }
C++
UTF-8
519
2.90625
3
[]
no_license
/* * Exception.cpp * * Created on: 05.01.2013 * Author: yoshi252 */ #include "Exception.h" namespace blobby { /** * Constructor * * \param [in] message The message of the exception. Will be returned by what(). */ Exception::Exception(const std::string& message) : m_message(message) { } /** * Destructor */ Exception::~Exception() throw() { } /** * @return The message of the exception. */ const char* Exception::what() const throw() { return m_message.c_str(); } } // namespace blobby
SQL
UTF-8
5,767
3.0625
3
[ "MIT" ]
permissive
/* SQL setup script for AWS Services Snapshot utility v0.0.8 This script sets up the PostgreSQL database 'aws_snapshot' for use by the AWS Services Snapshot utility >> Note: this script must be executed using the 'ec2-user' role << ------------------------------------------------------------------------------------ MIT License Copyright (c) 2018 Enterprise Group, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------------ */ /* create aws_sps__commands schema */ CREATE SCHEMA IF NOT EXISTS aws_sps__commands ; /* create driver_aws_services table */ DROP TABLE IF EXISTS aws_sps__commands._postgresql_reserved_words ; CREATE TABLE aws_sps__commands._postgresql_reserved_words( key_id SERIAL PRIMARY KEY , reserved_words TEXT NOT NULL ); /* create driver_aws_services table */ DROP TABLE IF EXISTS aws_sps__commands._driver_aws_services ; CREATE TABLE aws_sps__commands._driver_aws_services( key_id SERIAL PRIMARY KEY , aws_service TEXT NOT NULL , execute_yn TEXT NOT NULL , global_aws_service_yn TEXT NOT NULL , driver_ver TEXT NOT NULL , driver_tested_yn TEXT NOT NULL , driver_all_ok_yn TEXT NOT NULL , aws_service_comment TEXT NOT NULL ); /* create driver_aws_cli_commands table */ DROP TABLE IF EXISTS aws_sps__commands._driver_aws_cli_commands ; CREATE TABLE aws_sps__commands._driver_aws_cli_commands( key_id SERIAL PRIMARY KEY , aws_service TEXT NOT NULL , aws_cli_command TEXT NOT NULL , execute_yn TEXT NOT NULL , recursive_yn TEXT NOT NULL , test_ok_yn TEXT NOT NULL , command_comment TEXT NOT NULL ); /* create driver_aws_cli_commands_recursive table */ DROP TABLE IF EXISTS aws_sps__commands._driver_aws_cli_commands_recursive ; CREATE TABLE aws_sps__commands._driver_aws_cli_commands_recursive( key_id SERIAL PRIMARY KEY , aws_service TEXT NOT NULL , aws_cli_command TEXT NOT NULL , parameter_source_aws_service TEXT NOT NULL , parameter_source_aws_cli_command TEXT NOT NULL , parameter_source_key TEXT NOT NULL , recursive_dependent_yn TEXT NOT NULL , parameter_multi_yn TEXT NOT NULL , parameter_count TEXT NOT NULL , parameter_source_table_multi_yn TEXT NOT NULL , parameter_source_table_count TEXT NOT NULL , command_parameter TEXT NOT NULL , parameter_key_hardcode_yn TEXT , parameter_key_hardcode_value TEXT , test_ok_yn TEXT , command_recursive_comment TEXT , recursive_yn TEXT NOT NULL , execute_yn TEXT NOT NULL , recursive_multi_dependent_yn TEXT NOT NULL , command_repeated_yn TEXT NOT NULL , command_recursive_table TEXT NOT NULL , parameter_source_table TEXT NOT NULL , parameter_source_attribute TEXT NOT NULL , parameter_source_join_attribute TEXT NOT NULL , command_repeated_hardcoded_yn TEXT , command_repeated_hardcoded_prior TEXT , command_repeated_hardcoded_after TEXT , join_type TEXT , command_recursive TEXT , command_recursive_header TEXT , command_recursive_1 TEXT , command_recursive_2 TEXT , command_recursive_3 TEXT , command_recursive_4 TEXT , command_recursive_5 TEXT , command_recursive_6 TEXT , command_recursive_7 TEXT , command_recursive_8 TEXT , parameter_01_source_table TEXT , parameter_02_source_table TEXT , parameter_03_source_table TEXT , parameter_04_source_table TEXT , parameter_05_source_table TEXT , parameter_06_source_table TEXT , parameter_07_source_table TEXT , parameter_08_source_table TEXT , parameter_01_source_key TEXT , parameter_02_source_key TEXT , parameter_03_source_key TEXT , parameter_04_source_key TEXT , parameter_05_source_key TEXT , parameter_06_source_key TEXT , parameter_07_source_key TEXT , parameter_08_source_key TEXT , command_recursive_single_query TEXT , command_recursive_multi_query TEXT , query_1_param TEXT , query_name TEXT , query_drop TEXT , query_create_build TEXT , query_create_header TEXT , query_create_1 TEXT , query_create_2 TEXT , query_create_3 TEXT , query_create_4 TEXT , query_create_5 TEXT , query_create_6 TEXT , query_create_7 TEXT , query_create_8 TEXT , query_create_tail TEXT , query_insert_build TEXT , query_insert_header TEXT , query_insert_1 TEXT , query_insert_2 TEXT , query_insert_3 TEXT , query_insert_4 TEXT , query_insert_5 TEXT , query_insert_6 TEXT , query_insert_7 TEXT , query_insert_8 TEXT , query_insert_tail TEXT , query_select_build TEXT , query_select_header TEXT , query_select_2 TEXT , query_select_3 TEXT , query_select_4 TEXT , query_select_5 TEXT , query_select_6 TEXT , query_select_7 TEXT , query_select_8 TEXT , query_from TEXT , query_from_2 TEXT , query_from_3 TEXT , query_from_4 TEXT , query_from_5 TEXT , query_from_6 TEXT , query_from_7 TEXT , query_from_8 TEXT , query_tail TEXT ) ;
Python
UTF-8
2,222
2.84375
3
[]
no_license
# Design: boot_script.py # Description: # Author: German Cano Quiveu <germancq@dte.us.es> # Copyright Universidad de Sevilla, Spain import sys import binascii import collections elf_signature = binascii.unhexlify(b'7F454C46') PH_info = collections.namedtuple('PH_info','offset sz vaddr') def from_bytes (data, big_endian = True): if isinstance(data, str): data = bytearray(data) if big_endian: data = reversed(data) num = 0 for offset, byte in enumerate(data): num += byte << (offset * 8) return num def compare_elf_signature(i_file): i_file.seek(0) i_elf = i_file.read(4) if i_elf == elf_signature : return True else: print("Not elf file") sys.exit(2) def getPHoffset(i_file): i_file.seek(28) i_ph_offset = i_file.read(4) return from_bytes(i_ph_offset) def getNumberPH(i_file): i_file.seek(44) numPH = i_file.read(2) return from_bytes(numPH) def getDataPH(i_file,offset,index): #Program Header size is 32 bytes startPH = offset + (32*index) #offset of the segment in the file image i_file.seek(startPH + 4) ph_offset = i_file.read(4) #size in bytes in the file image i_file.seek(startPH + 16) ph_filesz = i_file.read(4) #virtual address i_file.seek(startPH + 8) ph_vaddr = i_file.read(4) return PH_info(offset = from_bytes(ph_offset),sz = from_bytes(ph_filesz), vaddr = from_bytes(ph_vaddr)) def writePH(i_file,o_file,info_ph): if(o_file.tell() < info_ph.offset): for x in range (o_file.tell(),info_ph.vaddr): o_file.write(b"\x00") i_file.seek(info_ph.offset) o_file.seek(info_ph.vaddr) o_file.write(i_file.read(info_ph.sz)) def alignTo512(o_file): sz = o_file.tell()#current position mod512 = sz % 512 for x in range (0, 512-mod512): o_file.write(b"\x00") print(o_file.tell()/512) def main(): with open(sys.argv[1],"rb") as input_file: with open(sys.argv[2], "wb") as output_file: compare_elf_signature(input_file) program_header_offset = getPHoffset(input_file) program_header_number = getNumberPH(input_file) for k in range (0, program_header_number): info = getDataPH(input_file,program_header_offset,k) writePH(input_file,output_file,info) alignTo512(output_file) if __name__ == "__main__": main()
C#
UTF-8
2,620
3.015625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Data.SqlClient; namespace _30Aralik08 { public class Product { public Product() { } int productID; public int ProductID { get { return productID; } //set { productID = value; } } string productName; public string ProductName { get { return productName; } set { productName = value; } } string productDesc; public string ProductDesc { get { return productDesc; } set { productDesc = value; } } decimal price; public decimal Price { get { return price; } set { price = value; } } int categID; public int CategID { get { return categID; } set { categID = value; } } string categoryName; public string CategoryName { get { return categoryName; } set { categoryName = value; } } public static ArrayList GetAllProducts() { SqlConnection con = new SqlConnection("Server = .; Database = DoxaBilgisayar; trusted_Connection = Yes"); ConOpen(con); SqlCommand cmd = new SqlCommand("select P.ProductID, P.ProductName, P.ProductDesc, P.Price,C.CategoryID,C.CategoryName from Product P inner join Category C on P.CategoryID = C.CategoryID",con); SqlDataReader rdr = cmd.ExecuteReader(); ArrayList myResultList = new ArrayList(); while (rdr.Read()) { Product prd = new Product(); prd.productID = Convert.ToInt32(rdr[0]); prd.productName = rdr[1].ToString(); prd.productDesc = rdr[2].ToString(); prd.price = Convert.ToDecimal(rdr[3]); prd.categID = Convert.ToInt32(rdr[4]); prd.categoryName = rdr[5].ToString(); myResultList.Add(prd); } return myResultList; } private static void ConOpen(SqlConnection con) { if (con.State == System.Data.ConnectionState.Closed) { con.Open(); } } private static void ConClose(SqlConnection con) { if (con.State == System.Data.ConnectionState.Open) { con.Close(); } } } }
Python
UTF-8
193
3.15625
3
[]
no_license
temp_viagem = int(input('temp_viagem: ')) velocidade_media = float(input('velocidade_media: ')) distancia = velocidade_media * temp_viagem cosumo = distancia / 12 print('%.3f' % cosumo)
Shell
UTF-8
1,430
3.734375
4
[]
no_license
#!/bin/bash # Setup vars source .env DID=$(docker ps -aqf "name=cuckoo-docker_cuckoo") DPID=$(docker inspect -f '{{.State.Pid}}' $DID) VNET=vboxnet0 echo "Container ID is $DID" echo "DPID is $DPID" function test_root() { if [ "$EUID" -ne 0 ] then echo "Please run as root" exit fi } test_root function setup_vpn() { docker exec -ti $DID /bin/bash -c "cp /root/conf/openvpn/.auth /etc/openvpn/" docker exec -ti $DID /bin/bash -c "cp /root/conf/openvpn/$OVPN_CONFIG.conf /etc/openvpn/client/" docker exec -ti $DID /bin/bash -c "systemctl start openvpn-client@$OVPN_CONFIG.service" docker exec -ti $DID /bin/bash -c "systemctl status --no-pager openvpn-client@$OVPN_CONFIG.service" docker exec -ti $DID /bin/bash -c "systemctl restart iptables.service" docker exec -ti $DID /bin/bash -c "systemctl status --no-pager iptables.service" docker exec -ti $DID /bin/bash -c "/root/conf/openvpn/iptables.sh" } function setup_network() { # Networking: create new namespace mkdir -p /var/run/netns rm /var/run/netns/$DPID ln -s /proc/$DPID/ns/net /var/run/netns/$DPID ip link set $VNET netns $DPID docker exec -ti $DID /bin/bash -c "VBoxManage list hostonlyifs" docker exec -ti $DID /bin/bash -c "ip addr add 192.168.56.1/24 dev vboxnet0" docker exec -ti $DID /bin/bash -c "ip link set vboxnet0 up" docker exec -ti $DID /bin/bash -c "ip a" setup_vpn }
Markdown
UTF-8
25
2.640625
3
[]
no_license
# JS Simple JS exercises
C#
UTF-8
2,515
2.546875
3
[]
no_license
namespace AForge.Imaging.ColorReduction { public class ColorErrorDiffusionToAdjacentNeighbors : ErrorDiffusionColorDithering { private int[][] coefficients; private int coefficientsSum; public int[][] Coefficients { get { return coefficients; } set { coefficients = value; CalculateCoefficientsSum(); } } public ColorErrorDiffusionToAdjacentNeighbors(int[][] coefficients) { this.coefficients = coefficients; CalculateCoefficientsSum(); } protected unsafe override void Diffuse(int rError, int gError, int bError, byte* ptr) { int[] array = coefficients[0]; int num = 1; int num2 = pixelSize; int num3 = 0; int num4 = array.Length; while (num3 < num4 && x + num < width) { int num5 = ptr[num2 + 2] + rError * array[num3] / coefficientsSum; num5 = ((num5 >= 0) ? ((num5 > 255) ? 255 : num5) : 0); ptr[num2 + 2] = (byte)num5; int num6 = ptr[num2 + 1] + gError * array[num3] / coefficientsSum; num6 = ((num6 >= 0) ? ((num6 > 255) ? 255 : num6) : 0); ptr[num2 + 1] = (byte)num6; int num7 = ptr[num2] + bError * array[num3] / coefficientsSum; num7 = ((num7 >= 0) ? ((num7 > 255) ? 255 : num7) : 0); ptr[num2] = (byte)num7; num++; num3++; num2 += pixelSize; } int i = 1; for (int num8 = coefficients.Length; i < num8 && y + i < height; i++) { ptr += stride; array = coefficients[i]; int num9 = 0; int num10 = array.Length; int num11 = -(num10 >> 1); int num12 = -(num10 >> 1) * pixelSize; while (num9 < num10 && x + num11 < width) { if (x + num11 >= 0) { int num5 = ptr[num12 + 2] + rError * array[num9] / coefficientsSum; num5 = ((num5 >= 0) ? ((num5 > 255) ? 255 : num5) : 0); ptr[num12 + 2] = (byte)num5; int num6 = ptr[num12 + 1] + gError * array[num9] / coefficientsSum; num6 = ((num6 >= 0) ? ((num6 > 255) ? 255 : num6) : 0); ptr[num12 + 1] = (byte)num6; int num7 = ptr[num12] + bError * array[num9] / coefficientsSum; num7 = ((num7 >= 0) ? ((num7 > 255) ? 255 : num7) : 0); ptr[num12] = (byte)num7; } num11++; num9++; num12 += pixelSize; } } } private void CalculateCoefficientsSum() { coefficientsSum = 0; int i = 0; for (int num = coefficients.Length; i < num; i++) { int[] array = coefficients[i]; int j = 0; for (int num2 = array.Length; j < num2; j++) { coefficientsSum += array[j]; } } } } }
Markdown
UTF-8
10,910
2.640625
3
[ "Apache-2.0" ]
permissive
# Bee RFCs [![Bee RFC Book](https://github.com/iotaledger/bee-rfcs/workflows/Bee%20RFC%20Book/badge.svg)](https://iotaledger.github.io/bee-rfcs/) > This process is modelled after the approach taken by the Rust programming language, see [Rust RFC repository] for more information. Also see [maidsafe's RFC process] for another project into the crypto space. Our approach is taken and adapted from these. To make more substantial changes to Bee, we ask for these to go through a more organized design process --- a *RFC* (request for comments) process. The goal is to organize work between the different developers affiliated with the IOTA Foundation, and the wider open source community. We want to vet the ideas early on, get and give feedback, and only then start the implementation once the biggest questions are taken care of. ## What is *substantial* and when to follow this process You need to follow this process if you intend to make *substantial* changes to Bee and any of its constituting subcrates. + Anything that constitutes a breaking change as understood in the context of *semantic versioning*. + Any semantic or syntactic change to the existing algorithms that is not a bug fix. + Any proposed additional functionality and feature. + Anything that reduces interoperability (e.g. changes to public interfaces, the wire protocol or data serialisation.) Some changes do not require an RFC: + Rephrasing, reorganizing, refactoring, or otherwise "changing shape does not change meaning". + Additions that strictly improve objective, numerical quality criteria (warning removal, speedup, better platform coverage, more parallelism, trap more errors, etc.) + *Internal* additions, i.e. additions that are invisible to users of the public API, and which probably will be only noticed by developers of Bee. If you submit a pull request to implement a new feature without going through the RFC process, it may be closed with a polite request to submit an RFC first. ## The workflow of the RFC process > With both Rust and maidsafe being significantly larger projects, not all the steps below might be relevant to Bee's RFC process (for example, at the moment there are no dedicated subteams). However, to instill good open source governance we attempt to follow this process already now. In short, to get a major feature added to Bee, one must first get the RFC merged into the RFC repository as a markdown file. At that point the RFC is "active" and may be implemented with the goal of eventual inclusion into Bee. + Fork the RFC repository + Copy `0000-template.md` to `text/0000-my-feature.md` (where "my-feature" is descriptive; don't assign an RFC number yet; extra documents such as graphics or diagrams go into the new folder). + Fill in the RFC. Put care into the details: RFCs that do not present convincing motivation, demonstrate lack of understanding of the design's impact, or are disingenuous about the drawbacks or alternatives tend to be poorly-received. + Submit a pull request. As a pull request the RFC will receive design feedback from the larger community, and the author should be prepared to revise it in response. + Each pull request will be labeled with the most relevant sub-team, which will lead to its being triaged by that team in a future meeting and assigned to a member of the subteam. + Build consensus and integrate feedback. RFCs that have broad support are much more likely to make progress than those that don't receive any comments. Feel free to reach out to the RFC assignee in particular to get help identifying stakeholders and obstacles. + The sub-team will discuss the RFC pull request, as much as possible in the comment thread of the pull request itself. Offline discussion will be summarized on the pull request comment thread. + RFCs rarely go through this process unchanged, especially as alternatives and drawbacks are shown. You can make edits, big and small, to the RFC to clarify or change the design, but make changes as new commits to the pull request, and leave a comment on the pull request explaining your changes. Specifically, do not squash or rebase commits after they are visible on the pull request. + At some point, a member of the subteam will propose a "motion for final comment period" (FCP), along with a disposition for the RFC (merge, close, or postpone). + This step is taken when enough of the tradeoffs have been discussed that the subteam is in a position to make a decision. That does not require consensus amongst all participants in the RFC thread (which is usually impossible). However, the argument supporting the disposition on the RFC needs to have already been clearly articulated, and there should not be a strong consensus against that position outside of the subteam. Subteam members use their best judgment in taking this step, and the FCP itself ensures there is ample time and notification for stakeholders to push back if it is made prematurely. + For RFCs with lengthy discussion, the motion to FCP is usually preceded by a summary comment trying to lay out the current state of the discussion and major tradeoffs/points of disagreement. + Before actually entering FCP, all members of the subteam must sign off; this is often the point at which many subteam members first review the RFC in full depth. + The FCP lasts ten calendar days, so that it is open for at least 5 business days. It is also advertised widely, e.g. on discord or in a blog post. This way all stakeholders have a chance to lodge any final objections before a decision is reached. + In most cases, the FCP period is quiet, and the RFC is either merged or closed. However, sometimes substantial new arguments or ideas are raised, the FCP is canceled, and the RFC goes back into development mode. ## The RFC life-cycle Once an RFC becomes active then authors may implement it and submit the feature as a pull request to the repo. Being "active" is not a rubber stamp and in particular still does not mean the feature will ultimately be merged. It does mean that in principle all the major stakeholders have agreed to the feature and are amenable to merging it. Furthermore, the fact that a given RFC has been accepted and is "active" implies nothing about what priority is assigned to its implementation, nor does it imply anything about whether a developer has been assigned the task of implementing the feature. While it is not necessary that the author of the RFC also write the implementation, it is by far the most effective way to see an RFC through to completion. Authors should not expect that other project developers will take on responsibility for implementing their accepted feature. Modifications to active RFCs can be done in follow up PRs. We strive to write each RFC in a manner that it will reflect the final design of the feature, however, the nature of the process means that we cannot expect every merged RFC to actually reflect what the end result will be at the time of the next major release. We therefore try to keep each RFC document somewhat in sync with the network feature as planned, tracking such changes via followup pull requests to the document. An RFC that makes it through the entire process to implementation is considered "implemented" and is moved to the "implemented" folder. An RFC that fails after becoming active is "rejected" and moves to the "rejected" folder. ## Reviewing RFCs While the RFC pull request is up, the sub-team may schedule meetings with the author and/or relevant stakeholders to discuss the issues in greater detail, and in some cases the topic may be discussed at a sub-team meeting. In either case a summary from the meeting will be posted back to the RFC pull request. A sub-team makes final decisions about RFCs after the benefits and drawbacks are well understood. These decisions can be made at any time, but the sub-team will regularly issue decisions. When a decision is made, the RFC pull request will either be merged or closed. In either case, if the reasoning is not clear from the discussion in thread, the sub-team will add a comment describing the rationale for the decision. ## Implementing an RFC Some accepted RFCs represent vital features that need to be implemented right away. Other accepted RFCs can represent features that can wait until some arbitrary developer feels like doing the work. Every accepted RFC has an associated issue tracking its implementation in the affected repositories. Therefore, the associated issue can be assigned a priority via the triage process that the team uses for all issues in the appropriate repositories. The author of an RFC is not obligated to implement it. Of course, the RFC author (like any other developer) is welcome to post an implementation for review after the RFC has been accepted. If you are interested in working on the implementation for an "active" RFC, but cannot determine if someone else is already working on it, feel free to ask (e.g. by leaving a comment on the associated issue). ## RFC postponement Some RFC pull requests are tagged with the "postponed" label when they are closed (as part of the rejection process). An RFC closed with "postponed" is marked as such because we want neither to think about evaluating the proposal nor about implementing the described feature until some time in the future, and we believe that we can afford to wait until then to do so. Historically, "postponed" was used to postpone features until after 1.0. Postponed pull requests may be re-opened when the time is right. We don't have any formal process for that, you should ask members of the relevant sub-team. Usually an RFC pull request marked as "postponed" has already passed an informal first round of evaluation, namely the round of "do we think we would ever possibly consider making this change, as outlined in the RFC pull request, or some semi-obvious variation of it." (When the answer to the latter question is "no", then the appropriate response is to close the RFC, not postpone it.) ## Help! This is all too informal The process is intended to be as lightweight as reasonable for the present circumstances. As usual, we are trying to let the process be driven by consensus and community norms, not impose more structure than necessary. # Contributions, license, copyright This project is licensed under Apache License, Version 2.0, ([LICENSE-APACHE] or http://www.apache.org/licenses/LICENSE-2.0). Any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. [maidsafe's RFC process]: https://github.com/maidsafe/rfcs [LICENSE-APACHE]: https://github.com/iotaledger/bee-rfcs/blob/master/LICENSE-APACHE [Rust RFC repository]: https://github.com/rust-lang/rfcs
Java
UTF-8
1,661
3.53125
4
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hrickascislempi; import java.awt.geom.Point2D; import java.util.Scanner; /** * * @author já * metoda Monte Carlo * API Aplication Program interface je na netu * doukumentace, java.awt.geom, Point2D.Double */ public class Main { static double zjisteniHodnotyCislaPi(double pocetExperimentu) { // nebo muzem pouzit void jako parametr metody int bodyUvnitr=0; for (int i = 1; i <= pocetExperimentu; i++) { Point2D.Double k=nahodnyBod(); if (polohaBoduVuciKruzniciACtverci(k)== true) { bodyUvnitr++;}} double pi=bodyUvnitr/pocetExperimentu*4.0; return pi; } static boolean polohaBoduVuciKruzniciACtverci(Point2D.Double p) { // Point P reference na double vzd = vzdalenostBoduOdPocatku(p); boolean jeVKruznici=false; if (vzd<=1) jeVKruznici=true; return jeVKruznici; } static Point2D.Double nahodnyBod() { return new Point2D.Double(Math.random(), Math.random()); } static double vzdalenostBoduOdPocatku(Point2D.Double p) { return p.distance(0, 0); // instancni metoda, potrebuje pred sebou objekt. } /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Napiste pocet pokusu, ktere maji slouzit k vypoctu cisla Pi:"); int pocetPokusu=new Scanner(System.in).nextInt(); System.out.println("Cislo Pi je priblizne: " + zjisteniHodnotyCislaPi(pocetPokusu)); } }
Shell
UTF-8
204
3.21875
3
[]
no_license
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' cd $(dirname $(readlink -f $0)) escapeEol() { sed ' : again /\\$/ { N s/\\\s*\n\s*\\// t again }' | sed -e 's/\\n/\n/g' } escapeEol
Markdown
UTF-8
2,434
2.90625
3
[]
no_license
--- bibliography: - '../references.bib' --- Project Name ============ Making a “Résumé for Gig Workers” Description =========== Gig workers are increasingly piecing together earnings from various work platforms to make ends meet. But insight into their work performance and history are virtually nonexistent. Requesters — the people that hire workers — increasingly struggle with existing qualifications and credentials services, which lack sufficient detail about worker quality, driving them to undervalue workers. Requesters don’t get the information they need to make confident, informed decisions, and as a result they’re reluctant to trust gig workers to pay for creative, complex work. This summer we’ll be building a *gig worker résumé* service, an online system that aggregates workers’ histories, provides analytics on their performance over time, and helps requesters find high–quality workers. You’ll play a major part in designing and implementing this system, involving web scraping, some statistical analysis, data visualization, and potentially more. You’ll also have the opportunity to study how people use the system, using a mix of qualitative and quantitative analysis, to inform our next steps. Recommended Background {#sec:RecommendedBackground} ====================== Ideally, you have experience in Human–Computer Interaction (think CS 147, 247). Much of the day–to–day work will involve programming for the web (think CS 142), so regardless of your research goals you should be able to code (and be reasonably competent with existing libraries, frameworks, and APIs). It might be worth pointing out that I don’t expect you to be an expert in these things right now. You should be competent enough to start working on day 1, but this is a chance to hone your skills and maybe learn something completely new. If your background doesn’t fit with anything above, please tell us the most ambitious thing you’ve undertaken, academic or not! (Hard work can overcome lack of preparation!) Number of students allowed ========================== 2 Prerequisite/Preparation ======================== If you feel unprepared in any of the areas listed under the “” section, then your preparation between now and the start of the program will be to try to fill in gaps. If you want, we can discuss this further and start to prepare for your time through spring quarter.
Java
UTF-8
1,024
2.25
2
[]
no_license
package com.bjike.goddess.customer.vo; /** * 时效性因素层权重表现层对象 * * @Author: [ lijuntao ] * @Date: [ 2017-11-01 01:52 ] * @Description: [ 时效性因素层权重表现层对象 ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ public class TimelinessFactorWeightVO { /** * id */ private String id; /** * 时效性类型名称 */ private String timelinessName; /** * 时效性类型权重 */ private Double timelinessWeight; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTimelinessName() { return timelinessName; } public void setTimelinessName(String timelinessName) { this.timelinessName = timelinessName; } public Double getTimelinessWeight() { return timelinessWeight; } public void setTimelinessWeight(Double timelinessWeight) { this.timelinessWeight = timelinessWeight; } }
Java
UTF-8
1,957
2.84375
3
[]
no_license
package com.neeson.java8.annotation; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.*; import javax.lang.model.util.ElementScanner8; import javax.tools.Diagnostic; public class NameChecker { private final Messager messager; NameCheckScanner nameCheckScanner = new NameCheckScanner(); NameChecker(ProcessingEnvironment processingEnvironment) { this.messager = processingEnvironment.getMessager(); } public void checkName(Element element) { nameCheckScanner.scan(element); } private class NameCheckScanner extends ElementScanner8<Void, Void> { @Override public Void visitType(TypeElement e, Void aVoid) { scan(e.getTypeParameters(), aVoid); checkCamelCase(e, true); return super.visitType(e, aVoid); } @Override public Void visitExecutable(ExecutableElement e, Void aVoid) { if (e.getKind() == ElementKind.METHOD) { Name name = e.getSimpleName(); if (name.contentEquals(e.getEnclosingElement().getSimpleName())) { messager.printMessage(Diagnostic.Kind.WARNING,"普通方法" + name + "不应该与类名重复"); checkCamelCase(e,false); } } return super.visitExecutable(e, aVoid); } private void checkCamelCase(Element e, boolean initialCaps) { String name = e.getSimpleName().toString(); boolean previousUpper = false; boolean conventional = true; int firstCodePoint = name.codePointAt(0); if (Character.isUpperCase(firstCodePoint)) { previousUpper = true; if (!initialCaps) { messager.printMessage(Diagnostic.Kind.WARNING,"..."); } } } } }
C#
UTF-8
1,197
2.75
3
[]
no_license
using Ostis.Sctp.Arguments; namespace Ostis.Sctp.Commands { /// <summary> /// Команда: Поиск SC-элемента по его системному идентификатору. /// </summary> /// <example> /// Следующий пример демонстрирует использование класса <see cref="FindElementCommand"/> /// <code source="..\Ostis.Tests\CommandsTest.cs" region="FindElement" lang="C#" /> /// </example> public class FindElementCommand : Command { #region Параметры команды /// <summary> /// Идентификатор. /// </summary> public Identifier Identifier { get { return identifier; } } private readonly Identifier identifier; #endregion /// <summary> /// Инициализирует новую команду. /// </summary> /// <param name="identifier">идентификатор</param> public FindElementCommand(Identifier identifier) : base(CommandCode.FindElement) { Arguments.Add(this.identifier = identifier); } } }
Python
UTF-8
3,570
3.3125
3
[]
no_license
# # s = 'Это просто строка текста. А это ещё одна строка текстаю' # # pattern = 'строка' # # print(s.find(pattern)) # print(pattern in s) #----------------------------------------------------- # import re # s = 'Это просто строка текста. А это ещё одна строка текстаю' # # pattern = 'строка' # # if re.search(pattern, s): # print('Matched') # else: # print('No_Matched') #----------------------------------------------------- # import re # s = 'Это просто строка текста. А это ещё одна строка текстаю' # # pattern = 'строка' # # if re.search(pattern, s): # print('Matched') # else: # print('No_Matched') # # match = re.search(pattern, s) # # print(match) #----------------------------------------------------- # import re # s = 'Это просто строка текста. А это ещё одна строка текстаю' # # pattern = 'строка' # pattern2 = 'Это' # pattern3 = 'это' # # print(re.match(pattern, s)) # print(re.match(pattern2, s)) # регистро зависимый метод поиска. Находит только первое совподение # print(re.match(pattern3, s)) #----------------------------------------------------- # import re # s = 'Это просто строка текста. А это ещё одна строка текстаю' # # pattern = 'строка' # # print(re.findall(pattern, s)) # Находит все совподения в списке #----------------------------------------------------- # import re # s = 'Это просто строка текста. А это ещё одна строка текстаю.' # # pattern = 'строка' # # print(re.split('.', s))# Разделяет строку по заданному заблону # print(re.split('\.', s)) # print(re.split(r'\.', s)) # print(re.split(r'\.', s, 1)) # 1 указывает на одно разделение строки # #----------------------------------------------------- # # import re # s = '''Это просто строка текста. # А это ещё одна строка текстаю. # А это строка с цифрами: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10 # А это сторока с разными символами: "!", "@", "-", "&", "?", "_" # a\\b\tc # test string # ''' # # pattern = r'\w' #получает все симловы кроме специальных # pattern2 = r'\w+' # получает слова + цифры кроме специальных # print(re.findall(pattern, s)) # print(re.findall(pattern2, s)) #----------------------------------------------------- # # import re # s = '''Это просто строка текста. # А это ещё одна строка текстаю. # А это строка с цифрами: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10 # А это сторока с разными символами: "!", "@", "-", "&", "?", "_" # a\\b\tc # test string # ''' # # pattern = r'[]' # # print(re.findall(pattern, s)) # Функция для валидации email import re s = "mail@mail.com" def validate_email(email): # return re.match(r'^.+@\w+\.[a-z]{2,6}$', email, re.IGNORECASE) # return re.match(r'^.+@(\w+\.){0,2}[a-z]{2,6}$', email, re.IGNORECASE) return bool(re.match(r'^.+@(\w+\.){0,2}[a-z]{2,6}$', email, re.IGNORECASE)) print(validate_email("mail@mail.com")) print(validate_email("ivanov@mail")) print(validate_email("mail@mail.com.ru"))
JavaScript
UTF-8
487
2.9375
3
[]
no_license
/** * Created by Administrator on 2015/10/19. */ var utils = require('util'); /** * 这是一个基于对象间原型继承的函数、主要是工具 * */ console.log(utils.inspect({name:'qiansimin'})); //把对象转化成字符串 console.log(utils.isArray([])); //一些列的检测 返回的是布尔值 console.log(utils.isRegExp(/\d+/)); console.log(utils.isDate(new Date())); //检测是不是日期对象 console.log(utils.isError(new Error));
C#
UTF-8
973
3.578125
4
[ "MIT" ]
permissive
public class Solution { public bool SearchMatrix(int[,] matrix, int target) { return SearchMatrixInt(matrix, 0, matrix.GetLength(0) - 1, 0, matrix.GetLength(1) - 1, target); } private bool SearchMatrixInt(int[,] matrix, int top, int bottom, int left, int right, int target) { if (top > bottom || left > right) { return false; } int vMid = (top + bottom ) / 2; int hMid = (left + right) / 2; int mValue = matrix[vMid, hMid]; if (mValue == target) { return true; } else if (mValue > target) { return SearchMatrixInt(matrix, top, vMid - 1, left, right, target) || SearchMatrixInt(matrix, vMid, bottom, left, hMid - 1, target); } else { return SearchMatrixInt(matrix, top, vMid, hMid + 1, right, target) || SearchMatrixInt(matrix, vMid + 1, bottom, left, right, target); } } }
C#
UTF-8
544
2.9375
3
[]
no_license
namespace Calculator { public class MultipleOperation : BinaryOperator { public MultipleOperation() : base() { Priority = 2; Literal = "*"; } public override decimal Calculate(decimal[] x) => x[0]*x[1]; public override Operator Clone() { return new MultipleOperation() { Literal = Literal, Priority = Priority, ArgumentsCount = ArgumentsCount }; } } }
Python
UTF-8
2,448
2.921875
3
[]
no_license
import numpy as np import torch.optim from torch.autograd import Variable from models import linmodel import utils import numpy.linalg as linalg import sys def init_data(nsamples, dx, dy): Xold = np.linspace(0, 1000, nsamples * dx).reshape([nsamples, dx]) X = utils.standardize(Xold) invertible = False while not invertible: W = np.random.randint(1, 10, size=(dy, dx)) if linalg.cond(W) < 1 / sys.float_info.epsilon: invertible = True print('W invertible') Y = W.dot(X.T) # target # for i in range(Y.shape[1]): # Y[:, i] = utils.add_noise(Y[:, i]) print('shapes Y = {}, X: {}, W: {}'.format(Y.shape, X.shape, W.shape)) x = Variable(torch.from_numpy(X), requires_grad=True).type(torch.FloatTensor) y = Variable(torch.from_numpy(Y), requires_grad=True).type(torch.FloatTensor) w = Variable(torch.from_numpy(W), requires_grad=True).type(torch.FloatTensor) return x, y, w def instantiate_model(dx, dy): model = linmodel.LinModel(dx, dy) optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) return model, optimizer def step(x, y, model, optimizer): optimizer.zero_grad() prediction = model(x) # x = (400, 1): x1 = (200. 1). x2 = (200, 1) loss = linmodel.cost(y, prediction) loss.backward() # get the gradients # print([param.grad.data for param in model.parameters()]) optimizer.step() # return model, optimizer, loss.data.numpy() def get_mse(m, w): r = np.array([param.data for param in m.parameters()]) res = Variable(r[0]) return linmodel.mse(res, w) if __name__ == "__main__": NUM_ITERATIONS = 10000 N = 500 # 50 - 500 - 1000 - 5000 dx = 10 # log fino a 1M (0-6) dy = 1 x, y, w = init_data(N, dx, dy) m, o = instantiate_model(dx, dy) losses = [] for i in range(NUM_ITERATIONS): m, o, l = step(x, y, m, o) losses.append(l) print(w) print([param.data for param in m.parameters()]) print(min(losses), max(losses)) import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(losses, label='{}/{}'.format(N, dx)) legend = ax.legend(loc='upper right') plt.ylim(0, 10000) plt.xlim(0, NUM_ITERATIONS) plt.show() # print(get_mse(m, w)) # print(w) # print([param.data for param in m.parameters()]) pred = m(x) plt.scatter(pred.data.numpy(), y.data.numpy()) plt.show()
C++
UTF-8
707
3.875
4
[ "MIT" ]
permissive
/* Problem-Task: Create a function that takes a string and returns the middle character(s). If the word's length is odd, return the middle character. If the word's length is even, return the middle two characters. Problem Link: https://edabit.com/challenge/p3SCSXaWQLWpvqCYZ */ #include "bits/stdc++.h" using namespace std; std::string getMiddle(std::string str) { int start = 0; int n = str.length(); int end = n-1; int mid = start+(end-start)/2; std::string result = ""; // even length if(n%2==0){ result = result + str[mid] + str[mid+1]; } else result = str[mid]; return result; } int main() { string str = "middle"; cout << getMiddle(str) << endl; return 0; }
Markdown
UTF-8
2,473
3.40625
3
[]
no_license
# simpleChatBot Developed the simple chat bot using Python and AIML(Artificial Intilegence Markup Language). #What is AIML? AIML was developed by Richard Wallace. He made a bot called A.L.I.C.E. (Artificial Linguistics Internet Computer Entity) which won several artificial intelligence awards. Interestingly, one of the Turing tests to look for artificial intelligence is to have a human chat with a bot through a text interface for several minutes and see if they thought it was a human. AIML is a form of XML that defines rules for matching patterns and determining responses. AIML as 4 Basic Tags: <aiml> - defines the beginning and end of a AIML document. <category> - defines the unit of knowledge in Alicebot's knowledge base. <pattern> - defines the pattern to match what a user may input to an Alicebot. <template> - defines the response of an Alicebot to user's input. other tags reference will be avilable in the reference link : http://www.alicebot.org/documentation/aiml-reference.html #Simplest Python Program python module for the running AIML : #'Pip install aiml' This is the simplest program we can start with. It creates the aiml object, learns the startup file, and then loads the rest of the aiml files. After that, it is ready to chat, and we enter an infinite loop that will continue to prompt the user for a message. You will need to enter a pattern the bot recognizes. The patterns recognized depend on what AIML files you loaded. We create the startup file as a separate entity so that we can add more aiml files to the bot later without having to modify any of the programs source code. We can just add more files to learn in the startup xml file. import aiml # Create the kernel and learn AIML files kernel = aiml.Kernel() kernel.learn("std-startup.xml") kernel.respond("load aiml b") # Press CTRL-C to break this loop while True: print kernel.respond(raw_input("Enter your message >> ")) in std_startup.xml file we can include the diffenrent aiml file according our requirement for chatbot replay process. for e.g : <learn>hello.aiml</learn> now 'hello.aiml' included in <learn> tag it loads the every information present in the aiml to the xml then replay to python. #brain.py python script for loading the aiml files through startup.xml #startup.xml xml script for loading the AIML files # * .aiml which consist of source and responce of chatbot.
JavaScript
UTF-8
3,810
3.109375
3
[]
no_license
$(function(){ var cart = {}; render(com.dawgpizza.menu.pizzas, com.dawgpizza.menu.drinks, com.dawgpizza.menu.dessert); renderTotal(); $('.add-to-cart').click(addToCart()); }); function render(pizzas, drinks, desserts){ var idx; var pizza; pizzas=com.dawgpizza.menu.pizzas; // (Pizza array. com.pizza.menu is the total object. Three arrays within this object) drink=com.dawgpizza.menu.drinks; dessert=com.dawgpizza.menu.dessert; var pizzaVariable = $('.templatePizza'); var drinksVariable = $('.templateDrinks'); var dessertVariable = $('.templateDessert'); for (idx = 0; idx < com.dawgpizza.menu.pizzas.length; ++idx) { pizza = com.dawgpizza.menu.pizzas[idx]; var clone=pizzaVariable.clone(); clone.find('.name').html(pizza.name); clone.find('.description').html(pizza.description); clone.find('.butname').html("Small: $" + pizza.prices[0]).attr({ "data-name": pizza.name, "data.price":pizza.prices[0] }) clone.find('.butname2').html("Medium: $" + pizza.prices[1]).attr({ "data-name": pizza.name, "data.price":pizza.prices[1] }) clone.find('.butname3').html("Large: $" + pizza.prices[2]).attr({ "data-name": pizza.name, "data.price":pizza.prices[2] }) $('div.pizzaheading').append(clone); } for (idx = 0; idx < com.dawgpizza.menu.drinks.length; ++idx) { drinks = com.dawgpizza.menu.drinks[idx]; var clone=drinksVariable.clone(); clone.find('.name').html(drinks.name); clone.find('.drinkname').html("$" + drinks.price).attr({ "data-name" : drinks.name, "data-price" : drinks.price }); $('div.drinksheading').append(clone); } for (idx = 0; idx < com.dawgpizza.menu.desserts.length; ++idx) { desserts = com.dawgpizza.menu.desserts[idx]; var clone=dessertVariable.clone(); clone.find('.name').html(desserts.name); clone.find('.dessertname').html("$" + desserts.price).attr({ "data-name" : desserts.name, "data-price" : desserts.price }); $('div.dessertheading').append(clone); } } function renderTotal(){ $(".total-price").html(total); }; function removeFromCart(){ var item = new ItemModel({ name: $(this).attr("data-name"), size: $(this).attr("data-size") }); total -= parseInt($(this).attr("data-price")); cart.removeItem(item); $(this).remove(); renderTotal(); } function addToCart () { var type = $(this).data("type"); var name = $(this).data("name"); var size = ""; if (type == "pizza") { size = $(this).data("size"); }; var price = $(this).data("price"); var item = new ItemModel({ name: name, type: type, size: size, price: price, qty: 1 }); var itemHtml = $(".template-cart-item").clone().removeClass("template-cart-item"); itemHtml.html(name + " " + size + " $" + price); $(".cart-items-container").append(itemHtml); itemHtml.click(removeFromCart); itemHtml.attr({ "data-name" : name, "data-type": type, "data-size": size, "data-price": price, }); cart.addItem(item); total += parseInt(price); renderTotal(); }
JavaScript
UTF-8
4,726
2.6875
3
[]
no_license
/** @module room/router */ 'use strict'; /* Imports */ const express = require('express'); const middleware = require('../middleware'); const mongoose = require('mongoose'); const Room = mongoose.model('Room'); const Post = mongoose.model('Post'); const ObjectId = mongoose.Types.ObjectId; /* Create router */ const router = express.Router(); /* Supported methods */ router.all('/', middleware.supportedMethods('GET, OPTIONS')); /* Room no id, return nothing */ router.get('/', function(req, res, next) { var newsArray = []; Room.find({}, function(err, rooms) { for (let room of rooms) { var news = { title : room.headline, postsCount : room.postsCount, location: room.location, lastPost : room.lastPost, itemsCount : room.items.length, tags : room.tags, id : room._id } news.description = room.items[0].body_xhtml.replace(/<p>/g, '').replace(/\n/g, '').replace(/<\/p>/g, '').replace(/<p\/>/g, ''); // news.description = 'FAKE NEWS FOR NOW' newsArray.push(news); } res.status(200).json({ statusCode: 200, message: 'sucessfully retrieved news', data: newsArray }).end(); }); }); /* Room id, return that room */ router.get('/:room_id', function(req, res, next) { /* If bad ID return */ if (!ObjectId.isValid(req.params.room_id)) { res.sendStatus(400); } /* Get room and populate data */ else if (req.accepts('text/html')) { Room.findById(req.params.room_id) .populate({ path: 'posts', populate: { path: 'replies' }, }) .exec(function(err, room_data) { if (err) { res.sendStatus(500); } else if (room_data) { res.render('room', { title : "Nepeta", roomstring : JSON.stringify(room_data), }); } else res.sendStatus(404); }); } /* If bad accepts return */ else { res.sendStatus(400); } }); /* Room id, post comment to that room*/ router.post('/:room_id', function(req, res, next) { var newPost = new Post(req.body); if (ObjectId.isValid(req.params.room_id)) { // retrieve the room (for statistics) Room.findById(req.params.room_id).exec(function(err, room){ if (err){ return next(err); } else { var currentRoom = room; // if true then post is a reply to another post // add as reply of parent if (newPost.parent) { Post.findById(newPost.parent).exec(function(err, post) { if (err) return next(err); if (!post) { res.status(404).json({ message: "Trying to reply to a non-existent post." }); } else { // save new post and augment coutn in room newPost.save(function(err, savedChild) { if (err) { res.status(400).json({ message: "Error saving new post." }); } else { // now save child id into parent post.replies.push(savedChild._id); post.save(function(err, savedParent) { if (err) { res.status(400).json({ message: "Could not save Post in parent post." }); } else if (savedParent) { room.postsCount++; room.save(function(err, savedRoom) { res.status(201).json(savedChild); }); } else res.status(400).json({ message: "Could not save parent." }); }); } }); } }); } else { // no parent. then it's not a reply to another post newPost.save(function(err, saved) { if (err) { res.status(400).json({ message: "Error saving new post." }); } else if (saved) { // post saved in DB, now add it to the room. room.posts.push(saved._id); room.postsCount++; room.save(function(err, updatedRoom) { if (err) { res.status(400).json({ message: "Could not save Post in Room. " }); } else { res.status(201).json(saved); } }); } else res.status(400); }); } } }); } }); /* Export router for room */ module.exports = router;
C#
UTF-8
3,069
2.546875
3
[ "MIT" ]
permissive
/* * SplitCmd.java * * Copyright (c) 1997 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * * Included in SQLite3 port to C# for use in testharness only; 2008 Noah B Hart * * RCS @(#) $Id: SplitCmd.java,v 1.1.1.1 1998/10/14 21:09:19 cvsadmin Exp $ * */ using System; namespace tcl.lang { /// <summary> This class implements the built-in "split" command in Tcl.</summary> class SplitCmd : Command { /// <summary> Default characters for splitting up strings.</summary> private static char[] defSplitChars = new char[] { ' ', '\n', '\t', '\r' }; /// <summary> This procedure is invoked to process the "split" Tcl /// command. See Tcl user documentation for details. /// /// </summary> /// <param name="interp">the current interpreter. /// </param> /// <param name="argv">command arguments. /// </param> /// <exception cref=""> TclException If incorrect number of arguments. /// </exception> public TCL.CompletionCode cmdProc( Interp interp, TclObject[] argv ) { char[] splitChars = null; string inString; if ( argv.Length == 2 ) { splitChars = defSplitChars; } else if ( argv.Length == 3 ) { splitChars = argv[2].ToString().ToCharArray(); } else { throw new TclNumArgsException( interp, 1, argv, "string ?splitChars?" ); } inString = argv[1].ToString(); int len = inString.Length; int num = splitChars.Length; /* * Handle the special case of splitting on every character. */ if ( num == 0 ) { TclObject list = TclList.newInstance(); list.preserve(); try { for ( int i = 0; i < len; i++ ) { TclList.append( interp, list, TclString.newInstance( inString[i] ) ); } interp.setResult( list ); } finally { list.release(); } return TCL.CompletionCode.RETURN; } /* * Normal case: split on any of a given set of characters. * Discard instances of the split characters. */ TclObject list2 = TclList.newInstance(); int elemStart = 0; list2.preserve(); try { int i, j; for ( i = 0; i < len; i++ ) { char c = inString[i]; for ( j = 0; j < num; j++ ) { if ( c == splitChars[j] ) { TclList.append( interp, list2, TclString.newInstance( inString.Substring( elemStart, ( i ) - ( elemStart ) ) ) ); elemStart = i + 1; break; } } } if ( i != 0 ) { TclList.append( interp, list2, TclString.newInstance( inString.Substring( elemStart ) ) ); } interp.setResult( list2 ); } finally { list2.release(); } return TCL.CompletionCode.RETURN; } } }
Markdown
UTF-8
944
3.359375
3
[ "MIT" ]
permissive
在张量中排列轴。 **别名** : [ `tf.compat.v1.keras.backend.permute_dimensions` ](/api_docs/python/tf/keras/backend/permute_dimensions), [ `tf.compat.v2.keras.backend.permute_dimensions` ](/api_docs/python/tf/keras/backend/permute_dimensions) ``` tf.keras.backend.permute_dimensions( x, pattern ) ``` #### 参数: - **`x`** : Tensor or variable. - **`pattern`** : A tuple ofdimension indices, e.g. `(0, 2, 1)` . #### 返回: 张量 #### 示例: ``` >>> a = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) >>> a <tf.Tensor: id=49, shape=(4, 3), dtype=int32, numpy= array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]], dtype=int32)> >>> tf.keras.backend.permute_dimensions(a, pattern=(1, 0)) <tf.Tensor: id=52, shape=(3, 4), dtype=int32, numpy= array([[ 1, 4, 7, 10], [ 2, 5, 8, 11], [ 3, 6, 9, 12]], dtype=int32)> ```
Java
UTF-8
1,106
3.1875
3
[]
no_license
/* Martin Alegría A01022216 */ public class Persona { private String nombre; private String apellido; private int nacimiento; private String telefono; Persona(String nombre, String apellido, int nacimiento){ this.nombre = nombre; this.apellido = apellido; this.nacimiento = nacimiento; } public String getNombre() { return nombre; } public String getApellido() { return apellido; } public int getNacimiento() { return nacimiento; } public String getTelefono() { return telefono; } public void setNombre(String nombre) { this.nombre = nombre; } public void setApellido(String apellido) { this.apellido = apellido; } public void setNacimiento(int nacimiento) { this.nacimiento = nacimiento; } public void setTelefono(String telefono) { this.telefono = telefono; } @Override public String toString(){ return nombre + " " + apellido + "\t Año de Nacimiento: " + nacimiento + "\n"; } }
Java
UTF-8
1,867
2.21875
2
[]
no_license
package com.game.core.room; import com.game.core.room.interfaces.ItemConsume; import com.game.manager.DBServiceManager; import com.game.manager.OnlineManager; import com.game.socket.module.UserVistor; import com.logger.type.LogType; import java.util.HashSet; import java.util.Set; /** * Created by Administrator on 2017/5/27. */ public class ItemConsumeService implements ItemConsume { private static final ItemConsumeService intance = new ItemConsumeService(); private ItemConsumeService(){} private Set<Integer> whiteFilter = new HashSet<>(10); static final ItemConsumeService getIntance(){ return intance; } @Override public boolean checkCard(int roleId, int needCardCount) { if(roleId == 0 || whiteFilter.contains(roleId)){ return true; } UserVistor vistor = OnlineManager.getIntance().getRoleId(roleId); if(vistor != null && vistor.getGameRole() != null){ return vistor.getGameRole().getCard()-needCardCount > 0; } return false; } @Override public void removeCard(int roleId, int needCardCount) { if(roleId == 0 || whiteFilter.contains(roleId)){ return; } UserVistor vistor = OnlineManager.getIntance().getRoleId(roleId); if(vistor != null && vistor.getGameRole() != null){ vistor.getGameRole().setCard(Math.max(0, vistor.getGameRole().getCard()-needCardCount)); return; } ///添加 int logId = (int) (System.currentTimeMillis()/1000); DBServiceManager.getInstance().getUserService().addMoney(roleId,-needCardCount, LogType.Card,logId); } public Set<Integer> getWhiteFilter() { return whiteFilter; } public void setWhiteFilter(Set<Integer> whiteFilter) { this.whiteFilter = whiteFilter; } }
Python
UTF-8
12,767
2.609375
3
[]
no_license
from numpy import * from pylab import * numshots = 30 shot = zeros(numshots) speed = zeros(numshots) current = zeros(numshots) saturatedfrequency = zeros(numshots) saturatedfrequencyerr = zeros(numshots) saturatedpower = zeros(numshots) saturatedintervalstart = zeros(numshots) saturatedintervalstop = zeros(numshots) timefieldon = zeros(numshots) timesaturated = zeros(numshots) timefieldoff = zeros(numshots) freqband_min = zeros(numshots) freqband_max = zeros(numshots) #Shear measurements taken from 12 to 16 cm. saturatedshear = zeros(numshots) beginningshear = zeros(numshots) #For MRI-Zed shots. Ring-speed ratio at 10%: 400, 220, 53, 53 #Measurements taken at r=19.2 cm i = 0 shot[i] = 1036 speed[i] = 400 current[i] = 800 saturatedfrequency[i] = 0.25 saturatedfrequencyerr[i] = 0.03 freqband_min[i] = 0.20 freqband_max[i] = 0.35 saturatedpower[i] = 11.637 saturatedintervalstart[i] = 50 saturatedintervalstop[i] = 69 timefieldon[i] = 20 timesaturated[i] = 50 timefieldoff[i] = 70 saturatedshear[i] = -1.26525 i = 1 shot[i] = 926 speed[i] = 400 current[i] = 1000 saturatedfrequency[i] = 0.40 saturatedfrequencyerr[i] = 0.02 freqband_min[i] = 0.28 freqband_max[i] = 0.58 saturatedpower[i] = 25.728 saturatedintervalstart[i] = 32 saturatedintervalstop[i] = 59 timefieldon[i] = 20 timesaturated[i] = 32 timefieldoff[i] = 60 saturatedshear[i] = -1.48177 i = 2 shot[i] = 927 speed[i] = 400 current[i] = 1200 saturatedfrequency[i] = 0.44 saturatedfrequencyerr[i] = 0.02 freqband_min[i] = 0.23 freqband_max[i] = 0.67 saturatedpower[i] = 73.902 saturatedintervalstart[i] = 32 saturatedintervalstop[i] = 49 timefieldon[i] = 20 timesaturated[i] = 32 timefieldoff[i] = 50 saturatedshear[i] = -1.411973 i = 3 shot[i] = 1044 speed[i] = 400 current[i] = 1400 saturatedfrequency[i] = 0.45 saturatedfrequencyerr[i] = 0.05 freqband_min[i] = 0.35 freqband_max[i] = 0.60 saturatedpower[i] = 71.254 saturatedintervalstart[i] = 32 saturatedintervalstop[i] = 39 timefieldon[i] = 20 timesaturated[i] = 32 timefieldoff[i] = 40 saturatedshear[i] = -1.007015 i = 4 shot[i] = 854 speed[i] = 800 current[i] = 1200 saturatedfrequency[i] = 0.59 saturatedfrequencyerr[i] = 0.10 freqband_min[i] = 0.50 freqband_max[i] = 0.80 saturatedpower[i] = 16.627 saturatedintervalstart[i] = 135 saturatedintervalstop[i] = 154 timefieldon[i] = 125 timesaturated[i] = 135 timefieldoff[i] = 155 saturatedshear[i] = -2.88058 i = 5 shot[i] = 856 speed[i] = 1200 current[i] = 1200 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 125 timesaturated[i] = nan timefieldoff[i] = 155 saturatedshear[i] = -3.935047 i = 6 shot[i] = 858 speed[i] = 1600 current[i] = 1200 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 125 timesaturated[i] = nan timefieldoff[i] = 155 saturatedshear[i] = -5.0827 i = 7 shot[i] = 860 speed[i] = 1800 current[i] = 1200 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 5 timesaturated[i] = nan timefieldoff[i] = 35 saturatedshear[i] = -5.8765 i = 8 shot[i] = 894 speed[i] = 800 current[i] = 600 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 20 timesaturated[i] = nan timefieldoff[i] = 80 saturatedshear[i] = nan i = 9 shot[i] = 898 speed[i] = 800 current[i] = 1000 saturatedfrequency[i] = 0.94 saturatedfrequencyerr[i] = 0.08 freqband_min[i] = 0.8 freqband_max[i] = 1.1 saturatedpower[i] = 0.5202 saturatedintervalstart[i] = 40 saturatedintervalstop[i] = 59 timefieldon[i] = 20 timesaturated[i] = 40 timefieldoff[i] = 60 saturatedshear[i] = nan i = 10 shot[i] = 900 speed[i] = 800 current[i] = 1400 saturatedfrequency[i] = 0.70 saturatedfrequencyerr[i] = 0.05 freqband_min[i] = 0.40 freqband_max[i] = 1.0 saturatedpower[i] = 89.774 saturatedintervalstart[i] = 30 saturatedintervalstop[i] = 39 timefieldon[i] = 20 timesaturated[i] = 30 timefieldoff[i] = 40 saturatedshear[i] = nan i = 11 shot[i] = 902 speed[i] = 1200 current[i] = 1400 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 20 timesaturated[i] = nan timefieldoff[i] = 40 saturatedshear[i] = nan i = 12 shot[i] = 904 speed[i] = 1200 current[i] = 1600 saturatedfrequency[i] = 0.90 saturatedfrequencyerr[i] = 0.10 freqband_min[i] = 0.50 freqband_max[i] = 1.27 saturatedpower[i] = 37.93 saturatedintervalstart[i] = 27.5 saturatedintervalstop[i] = 34 timefieldon[i] = 20 timesaturated[i] = 27.5 timefieldoff[i] = 35 i = 13 shot[i] = 909 speed[i] = 400 current[i] = 700 saturatedfrequency[i] = 0.48 saturatedfrequencyerr[i] = 0.03 freqband_min[i] = 0.39 freqband_max[i] = 0.63 saturatedpower[i] = 0.12453 saturatedintervalstart[i] = 50 saturatedintervalstop[i] = 74 timefieldon[i] = 20 timesaturated[i] = 50 timefieldoff[i] = 75 i = 14 shot[i] = 911 speed[i] = 200 current[i] = 500 saturatedfrequency[i] = 0.132 saturatedfrequencyerr[i] = 0.02 freqband_min[i] = 0.11 freqband_max[i] = 0.16 saturatedpower[i] = 0.1837 saturatedintervalstart[i] = 50 saturatedintervalstop[i] = 79 timefieldon[i] = 20 timesaturated[i] = 50 timefieldoff[i] = 80 i = 15 shot[i] = 913 speed[i] = 200 current[i] = 600 saturatedfrequency[i] = 0.20 saturatedfrequencyerr[i] = 0.015 freqband_min[i] = 0.11 freqband_max[i] = 0.27 saturatedpower[i] = 2.2813 saturatedintervalstart[i] = 33 saturatedintervalstop[i] = 79 timefieldon[i] = 20 timesaturated[i] = 33 timefieldoff[i] = 80 i = 16 shot[i] = 914 speed[i] = 200 current[i] = 700 saturatedfrequency[i] = 0.24 saturatedfrequencyerr[i] = 0.01 freqband_min[i] = 0.17 freqband_max[i] = 0.32 saturatedpower[i] = 5.8443 saturatedintervalstart[i] = 34 saturatedintervalstop[i] = 74 timefieldon[i] = 20 timesaturated[i] = 34 timefieldoff[i] = 75 i = 17 shot[i] = 915 speed[i] = 200 current[i] = 1600 saturatedfrequency[i] = 0.25 saturatedfrequencyerr[i] = 0.03 freqband_min[i] = 0.12 freqband_max[i] = 0.40 saturatedpower[i] = 21.138 saturatedintervalstart[i] = 27 saturatedintervalstop[i] = 34 timefieldon[i] = 20 timesaturated[i] = 27 timefieldoff[i] = 35 i = 18 shot[i] = 916 speed[i] = 600 current[i] = 900 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 20 timesaturated[i] = nan timefieldoff[i] = 65 i = 19 shot[i] = 917 speed[i] = 600 current[i] = 1000 saturatedfrequency[i] = 0.36 saturatedfrequencyerr[i] = 0.05 freqband_min[i] = 0.29 freqband_max[i] = 0.50 saturatedpower[i] = 1.6104 saturatedintervalstart[i] = 43 saturatedintervalstop[i] = 59 timefieldon[i] = 20 timesaturated[i] = 43 timefieldoff[i] = 60 i = 20 shot[i] = 918 speed[i] = 600 current[i] = 1100 saturatedfrequency[i] = 0.40 saturatedfrequencyerr[i] = 0.03 freqband_min[i] = 0.25 freqband_max[i] = 0.60 saturatedpower[i] = 13.94 saturatedintervalstart[i] = 41 saturatedintervalstop[i] = 54 timefieldon[i] = 20 timesaturated[i] = 41 timefieldoff[i] = 55 i = 21 shot[i] = 919 speed[i] = 800 current[i] = 1100 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 20 timesaturated[i] = nan timefieldoff[i] = 55 i = 22 shot[i] = 920 speed[i] = 600 current[i] = 1300 saturatedfrequency[i] = 0.63 saturatedfrequencyerr[i] = 0.03 freqband_min[i] = 0.40 freqband_max[i] = 0.80 saturatedpower[i] = 74.017 saturatedintervalstart[i] = 32 saturatedintervalstop[i] = 44 timefieldon[i] = 20 timesaturated[i] = 32 timefieldoff[i] = 45 i = 23 shot[i] = 921 speed[i] = 1000 current[i] = 1300 saturatedfrequency[i] = 0.56 saturatedfrequencyerr[i] = 0.05 freqband_min[i] = 0.50 freqband_max[i] = 0.70 saturatedpower[i] = 2.9412 saturatedintervalstart[i] = 32 saturatedintervalstop[i] = 44 timefieldon[i] = 20 timesaturated[i] = 32 timefieldoff[i] = 45 i = 24 shot[i] = 922 speed[i] = 1000 current[i] = 1400 saturatedfrequency[i] = 0.72 saturatedfrequencyerr[i] = 0.03 freqband_min[i] = 0.50 freqband_max[i] = 1.0 saturatedpower[i] = 7.9399 saturatedintervalstart[i] = 30 saturatedintervalstop[i] = 39 timefieldon[i] = 20 timesaturated[i] = 30 timefieldoff[i] = 40 i = 25 shot[i] = 931 speed[i] = 100 current[i] = 1600 saturatedfrequency[i] = 0.20 saturatedfrequencyerr[i] = 0.15 freqband_min[i] = 0.2 freqband_max[i] = 0.4 saturatedpower[i] = 1.455 saturatedintervalstart[i] = 25 saturatedintervalstop[i] = 34 timefieldon[i] = 20 timesaturated[i] = 25 timefieldoff[i] = 35 i = 26 shot[i] = 932 speed[i] = 100 current[i] = 800 saturatedfrequency[i] = 0.125 saturatedfrequencyerr[i] = 0.01 freqband_min[i] = 0.075 freqband_max[i] = 0.175 saturatedpower[i] = 6.1972 saturatedintervalstart[i] = 38 saturatedintervalstop[i] = 69 timefieldon[i] = 20 timesaturated[i] = 38 timefieldoff[i] = 70 i = 27 shot[i] = 933 speed[i] = 100 current[i] = 500 saturatedfrequency[i] = 0.126 saturatedfrequencyerr[i] = 0.01 freqband_min[i] = 0.10 freqband_max[i] = 0.16 saturatedpower[i] = 2.9229 saturatedintervalstart[i] = 40 saturatedintervalstop[i] = 79 timefieldon[i] = 20 timesaturated[i] = 40 timefieldoff[i] = 80 i = 28 shot[i] = 934 speed[i] = 100 current[i] = 400 saturatedfrequency[i] = 0.20 saturatedfrequencyerr[i] = 0.015 freqband_min[i] = 0.12 freqband_max[i] = 0.30 saturatedpower[i] = 1.9822 saturatedintervalstart[i] = 45 saturatedintervalstop[i] = 79 timefieldon[i] = 20 timesaturated[i] = 45 timefieldoff[i] = 80 i = 29 shot[i] = 935 speed[i] = 100 current[i] = 300 saturatedfrequency[i] = nan saturatedfrequencyerr[i] = nan freqband_min[i] = nan freqband_max[i] = nan saturatedpower[i] = nan saturatedintervalstart[i] = nan saturatedintervalstop[i] = nan timefieldon[i] = 20 timesaturated[i] = nan timefieldoff[i] = 80 def get_data(): mrized_data = {'shot': shot, 'speed': speed, 'current': current, 'saturatedfrequency': saturatedfrequency, 'saturatedfrequencyerr': saturatedfrequencyerr, 'saturatedpower': saturatedpower, 'timefieldon': timefieldon, 'timesaturated': timesaturated, 'timefieldoff': timefieldoff, 'saturatedshear': saturatedshear} return mrized_data rho = 6.36 #Density of GaInSn in gm/cm^3 eta = 2.57e3 #Magnetic diffusivity in cm^2/sec def plot_amplitudes(elsasser = 1): mrized_data = get_data() scatter(mrized_data['speed']*2*pi/60, mrized_data['current']*2.8669, mrized_data['saturatedpower']*1000000/(mrized_data['speed']*mrized_data['speed']), label='_nolegend_') #also plot the xs. nan_idx = isnan(mrized_data['saturatedpower']) plot(mrized_data['speed'][nan_idx]*2*pi/60, mrized_data['current'][nan_idx]*2.8669, 'x', color='black', label='_nolegend_') xlabel("IC Speed [rad/sec]") ylabel("B [Gauss]") title("$P_{fundamental}/\Omega_{IC}^2$") #Now plot line for Elsasser number constant #Defined as v_A^2/(eta*Omega) Omega = linspace(0,1200, 100) Omega = Omega*2*pi/60 B_crit = sqrt(4*pi*rho*eta*Omega*elsasser) labelstring = "$\Lambda = $" + str(elsasser) axes = axis() plot(Omega, B_crit, color='k', label=labelstring) axis(axes) legend(loc='lower right') def plot_frequencies(): mrized_data = get_data() scatter(mrized_data['speed'], mrized_data['current'], (mrized_data['saturatedfrequency'] + mrized_data['speed']*53/(60*400))*100000/mrized_data['speed']) xlabel("IC Speed [RPM]") ylabel("Coil Current [A]") def plot_quantity_at_speed(quantity, speed): mrized_data = get_data() count = 0 for i in range(0, mrized_data['speed'].size): if (mrized_data['speed'][i] == speed): count = count + 1 quantity_array = zeros(count) current_array = zeros(count) index = 0 for i in range(0, mrized_data['speed'].size): if (mrized_data['speed'][i] == speed): quantity_array[index] = mrized_data[quantity][i] current_array[index] = mrized_data['current'][i] index = index + 1 plot(current_array, quantity_array, 'o') xlabel("Current [A]") ylabel(quantity) title("MRI-Zed oscillations")
Python
UTF-8
3,179
2.71875
3
[]
no_license
import numpy as np import pandas as pd import matplotlib.pyplot as plt from repositories.groups_repository import groups_repo from repositories.subjects_repository import subjects_repo from repositories.students_repository import students_repo from repositories.marks_repository import marks_repo graphics_folder_path = 'outputs/plots/' def create_average_mark_in_group_plot(): data = {} groups = groups_repo.find_all() for g in groups: group_id = g['_id'] group_name = g['name'] group_marks = marks_repo.get_marks_by_group(group_id) mean_value = np.mean(list(map(lambda m: m['value'], group_marks))) data[group_name] = mean_value save_figure('average_mark_in_group', lambda: plt.bar(data.keys(), data.values())) def create_average_mark_by_subject_plot(): data = {} subjects = subjects_repo.find_all() for s in subjects: subject_id = s['_id'] subject_name = s['name'] subject_marks = marks_repo.find({'subject_id': subject_id}) mapped_marks = list(map(lambda m: m['value'], subject_marks)) mean_value = np.mean(mapped_marks) if len(mapped_marks) > 0 else 0 data[subject_name] = mean_value save_figure('average_mark_by_subject', lambda: plt.bar(data.keys(), data.values())) def create_average_mark_in_group_by_each_subject_plot(): data = {} groups = groups_repo.find_all() subjects = subjects_repo.find_all() for s in subjects: subject_id = s['_id'] subject_name = s['name'] values = [] for g in groups: group_id = g['_id'] marks = marks_repo.get_marks_by_group_and_subject(group_id, subject_id) mapped_marks = list(map(lambda m: m['value'], marks)) mean_value = np.mean(mapped_marks) if len(mapped_marks) > 0 else 0 values.append(mean_value) data[subject_name] = values plot = pd.DataFrame(data, index=list(map(lambda m: m['name'], groups))).plot(kind='bar') save_figure('average_mark_in_group_by_each_subject', plot=plot) def create_age_mark_plot(): data = {} ages = students_repo.get_ages() for a in ages: marks = marks_repo.get_marks_by_student_age(a) mapped_marks = list(map(lambda m: m['value'], marks)) mean_value = np.mean(mapped_marks) if len(mapped_marks) > 0 else 0 data[a] = mean_value save_figure('age_mark_plot', lambda: plt.plot(data.keys(), data.values())) def create_group_activity_pie_plot(): data = {} groups = groups_repo.find_all() for g in groups: group_id = g['_id'] group_name = g['name'] count = marks_repo.get_group_marks_count(group_id) data[group_name] = count plt.title('Groups activity') plt.axis('equal') save_figure('group_activity_pie', lambda: plt.pie(data.values(), labels=data.keys(), shadow=True, autopct='%1.1f%%')) def save_figure(image_name, create_figure=None, plot=None): fig = plt.figure() if plot is None else plot.get_figure() if create_figure is not None: create_figure() fig.savefig(graphics_folder_path + image_name + '.png', dpi=fig.dpi)
Java
UTF-8
343
1.648438
2
[]
no_license
package icons; import com.intellij.openapi.util.IconLoader; import javax.swing.*; /** * Icon interface used to get the correct icons for the plugin. */ public interface DemarkIcons { // icon by <div>Icons made by Gregor Cresnar from Flaticon // licensed by Creative Commons BY 3.0 Icon TOGGLE = IconLoader.getIcon("/icons/eye.png"); }
C
UTF-8
22,847
2.90625
3
[ "Unlicense" ]
permissive
#include "options.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <errno.h> #include <ctype.h> struct sn_parse_context { /* Initial state */ struct sn_commandline *def; struct sn_option *options; void *target; int argc; char **argv; unsigned long requires; /* Current values */ unsigned long mask; int args_left; char **arg; char *data; char **last_option_usage; }; static int sn_has_arg (struct sn_option *opt) { switch (opt->type) { case SN_OPT_INCREMENT: case SN_OPT_DECREMENT: case SN_OPT_SET_ENUM: case SN_OPT_HELP: return 0; case SN_OPT_ENUM: case SN_OPT_STRING: case SN_OPT_BLOB: case SN_OPT_FLOAT: case SN_OPT_INT: case SN_OPT_LIST_APPEND: case SN_OPT_LIST_APPEND_FMT: case SN_OPT_READ_FILE: return 1; } assert(0); } static void sn_print_usage (struct sn_parse_context *ctx, FILE *stream) { int i; int first; struct sn_option *opt; fprintf (stream, " %s ", ctx->argv[0]); /* Print required options (long names) */ first = 1; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (opt->mask_set & ctx->requires) { if (first) { first = 0; fprintf (stream, "{--%s", opt->longname); } else { fprintf (stream, "|--%s", opt->longname); } } } if (!first) { fprintf (stream, "} "); } /* Print flag short options */ first = 1; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (opt->mask_set & ctx->requires) continue; /* already printed */ if (opt->shortname && !sn_has_arg (opt)) { if (first) { first = 0; fprintf (stream, "[-%c", opt->shortname); } else { fprintf (stream, "%c", opt->shortname); } } } if (!first) { fprintf (stream, "] "); } /* Print short options with arguments */ for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (opt->mask_set & ctx->requires) continue; /* already printed */ if (opt->shortname && sn_has_arg (opt) && opt->metavar) { fprintf (stream, "[-%c %s] ", opt->shortname, opt->metavar); } } fprintf (stream, "[options] \n"); /* There may be long options too */ } static char *sn_print_line (FILE *out, char *str, size_t width) { int i; if (strlen (str) < width) { fprintf (out, "%s", str); return ""; } for (i = width; i > 1; --i) { if (isspace (str[i])) { fprintf (out, "%.*s", i, str); return str + i + 1; } } /* no break points, just print as is */ fprintf (out, "%s", str); return ""; } static void sn_print_help (struct sn_parse_context *ctx, FILE *stream) { int i; int optlen; struct sn_option *opt; char *last_group; char *cursor; fprintf (stream, "Usage:\n"); sn_print_usage (ctx, stream); fprintf (stream, "\n%s\n", ctx->def->short_description); last_group = NULL; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (!last_group || last_group != opt->group || strcmp (last_group, opt->group)) { fprintf (stream, "\n"); fprintf (stream, "%s:\n", opt->group); last_group = opt->group; } fprintf (stream, " --%s", opt->longname); optlen = 3 + strlen (opt->longname); if (opt->shortname) { fprintf (stream, ",-%c", opt->shortname); optlen += 3; } if (sn_has_arg (opt)) { if (opt->metavar) { fprintf (stream, " %s", opt->metavar); optlen += strlen (opt->metavar) + 1; } else { fprintf (stream, " ARG"); optlen += 4; } } if (optlen < 23) { fputs (&" "[optlen], stream); cursor = sn_print_line (stream, opt->description, 80-24); } else { cursor = opt->description; } while (*cursor) { fprintf (stream, "\n "); cursor = sn_print_line (stream, cursor, 80-24); } fprintf (stream, "\n"); } } static void sn_print_option (struct sn_parse_context *ctx, int opt_index, FILE *stream) { char *ousage; char *oend; size_t olen; struct sn_option *opt; opt = &ctx->options[opt_index]; ousage = ctx->last_option_usage[opt_index]; if (*ousage == '-') { /* Long option */ oend = strchr (ousage, '='); if (!oend) { olen = strlen (ousage); } else { olen = (oend - ousage); } if (olen != strlen (opt->longname)+2) { fprintf (stream, " %.*s[%s] ", (int)olen, ousage, opt->longname + (olen-2)); } else { fprintf (stream, " %s ", ousage); } } else if (ousage == ctx->argv[0]) { /* Binary name */ fprintf (stream, " %s (executable) ", ousage); } else { /* Short option */ fprintf (stream, " -%c (--%s) ", *ousage, opt->longname); } } static void sn_option_error (char *message, struct sn_parse_context *ctx, int opt_index) { fprintf (stderr, "%s: Option", ctx->argv[0]); sn_print_option (ctx, opt_index, stderr); fprintf (stderr, "%s\n", message); exit (1); } static void sn_memory_error (struct sn_parse_context *ctx) { fprintf (stderr, "%s: Memory error while parsing command-line", ctx->argv[0]); abort (); } static void sn_invalid_enum_value (struct sn_parse_context *ctx, int opt_index, char *argument) { struct sn_option *opt; struct sn_enum_item *items; opt = &ctx->options[opt_index]; items = (struct sn_enum_item *)opt->pointer; fprintf (stderr, "%s: Invalid value ``%s'' for", ctx->argv[0], argument); sn_print_option (ctx, opt_index, stderr); fprintf (stderr, ". Options are:\n"); for (;items->name; ++items) { fprintf (stderr, " %s\n", items->name); } exit (1); } static void sn_option_conflict (struct sn_parse_context *ctx, int opt_index) { unsigned long mask; int i; int num_conflicts; struct sn_option *opt; fprintf (stderr, "%s: Option", ctx->argv[0]); sn_print_option (ctx, opt_index, stderr); fprintf (stderr, "conflicts with the following options:\n"); mask = ctx->options[opt_index].conflicts_mask; num_conflicts = 0; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (i == opt_index) continue; if (ctx->last_option_usage[i] && opt->mask_set & mask) { num_conflicts += 1; fprintf (stderr, " "); sn_print_option (ctx, i, stderr); fprintf (stderr, "\n"); } } if (!num_conflicts) { fprintf (stderr, " "); sn_print_option (ctx, opt_index, stderr); fprintf (stderr, "\n"); } exit (1); } static void sn_print_requires (struct sn_parse_context *ctx, unsigned long mask) { int i; struct sn_option *opt; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (opt->mask_set & mask) { fprintf (stderr, " --%s\n", opt->longname); if (opt->shortname) { fprintf (stderr, " -%c\n", opt->shortname); } } } exit (1); } static void sn_option_requires (struct sn_parse_context *ctx, int opt_index) { fprintf (stderr, "%s: Option", ctx->argv[0]); sn_print_option (ctx, opt_index, stderr); fprintf (stderr, "requires at least one of the following options:\n"); sn_print_requires (ctx, ctx->options[opt_index].requires_mask); exit (1); } static void sn_append_string (struct sn_parse_context *ctx, struct sn_option *opt, char *str) { struct sn_string_list *lst; lst = (struct sn_string_list *)( ((char *)ctx->target) + opt->offset); if (lst->items) { lst->num += 1; lst->items = realloc (lst->items, sizeof (char *) * lst->num); } else { lst->items = malloc (sizeof (char *)); lst->num = 1; } if (!lst->items) { sn_memory_error (ctx); } lst->items[lst->num-1] = str; } static void sn_append_string_to_free (struct sn_parse_context *ctx, struct sn_option *opt, char *str) { struct sn_string_list *lst; lst = (struct sn_string_list *)( ((char *)ctx->target) + opt->offset); if (lst->to_free) { lst->to_free_num += 1; lst->to_free = realloc (lst->items, sizeof (char *) * lst->to_free_num); } else { lst->to_free = malloc (sizeof (char *)); lst->to_free_num = 1; } if (!lst->items) { sn_memory_error (ctx); } lst->to_free[lst->to_free_num-1] = str; } static void sn_process_option (struct sn_parse_context *ctx, int opt_index, char *argument) { struct sn_option *opt; struct sn_enum_item *items; char *endptr; struct sn_blob *blob; FILE *file; char *data; size_t data_len; size_t data_buf; int bytes_read; opt = &ctx->options[opt_index]; if (ctx->mask & opt->conflicts_mask) { sn_option_conflict (ctx, opt_index); } ctx->mask |= opt->mask_set; switch (opt->type) { case SN_OPT_HELP: sn_print_help (ctx, stdout); exit (0); return; case SN_OPT_INT: *(long *)(((char *)ctx->target) + opt->offset) = strtol (argument, &endptr, 0); if (endptr == argument || *endptr != 0) { sn_option_error ("requires integer argument", ctx, opt_index); } return; case SN_OPT_INCREMENT: *(int *)(((char *)ctx->target) + opt->offset) += 1; return; case SN_OPT_DECREMENT: *(int *)(((char *)ctx->target) + opt->offset) -= 1; return; case SN_OPT_ENUM: items = (struct sn_enum_item *)opt->pointer; for (;items->name; ++items) { if (!strcmp (items->name, argument)) { *(int *)(((char *)ctx->target) + opt->offset) = \ items->value; return; } } sn_invalid_enum_value (ctx, opt_index, argument); return; case SN_OPT_SET_ENUM: *(int *)(((char *)ctx->target) + opt->offset) = \ *(int *)(opt->pointer); return; case SN_OPT_STRING: *(char **)(((char *)ctx->target) + opt->offset) = argument; return; case SN_OPT_BLOB: blob = (struct sn_blob *)(((char *)ctx->target) + opt->offset); blob->data = argument; blob->length = strlen (argument); blob->need_free = 0; return; case SN_OPT_FLOAT: #if defined SN_HAVE_WINDOWS *(float *)(((char *)ctx->target) + opt->offset) = (float) atof (argument); #else *(float *)(((char *)ctx->target) + opt->offset) = strtof (argument, &endptr); if (endptr == argument || *endptr != 0) { sn_option_error ("requires float point argument", ctx, opt_index); } #endif return; case SN_OPT_LIST_APPEND: sn_append_string (ctx, opt, argument); return; case SN_OPT_LIST_APPEND_FMT: data_buf = strlen (argument) + strlen (opt->pointer); data = malloc (data_buf); #if defined SN_HAVE_WINDOWS data_len = _snprintf_s (data, data_buf, _TRUNCATE, opt->pointer, argument); #else data_len = snprintf (data, data_buf, opt->pointer, argument); #endif assert (data_len < data_buf); sn_append_string (ctx, opt, data); sn_append_string_to_free (ctx, opt, data); return; case SN_OPT_READ_FILE: if (!strcmp (argument, "-")) { file = stdin; } else { file = fopen (argument, "r"); if (!file) { fprintf (stderr, "Error opening file ``%s'': %s\n", argument, strerror (errno)); exit (2); } } data = malloc (4096); if (!data) sn_memory_error (ctx); data_len = 0; data_buf = 4096; for (;;) { bytes_read = fread (data + data_len, 1, data_buf - data_len, file); data_len += bytes_read; if (feof (file)) break; if (data_buf - data_len < 1024) { if (data_buf < (1 << 20)) { data_buf *= 2; /* grow twice until not too big */ } else { data_buf += 1 << 20; /* grow 1 Mb each time */ } data = realloc (data, data_buf); if (!data) sn_memory_error (ctx); } } if (data_len != data_buf) { data = realloc (data, data_len); assert (data); } if (ferror (file)) { #if defined _MSC_VER #pragma warning (push) #pragma warning (disable:4996) #endif fprintf (stderr, "Error reading file ``%s'': %s\n", argument, strerror (errno)); #if defined _MSC_VER #pragma warning (pop) #endif exit (2); } if (file != stdin) { fclose (file); } blob = (struct sn_blob *)(((char *)ctx->target) + opt->offset); blob->data = data; blob->length = data_len; blob->need_free = 1; return; } abort (); } static void sn_parse_arg0 (struct sn_parse_context *ctx) { int i; struct sn_option *opt; char *arg0; arg0 = strrchr (ctx->argv[0], '/'); if (arg0 == NULL) { arg0 = ctx->argv[0]; } else { arg0 += 1; /* Skip slash itself */ } for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) return; if (opt->arg0name && !strcmp (arg0, opt->arg0name)) { assert (!sn_has_arg (opt)); ctx->last_option_usage[i] = ctx->argv[0]; sn_process_option (ctx, i, NULL); } } } static void sn_error_ambiguous_option (struct sn_parse_context *ctx) { struct sn_option *opt; char *a, *b; char *arg; arg = ctx->data+2; fprintf (stderr, "%s: Ambiguous option ``%s'':\n", ctx->argv[0], ctx->data); for (opt = ctx->options; opt->longname; ++opt) { for (a = opt->longname, b = arg; ; ++a, ++b) { if (*b == 0 || *b == '=') { /* End of option on command-line */ fprintf (stderr, " %s\n", opt->longname); break; } else if (*b != *a) { break; } } } exit (1); } static void sn_error_unknown_long_option (struct sn_parse_context *ctx) { fprintf (stderr, "%s: Unknown option ``%s''\n", ctx->argv[0], ctx->data); exit (1); } static void sn_error_unexpected_argument (struct sn_parse_context *ctx) { fprintf (stderr, "%s: Unexpected argument ``%s''\n", ctx->argv[0], ctx->data); exit (1); } static void sn_error_unknown_short_option (struct sn_parse_context *ctx) { fprintf (stderr, "%s: Unknown option ``-%c''\n", ctx->argv[0], *ctx->data); exit (1); } static int sn_get_arg (struct sn_parse_context *ctx) { if (!ctx->args_left) return 0; ctx->args_left -= 1; ctx->arg += 1; ctx->data = *ctx->arg; return 1; } static void sn_parse_long_option (struct sn_parse_context *ctx) { struct sn_option *opt; char *a, *b; int longest_prefix; int cur_prefix; int best_match; char *arg; int i; arg = ctx->data+2; longest_prefix = 0; best_match = -1; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; for (a = opt->longname, b = arg;; ++a, ++b) { if (*b == 0 || *b == '=') { /* End of option on command-line */ cur_prefix = a - opt->longname; if (!*a) { /* Matches end of option name */ best_match = i; longest_prefix = cur_prefix; goto finish; } if (cur_prefix == longest_prefix) { best_match = -1; /* Ambiguity */ } else if (cur_prefix > longest_prefix) { best_match = i; longest_prefix = cur_prefix; } break; } else if (*b != *a) { break; } } } finish: if (best_match >= 0) { opt = &ctx->options[best_match]; ctx->last_option_usage[best_match] = ctx->data; if (arg[longest_prefix] == '=') { if (sn_has_arg (opt)) { sn_process_option (ctx, best_match, arg + longest_prefix + 1); } else { sn_option_error ("does not accept argument", ctx, best_match); } } else { if (sn_has_arg (opt)) { if (sn_get_arg (ctx)) { sn_process_option (ctx, best_match, ctx->data); } else { sn_option_error ("requires an argument", ctx, best_match); } } else { sn_process_option (ctx, best_match, NULL); } } } else if (longest_prefix > 0) { sn_error_ambiguous_option (ctx); } else { sn_error_unknown_long_option (ctx); } } static void sn_parse_short_option (struct sn_parse_context *ctx) { int i; struct sn_option *opt; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (!opt->shortname) continue; if (opt->shortname == *ctx->data) { ctx->last_option_usage[i] = ctx->data; if (sn_has_arg (opt)) { if (ctx->data[1]) { sn_process_option (ctx, i, ctx->data+1); } else { if (sn_get_arg (ctx)) { sn_process_option (ctx, i, ctx->data); } else { sn_option_error ("requires an argument", ctx, i); } } ctx->data = ""; /* end of short options anyway */ } else { sn_process_option (ctx, i, NULL); ctx->data += 1; } return; } } sn_error_unknown_short_option (ctx); } static void sn_parse_arg (struct sn_parse_context *ctx) { if (ctx->data[0] == '-') { /* an option */ if (ctx->data[1] == '-') { /* long option */ if (ctx->data[2] == 0) { /* end of options */ return; } sn_parse_long_option (ctx); } else { ctx->data += 1; /* Skip minus */ while (*ctx->data) { sn_parse_short_option (ctx); } } } else { sn_error_unexpected_argument (ctx); } } void sn_check_requires (struct sn_parse_context *ctx) { int i; struct sn_option *opt; for (i = 0;; ++i) { opt = &ctx->options[i]; if (!opt->longname) break; if (!ctx->last_option_usage[i]) continue; if (opt->requires_mask && (opt->requires_mask & ctx->mask) != opt->requires_mask) { sn_option_requires (ctx, i); } } if ((ctx->requires & ctx->mask) != ctx->requires) { fprintf (stderr, "%s: At least one of the following required:\n", ctx->argv[0]); sn_print_requires (ctx, ctx->requires & ~ctx->mask); exit (1); } } void sn_parse_options (struct sn_commandline *cline, void *target, int argc, char **argv) { struct sn_parse_context ctx; int num_options; ctx.def = cline; ctx.options = cline->options; ctx.target = target; ctx.argc = argc; ctx.argv = argv; ctx.requires = cline->required_options; for (num_options = 0; ctx.options[num_options].longname; ++num_options); ctx.last_option_usage = calloc (sizeof (char *), num_options); if (!ctx.last_option_usage) sn_memory_error (&ctx); ctx.mask = 0; ctx.args_left = argc - 1; ctx.arg = argv; sn_parse_arg0 (&ctx); while (sn_get_arg (&ctx)) { sn_parse_arg (&ctx); } sn_check_requires (&ctx); free (ctx.last_option_usage); } void sn_free_options (struct sn_commandline *cline, void *target) { int i, j; struct sn_option *opt; struct sn_blob *blob; struct sn_string_list *lst; for (i = 0;; ++i) { opt = &cline->options[i]; if (!opt->longname) break; switch(opt->type) { case SN_OPT_LIST_APPEND: case SN_OPT_LIST_APPEND_FMT: lst = (struct sn_string_list *)(((char *)target) + opt->offset); if(lst->items) { free(lst->items); lst->items = NULL; } if(lst->to_free) { for(j = 0; j < lst->to_free_num; ++j) { free(lst->to_free[j]); } free(lst->to_free); lst->to_free = NULL; } break; case SN_OPT_READ_FILE: case SN_OPT_BLOB: blob = (struct sn_blob *)(((char *)target) + opt->offset); if(blob->need_free && blob->data) { free(blob->data); blob->need_free = 0; } break; default: break; } } }
TypeScript
UTF-8
456
2.734375
3
[]
no_license
import { Injectable } from '@angular/core'; import { APP_CONSTANTS } from '../constants/app.constants'; /** * Service which lets you choose storage of your choice */ @Injectable() export class WebStorageService { /** * Returns storage to be used to store data based on type * @param type local or session */ getStorage(type: string): Storage { return type === APP_CONSTANTS.WEB_STORAGE_TYPE.LOCAL ? localStorage : sessionStorage; } }
Java
UTF-8
3,115
3.125
3
[]
no_license
package com.car.admin; import com.car.admin.util.DateUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTest { public static void main(String[] args) throws ParseException { Date beginDate = new Date(); String end = "2019-5-31"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date endDate = format.parse(end); //获取开始时间和结束时间之间相差多少天 //System.out.println("获取开始时间和结束时间之间相差多少天:"+DateUtils.getSubDays(beginDate,endDate)); //判断是否是在同一天,true代表同一天,false代表不是同一天 //System.out.println(DateUtils.isSameDate(beginDate,endDate)); //获取开始日期和结束日期之间的分钟数 //System.out.println("获取开始日期和结束日期之间的分钟数:"+DateUtils.getSubMinutes(beginDate,endDate)); //获取开始日期和结束日期之间的毫秒数 //System.out.println("获取开始日期和结束日期之间的毫秒数:"+DateUtils.getSubMsec(beginDate,endDate)); //通过长整型计算持续时间 //System.out.println(DateUtils.calculateDuration(80000000)); //转换为中文日期表示 //System.out.println(DateUtils.changeToLocalString(beginDate)); //根据当前时间获取几天前的日期 //System.out.println("当前时间两天前的时间:"+DateUtils.getBeforeDate(2)); //获取当前时间 小时 //System.out.println("当前时间的小时:"+DateUtils.currentHour()); //获取当前分钟数 //System.out.println("当前时间的分钟:"+DateUtils.currentMinute()); //该值根据log决定,当log以毫秒为单位时,flag=false时log以秒为单位,false=true时log以毫秒为单位 //根据毫秒计算时分 //System.out.println(DateUtils.formatLongToTime(20190522140852014L,false)); //返回经过了几小时几分钟 //System.out.println(DateUtils.formatLongToTime2(20190522140852014L,false)); //返回精确到毫秒的当前时间 //System.out.println(DateUtils.getCurrentByYmdHmsSSS()); //返回精确到秒的当前时间 //System.out.println(DateUtils.getCurrentByYmdHms()); /** * 凌晨 * * @param date * @flag 0 返回yyyy-MM-dd 00:00:00日期<br> * 1 返回yyyy-MM-dd 23:59:59日期 * @return */ //System.out.println(DateUtils.weeHours(beginDate,1)); //获取当天最早时间 Date startTime = DateUtils.getStartTime(); //System.out.println(startTime); //获取当天最晚时间 //System.out.println(DateUtils.getEndTime()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date parse = simpleDateFormat.parse("2019-8-31"); //判断一个日期是否是周末 System.out.println(DateUtils.ifWeekend(parse)); } }
JavaScript
UTF-8
1,679
2.578125
3
[ "MIT" ]
permissive
import React, { Component } from "react"; export default class NewGame extends Component { constructor(props) { super(props); this.state = { name: "", error: "" }; this.handleSubmit = this.handleSubmit.bind(this); this.handleNameChange = this.handleNameChange.bind(this); this.handleRedirect = this.handleRedirect.bind(this); } handleSubmit(e) { e.preventDefault(); const name = this.state.name ? this.state.name.trim() : undefined; Meteor.call("game.insert", name, (error, _id) => { if (error) { console.log(error.reason); this.setState({ error: error.reason }); } else { this.setState({ name: "", error: "" }); this.props.history.push(`/${_id}`); } }); } handleNameChange(e) { const name = e.target.value; this.setState({ name }); } handleRedirect(e) { e.preventDefault(); const name = this.state.name ? this.state.name.trim() : undefined; if(name) { this.props.history.push(`/${name}`); } else { console.log('Game id required'); } } render() { return ( <div> <form onSubmit={this.handleSubmit} noValidate> <input type="text" name="name" ref={name => (this.name = name)} placeholder="Team name or Game id" value={this.state.name} onChange={this.handleNameChange} /> <br /> <button type="submit">Create new</button> <button onClick={this.handleRedirect}>Redirect to old</button> </form> </div> ); } }
Python
UTF-8
485
2.71875
3
[]
no_license
import os import subprocess f = open("Log_2019_12_12_13_24.txt", "r") #print(os.getcwd()) if f.mode == "r": contents = f.readlines() f.close() dict = {} for line in contents: if(line.startswith("Section")): split = line.split('_') if split[0] not in dict.keys(): dict[split[0]] = {} if split[1] not in dict[split[0]].keys(): dict[split[0]][split[1]] = 1 else: dict[split[0]][split[1]] += 1 print(dict)
Go
UTF-8
1,788
2.546875
3
[ "MIT" ]
permissive
package models import ( "encoding/json" "strconv" "strings" ) var ( PresenceexpandMarshalled = false ) // This struct is here to use the useless readonly properties so that their required imports don't throw an unused error (time, etc.) type PresenceexpandDud struct { Id string `json:"id"` SelfUri string `json:"selfUri"` } // Presenceexpand type Presenceexpand struct { // Name Name string `json:"name"` // Presences - An array of user presences Presences []Userpresence `json:"presences"` // OutOfOffices - An array of out of office statuses OutOfOffices []Outofoffice `json:"outOfOffices"` } // String returns a JSON representation of the model func (o *Presenceexpand) String() string { o.Presences = []Userpresence{{}} o.OutOfOffices = []Outofoffice{{}} j, _ := json.Marshal(o) str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\u`, `\u`, -1)) return str } func (u *Presenceexpand) MarshalJSON() ([]byte, error) { type Alias Presenceexpand if PresenceexpandMarshalled { return []byte("{}"), nil } PresenceexpandMarshalled = true return json.Marshal(&struct { Name string `json:"name"` Presences []Userpresence `json:"presences"` OutOfOffices []Outofoffice `json:"outOfOffices"` *Alias }{ Presences: []Userpresence{{}}, OutOfOffices: []Outofoffice{{}}, Alias: (*Alias)(u), }) }
Markdown
UTF-8
328
2.59375
3
[]
no_license
# Typewriter-Animation-Effects <h4>Typewriter Animation Effects Using Pure CSS</h4> Just download the respository and unzip the file. </br> Open index.html file and here you go. </br> Enjoy the typewriter animation effects.</br> <h3>Follow Me in Github for more intresting projects.</h3></br> ![](typewriter-animation.gif)
Python
UTF-8
729
4.375
4
[ "MIT" ]
permissive
"""Fix the loop! Your collegue wrote an simple loop to list his favourite animals. But there seems to be a minor mistake in the grammar, which prevents the program to work. If you pass the list of your favourite animals to the function, you should get the list of the animals with orderings and newlines added #1 Best Practices Solution by Unnamed, d0486467: def list_animals(animals): return ''.join('{}. {}\n'.format(i, x) for (i, x) in enumerate(animals, 1)) """ def list_animals(animals): """Takes a list of animals and makes them a numbered list.""" animal_list = [] for idx, animal in enumerate(animals): animal_list.append("{}. {}\n".format(idx + 1, animal)) return ''.join(animal_list)
Java
UTF-8
3,551
2.375
2
[]
no_license
package simcity.buildings.restaurant.six; import java.util.Random; import java.util.Timer; import java.util.concurrent.Semaphore; import simcity.PersonAgent; import simcity.Role; import simcity.SimSystem; import simcity.buildings.restaurant.five.RestaurantFiveSystem; import simcity.buildings.restaurant.five.RestaurantFiveCustomerRole.AgentEvent; import simcity.buildings.restaurant.five.RestaurantFiveCustomerRole.AgentState; import simcity.gui.restaurantfive.RestaurantFiveCustomerGui; import simcity.gui.restaurantsix.RestaurantSixCustomerGui; import simcity.gui.trace.AlertLog; import simcity.gui.trace.AlertTag; import simcity.interfaces.restaurant.six.RestaurantSixCashier; import simcity.interfaces.restaurant.six.RestaurantSixCustomer; import simcity.interfaces.restaurant.six.RestaurantSixHost; import simcity.interfaces.restaurant.six.RestaurantSixWaiter; public class RestaurantSixCustomerRole extends Role implements RestaurantSixCustomer{ private RestaurantSixSystem restaurant = null; Timer timer = new Timer(); private String myOrder;// = "Chicken"; private double myBill; Random choiceGenerator = new Random(); private Semaphore atDest = new Semaphore(0, true); // This is the table the customer is currently going to private int myTable = -1; private int waitingX = 0; private int waitingY = 0; private RestaurantSixMenu myMenu; // agent correspondents private RestaurantSixHost host; private RestaurantSixWaiter waiter; private RestaurantSixCashier cashier; // private boolean isHungry = false; //hack for gui public enum AgentState { DoingNothing, WaitingInRestaurant, BeingSeated, Seated, ReadyToOrder, Ordered, Eating, DoneEating, WaitingForCheck, Paying, Leaving }; private AgentState state = AgentState.DoingNothing;//The start state public enum AgentEvent { none, gotHungry, followWaiter, seated, noTables, readyToOrder, ordering, reOrdering, ordered, foodArriving, doneEating, gotCheck, doneLeaving, donePaying }; AgentEvent event = AgentEvent.none; public RestaurantSixCustomerRole(PersonAgent p){ person = p; this.gui = new RestaurantSixCustomerGui(this); } // Messages @Override public void msgNoTables(int x, int y) { AlertLog.getInstance().logMessage(AlertTag.valueOf(restaurant.getName()), "RestaurantSixCustomer: " + person.getName(), "I was told there are no tables here!"); } // Scheduler @Override public boolean pickAndExecuteAnAction() { // TODO Auto-generated method stub AlertLog.getInstance().logMessage(AlertTag.valueOf(restaurant.getName()), "RestaurantSixCustomer: " + person.getName(), "Clayton in da sched"); return false; } // Actions // Utilities @Override public void atDestination() { atDest.release(); } @Override public void exitBuilding() { // TODO Auto-generated method stub } @Override public void enterBuilding(SimSystem s) { restaurant = (RestaurantSixSystem)s; AlertLog.getInstance().logMessage(AlertTag.valueOf(restaurant.getName()), "RestaurantSixCustomer: " + person.getName(), "Can't wait to eat at this restaurant!"); //int n = restaurant.getHost().getNumWaitingCustomers(); ((RestaurantSixCustomerGui) gui).DoGoToHost(); try { atDest.acquire(); } catch (InterruptedException e) { //e.printStackTrace(); } restaurant.getHost().msgIWantFood(this); state = AgentState.DoingNothing; event = AgentEvent.gotHungry; stateChanged(); } @Override public String getCustomerName() { // TODO Auto-generated method stub return null; } }
Python
UTF-8
934
2.890625
3
[]
no_license
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib class Auto_email(): def enviar_correo(self,destinatario,remitente,password,mensaje,titulo): ## "Instanciando" el mensaje: msg = MIMEMultipart() msg['From'] = remitente msg['To'] = destinatario msg['Subject'] = titulo ## Agregando el mensaje en el cuerpo del correo: msg.attach(MIMEText(mensaje, 'plain')) #Indicando el servidor y el puerto: server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() # Ingresando credenciales para enviar el correo server.login(msg['From'], password) # Enviando el mensaje a través del "server". server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() #print "successfully sent email to %s:" % (msg['To']) print('Ya acabó')
TypeScript
UTF-8
4,638
2.921875
3
[]
no_license
class SegmentedMedia { private frameWidth: number private img: p5.Image private urlRoot: string private imgTags: string private pieceHeight: number private xPos: number private noOfSegments: number private segmentPosition: number[] private selectedSegment: number constructor() { this.frameWidth = 350 this.urlRoot = 'https://source.unsplash.com/' this.imgTags = 'cartoons' this.img = loadImage(this.getImgUrl(), this.imageLoaded) this.pieceHeight = 0 this.xPos = 0 this.noOfSegments = 3 this.segmentPosition = [] this.selectedSegment = -1 } /**Gets the basic offset for the media*/ public getOffset() { let topOffset = height / 4 let leftOffset = (width / 2) - (this.frameWidth / 2) return [topOffset, leftOffset] } /**Gets the theme*/ public setTag(theme:string){ this.imgTags = theme } /**Gets the imgUrl*/ private getImgUrl(): string { let imgUrl = this.urlRoot + this.frameWidth + "x" + this.frameWidth + "/?" + this.imgTags + "/sig=" + round(random(100)) return imgUrl } /**Gets the reference frame*/ private referenceFrame() { noFill() stroke('red') strokeWeight(4) let offsets = this.getOffset() rect(offsets[1], offsets[0], this.frameWidth, this.frameWidth) } /** * A callback function used to check if the image is loaded * @param _img teh image to be checked */ private imageLoaded(_img: p5.Image) { isImageLoaded = true } /** * Draws the moving image * @param offsets the offsets set for the game */ private drawMovingImage(offsets: number[]) { this.pieceHeight = (this.frameWidth / this.noOfSegments) //updates the x-position this.xPos += this.noOfSegments * 1.5 if (this.xPos >= width) { this.xPos = 0 } for (let i = 0; i < this.noOfSegments; i++) { //Updates array with the new position if (i > this.selectedSegment) { this.segmentPosition[i] = this.xPos //reverse direction for alternate images if (i % 2 === 1) { this.segmentPosition[i] = width - (this.xPos + this.frameWidth) } } //Renders the image image(this.img, this.segmentPosition[i], offsets[0] + (this.pieceHeight * i), this.frameWidth, this.pieceHeight, 0, this.pieceHeight * i, this.frameWidth, this.pieceHeight) if (isImageLoaded === true) { //Draws a rectangle around the selected Image if (i === (this.selectedSegment + 1)) { stroke('hsla(160, 100%, 50%, 0.5)') strokeWeight(10) rect(this.segmentPosition[i], offsets[0] + (this.pieceHeight * i), this.frameWidth, this.pieceHeight) } } else {//Prints loading text textSize(20) fill('white') stroke(1) text(("Loading level please wait.. "), width * 0.5, height * 0.5) } } } /** * Updates the gameParameters * @param timeOut checks timer */ public updateParameters(timeOut: Boolean) { this.selectedSegment = -1 this.xPos = 0 if (timeOut === false) { isImageLoaded = false this.img = loadImage(this.getImgUrl(), this.imageLoaded) this.noOfSegments++ } } /** * Updates the segment * @param timeOut checks timer * @returns if level completed is true / false */ public updateSegment(): Boolean { let levelComplete = false this.selectedSegment++ if (this.selectedSegment + 1 >= this.noOfSegments) { levelComplete = true } return levelComplete } /**Resets the Parameters*/ public resetParameters() { this.pieceHeight = 0 this.xPos = 0 this.noOfSegments = 3 this.segmentPosition = [] this.selectedSegment = -1 } /**gets position of the selected segment*/ public getSelectedSegmentPosition() { return this.segmentPosition[this.selectedSegment + 1] } /**Draws the reference frame and the moving image*/ public draw() { let offsets = this.getOffset() this.referenceFrame() this.drawMovingImage(offsets) } }
Java
UTF-8
4,508
2.359375
2
[]
no_license
package com.example.sliderapp; import androidx.appcompat.app.AppCompatActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.SeekBar; import android.widget.Toast; import java.io.DataOutputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Set; public class MainActivity extends AppCompatActivity { private SeekBar simpleSeekBar; private BluetoothAdapter mBluetoothAdapter; private BluetoothDevice mDevice; private DataOutputStream os; private InputStream is; private BluetoothSocket socket; private String valString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); simpleSeekBar = (SeekBar) findViewById(R.id.seekBar); if (mBluetoothAdapter == null) { Toast.makeText(MainActivity.this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show(); } else if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); } if (mBluetoothAdapter.getBondedDevices() != null) { Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { mDevice = device; } } } else { Toast.makeText(MainActivity.this, "You must pair your device first", Toast.LENGTH_SHORT).show(); } simpleSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progressChangedValue = 0; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progressChangedValue = progress; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { Toast.makeText(MainActivity.this, "Seek bar progress is :" + progressChangedValue, Toast.LENGTH_SHORT).show(); valString = String.format("%d\n", progressChangedValue); // byte[] valBytes = val.getBytes(); } BroadcastReceiver discoveryResult = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME); BluetoothDevice remoteDevice; remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Toast.makeText(getApplicationContext(), "Discovered: " + remoteDeviceName + " address " + remoteDevice.getAddress(), Toast.LENGTH_SHORT).show(); try{ BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(remoteDevice.getAddress()); Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); BluetoothSocket clientSocket = (BluetoothSocket) m.invoke(device, 1); clientSocket.connect(); os = new DataOutputStream(clientSocket.getOutputStream()); new clientSock().start(); } catch (Exception e) { e.printStackTrace(); Log.e("BLUETOOTH", e.getMessage()); } } }; }); } public class clientSock extends Thread { public void run() { try { os.writeBytes(valString); // anything you want os.flush(); } catch (Exception e1) { e1.printStackTrace(); return; } } } }
Python
UTF-8
2,770
2.71875
3
[]
no_license
import tkinter from tkinter import * import os import re import glob from gui import window, bottom_frame from sixth import listofdirs, x global sevenbutton global sevenlabel global sevenlabel1 global sevenlabel2 global sevenlabel3 global sevenlabel5 global sevenlabel6 global file_src global secondtext global rat global sevenlabel4 global seventext global scrollbar def gotoeight(): rat = secondtext.get("0.0", END) sevenlabel.destroy() sevenlabel1.destroy() seventext.destroy() sevenlabel3.destroy() sevenlabel5.destroy() sevenlabel6.destroy() sevenbutton.destroy() secondtext.destroy() sevenlabel4.destroy() scrollbar.destroy() exec(open(r".\eight.py").read()) var = StringVar() var1 = StringVar() var2 = StringVar() var3 = StringVar() var4 = StringVar() var5 = StringVar() var6 = StringVar() sevenlabel = Label(window, textvariable=var, fg="red") var.set("The selected file is: ") sevenlabel.pack() # print x # print listofdirs[x] # print listoffiles[x] try: file = open(listofdirs[x], "r") except IOError: print("There was an error reading file") sys.exit() file_text = file.read() file.close() # print file_text sevenlabel1 = Label(window, textvariable=var1) file_src = file.name var1.set(file_src) sevenlabel1.pack() # sevenlabel2 = Label( window, textvariable=var2, wraplength=700) # var2.set(file_text) # sevenlabel2.pack() scrollbar = Scrollbar(window) scrollbar.pack(side="right", fill="y") seventext = Text(window, yscrollcommand=scrollbar.set) seventext.insert(INSERT, file_text) scrollbar.config(command=seventext.yview) seventext.pack(side="left", fill="both") charCount = 0 words = file_text.split() wordCount = len(words) sentences = re.split(r' *[.?!][\'")\]]* *', file_text) sentCount = len(sentences) for word in words: for char in word: charCount += 1 sevenlabel3 = Label(bottom_frame, textvariable=var3) var3.set("Number of words:" + str(wordCount)) sevenlabel3.pack(anchor=CENTER) sevenlabel5 = Label(bottom_frame, textvariable=var5) var5.set("Number of sentences:" + str(sentCount)) sevenlabel5.pack(anchor=CENTER) sevenlabel6 = Label(bottom_frame, textvariable=var6) var6.set("Number of characters:" + str(charCount)) sevenlabel6.pack(anchor=CENTER) sevenlabel4 = Label(bottom_frame, textvariable=var4, justify=LEFT) var4.set("RATIO:") sevenlabel4.pack(anchor=CENTER) secondtext = Text(bottom_frame, height=1, width=5) secondtext.pack(anchor=CENTER) # secondtext.insert(topframe,"per") # scrollbar.config( command = fourthtext.yview ) sevenbutton = tkinter.Button(bottom_frame, text="EXTRACTIVE SUMMARY", command=gotoeight) sevenbutton.pack()
Markdown
UTF-8
3,624
3.1875
3
[ "MIT" ]
permissive
# 03/08/2019 ## More MVC stuff - ways to get data from the controller to the view 1. strongly typed view the model - often will be a view model - view can only take one model, so if you need several, either that's a collection type of some kind or make a new view model that contains the several you need 2. ViewData - a key-value pair dictionary - this obj is reachable via a property on Controller - can assign values in controller and access in the view (during the same HTTP request! It's cleared between requests) - e.g. ViewData["numOfmovies"] = viewModels.Count; ViewData["currentTime"] = DateTime.Now; <h4>Num of movie: @ViewData["numOfMovies"]</h4> 3. ViewBag - a different way to access ViewData "dynamic" type - set properties instead of using indexing syntax w/string - e.g. ViewBag.numOfmovies = viewModels.Count; - allows you to add new properties after object is created - turns off compile-time type checking (does not check if it's access a valid property) 4. TempData - a key-value pair dictionary - the values inside it survive across requests "magically" (by default - stored using cookies sent to the client which are then sent back to the server on subsequent requests) - But we can configure other providers for TempData in StartUp - e.g. we can use this to incrementally build some model that needs many forms to be submitted, not just one - With regular ["key"] access, the value you access gets deleted after the current request. We can circumvent that with methods - .Peek("key") - accesses value with marking for deletion - .Keep("key") - unmarks a value for deletion - ex: <h5>Counter (with TempData:) @TempData["Counter"]</h5> ```cshtml @{ if (((int)TempData["Counter"]) <= 3>) { TempData.Keep("Counter"); } } if (TempData.ContainsKey("Counter")) { TempData["Counter"] = ((int)TempData["Counter"]) + 1; } else { TempData["Counter"] = 0; } ``` - The other way we can keep data around to incrementally build something like an Order is with hidden form fields (corresponding to view model properties) - attributes - [Route("ShowAllMovies")] - in contrast to global/convention based routing - e.g. [/{num:int?}] - this skips initial controller part with / - e.g. [Index/apples] - public ActionResult Index([FromQuery]) int num {} -pre method won't work, but if you include '?' query string for num, it will work ## Client Server MVC - [Client] -requests-> [Server(MVC)] - [Client] <-response- [Server(MVC)] - From Server - ASP.NET Core has a sequence of middleware plugged in in-order using .Use___ in Startup.Configure - From Client - Other middleware -> - e.g. exceptio-handling, static-file serving, etc. - Routing middleware -> - MVC - Then the response goes back the other way - From MVC - Filters are applied to controllers or actions using attributes or globally in startup - Controller/action selection -> - Authorization filter -> - Resource filters -> - Exception filters -> - Model binding -> - Action Filters - Action filters (before) - Action method execution - Action tilers (after)
Java
UTF-8
9,480
1.898438
2
[ "Apache-2.0" ]
permissive
package com.guosen.zebra; /** * @Title: ZebraRun.java * @Package com.guosen.zebra.core.boot.runner * @Description: TODO(用一句话描述该文件做什么) * @author 邓启翔 * @date 2017年11月13日 下午4:21:35 * @version V1.0 */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.guosen.zebra.core.common.ZebraConstants; import com.guosen.zebra.core.exception.RpcBizException; import com.guosen.zebra.core.exception.RpcErrorMsgConstant; import com.guosen.zebra.core.exception.RpcFrameworkException; import com.guosen.zebra.core.grpc.anotation.ZebraConf; import com.guosen.zebra.core.grpc.util.HttpUtils; import com.guosen.zebra.core.grpc.util.NetUtils; import com.guosen.zebra.core.grpc.util.PropertiesContent; import com.guosen.zebra.core.serializer.utils.JStringUtils; import okhttp3.OkHttpClient; import okhttp3.Request; /** * @ClassName: ZebraRun * @Description: TODO(这里用一句话描述这个类的作用) * @author 邓启翔 * @date 2017年11月13日 下午4:21:35 * */ public class ZebraRun { private static final Logger log = LogManager.getLogger(ZebraRun.class); public static String APP_NODE = StringUtils.EMPTY; public static String APP_IDC = StringUtils.EMPTY; public static String APP_SET = ZebraConstants.DEFAULT_SET; public static boolean APP_IS_WEB = false; public static String CONF_ADDR = ""; public static String CONF_NAME = ""; /** * @Title: run * @Description: 启动springboot * @param @param args main函数接收参数 主要传SET * @param @param clz 启动类 * @param @param isWebEnv 是否是web应用,如果是true会启动web端口 * @param @throws Exception 设定文件 * @return void 返回类型 * @throws */ public static void run(String args[], Class<?> clz,boolean isWebEnv) throws Exception { initInParams(args); if(isWebEnv) APP_IS_WEB = isWebEnv; SpringApplication app = new SpringApplication(clz); ZebraConf conf = clz.getAnnotation(ZebraConf.class); if(!StringUtils.isEmpty(CONF_ADDR)){ dynamicConfCenterAddr(conf); } if(conf!=null){ CONF_NAME = conf.confName(); Properties p = getProp(conf); if(p!=null){ app.setDefaultProperties(p); } } if(isWebEnv){ app.setWebApplicationType(WebApplicationType.SERVLET); }else{ app.setWebApplicationType(WebApplicationType.NONE); } try{ app.run(args); }catch(Exception e){ e.printStackTrace(); throw e; } } private static void initInParams(String args[]) throws UnsupportedEncodingException{ try{ if (args.length > 0) { String arg = args[0]; Map<String,String> map = JStringUtils.toMap(arg); log.info("app started,environment is {}",map); if(!StringUtils.isEmpty(map.get("set"))&&!"none".equals(map.get("set").toLowerCase())){ APP_SET = map.get("set"); } if(!StringUtils.isEmpty(map.get("idc"))&&!"none".equals(map.get("idc").toLowerCase())){ APP_IDC = map.get("idc"); } if(!StringUtils.isEmpty(map.get("node"))&&!"none".equals(map.get("node").toLowerCase())){ APP_NODE = map.get("node"); } if(!StringUtils.isEmpty(map.get("host"))&&!"none".equals(map.get("host").toLowerCase())){ NetUtils.localIp = map.get("host"); } if(!StringUtils.isEmpty(map.get("conf"))&&!"none".equals(map.get("conf").toLowerCase())){ CONF_ADDR = map.get("conf"); } if(map.get("web")!=null) APP_IS_WEB = true; } }catch(Exception e){ e.printStackTrace(); } } @SuppressWarnings("resource") private static Properties getProp(ZebraConf conf) throws Exception{ Properties p = new Properties(); try { List<Object> list = Lists.newArrayList(); // 资源类配置 JSONArray array =getServiceConfig(conf.confName(), "0", conf.confaddr()); list.addAll(array); // 应用类配置 array =getServiceConfig(conf.confName(), "1", conf.confaddr()); list.addAll(array); if(list.size() == 0){ throw new RpcBizException("从配置中心获取配置异常,跳转到本地配置"); } // 生成配置文件 for (Object item : list) { JSONObject obj = (JSONObject)item; if (ZebraConstants.ZEBRA_SCOPE_GLOBAL.equals(obj.get(ZebraConstants.ZEBRA_SCOPE)) || (ZebraConstants.ZEBRA_SCOPE_IDC.equals(obj.get(ZebraConstants.ZEBRA_SCOPE)) && obj.get(ZebraConstants.ZEBRA_SCOPE_NAME).equals(APP_IDC)) || (ZebraConstants.ZEBRA_SCOPE_SET.equals(obj.get(ZebraConstants.ZEBRA_SCOPE)) && obj.get(ZebraConstants.ZEBRA_SCOPE_NAME).equals(APP_SET)) || (ZebraConstants.ZEBRA_SCOPE_NODE.equals(obj.get(ZebraConstants.ZEBRA_SCOPE)) && obj.get(ZebraConstants.ZEBRA_SCOPE_NAME).equals(APP_NODE))) { String txt = (String) obj.get("text"); String args[] = txt.split("\n"); for (String str : args) { if(str.startsWith("#"))continue; if(str.trim().length() ==0) continue; if(str.split("=").length==1){ p.setProperty(str.split("=")[0], StringUtils.EMPTY); }else{ p.setProperty(str.split("=")[0], str.substring(str.indexOf("=")+1)); } } } } // 保存 FileOutputStream out = new FileOutputStream(ZebraConstants.ZEBRA_PROPERTIES_NAME); // 为properties添加注释 p.store(out, "zebra auto generate properties"); out.close(); } catch (Exception e) { log.warn("get conf from conf-center error {}" , e); try { System.err.println("**************************************"); System.err.println("*************** 加载本地配置 *************"); System.err.println("**************************************"); FileInputStream in = new FileInputStream(ZebraConstants.ZEBRA_PROPERTIES_NAME); long size = in.getChannel().size(); if(size==0){ in = new FileInputStream(getLocalPath()+"/"+ZebraConstants.ZEBRA_PROPERTIES_NAME); size = in.getChannel().size(); if(size==0){//去绝对路径取 log.error(getLocalPath()+"/"+ZebraConstants.ZEBRA_PROPERTIES_NAME+" not exist"); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Properties prop = new Properties(); Resource[] rs = resolver.getResources("classpath:*.properties"); if(rs.length ==0){ throw new RpcBizException(RpcErrorMsgConstant.PROPERTIES_NOT_EXISTS_EXCEPTION); }else{ for (int i = 0; i < rs.length; i++) { Resource r = rs[i]; prop.load(r.getInputStream()); } } } }else{ p.load(in); in.close(); } } catch (IOException e1) { e1.printStackTrace(); throw e1; } } PropertiesContent.p = p; return p; } /** * @Title: getLocalPath * @Description: 获取linux本地部署路径 * @param @return 设定文件 * @return String 返回类型 * @throws */ private static String getLocalPath() { String jarWholePath = ZebraRun.class.getProtectionDomain().getCodeSource().getLocation().getFile(); try { jarWholePath = java.net.URLDecoder.decode(jarWholePath, "UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println(e.toString()); } String jarPath = new File(jarWholePath).getParentFile().getAbsolutePath(); return jarPath.replaceAll("\\/lib", ""); } /** * @Title: dynamicConfCenterAddr * @Description: 通过动态配置设置配置中心地址 * @param @param at 设定文件 * @return void 返回类型 * @throws */ @SuppressWarnings("unchecked") public static void dynamicConfCenterAddr(Annotation at) { InvocationHandler handler = Proxy.getInvocationHandler(at); try { Field hField = handler.getClass().getDeclaredField("memberValues"); hField.setAccessible(true); // 获取 memberValues @SuppressWarnings("rawtypes") Map memberValues =(Map)hField.get(handler); memberValues.put("confaddr", CONF_ADDR); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException(e); } } private static JSONArray getServiceConfig(String server, String type, String addr) throws Exception { Map<String, String> map = Maps.newConcurrentMap(); map.put("server", server); map.put("type", type); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(HttpUtils.getUrl(addr + "/zebra-conf/getConfNew", map)).build(); String ret = client.newCall(request).execute().body().string(); JSONObject result = JSON.parseObject(ret); if (result.getIntValue(ZebraConstants.KEY_CODE) == ZebraConstants.FAIL) { throw new RpcFrameworkException("Request Config Center Error"); } JSONArray array = result.getJSONArray(ZebraConstants.KEY_DATA); return array; } }
C#
UTF-8
4,346
2.84375
3
[]
no_license
using System; using System.IO; using System.Threading; namespace SDK.Prospero.Hardware { public static class TouchSensor { private static int mY; private static int mX; private static bool mPress; private static readonly Thread ProcessingThread = new Thread(Processing); private static Stream mStream; private static bool mPressMessage; public static Action OnTouch; private static void Processing() { try { while (true) { var inputEvent = new LinuxEventParser.InputEvent(); // get new event while (inputEvent.type != LinuxEventParser.EventTypes.EV_SYN) { var data = new byte[16]; for (var i = 0; i < 16; i++) { var rv = mStream.ReadByte(); if (rv > 0) data[i] = (byte)rv; } inputEvent = LinuxEventParser.ParseEvent(data); if (inputEvent.type == LinuxEventParser.EventTypes.EV_ABS) { switch (inputEvent.code) { case LinuxEventParser.CodeTypes.ABS_X: { mY = inputEvent.value; Application.GetInstance().PostEvent(Application.EventType.MouseMove, AdcToAbsolute(mX, mY)); //Console.WriteLine("mY: {0},{1}", AdcToAbsolute(mX, mY).X, AdcToAbsolute(mX, mY).Y); } break; case LinuxEventParser.CodeTypes.ABS_Y: { mX = inputEvent.value; Application.GetInstance().PostEvent(Application.EventType.MouseMove, AdcToAbsolute(mX, mY)); //Console.WriteLine("mX: {0},{1}", AdcToAbsolute(mX, mY).X, AdcToAbsolute(mX, mY).Y); } break; case LinuxEventParser.CodeTypes.PRESSURE: { mPressMessage = true; mPress = inputEvent.value == 1; } break; } if (OnTouch != null) OnTouch(); } } // need send press message here if(mPressMessage) { Application.GetInstance().PostEvent( mPress ? Application.EventType.MouseDown : Application.EventType.MouseUp, AdcToAbsolute(mX, mY)); //Console.WriteLine("{2}: {0},{1}", AdcToAbsolute(mX, mY).X, AdcToAbsolute(mX, mY).Y, mPress ? "Down" : "Up"); mPressMessage = false; } } } catch (ThreadAbortException) { // correct shutdown } } public static void Init(Stream aStream) { mStream = aStream; ProcessingThread.Start(); } // TODO: calibration needed! private static MouseData AdcToAbsolute(int x, int y) { //Console.WriteLine("{0}:{1} - {2}:{3}", x, y, ((x - 280)/16), ((y - 220)/12)); //return new MouseData { X = ((x - 280) / 16), Y = 320 - ((y - 220) / 12) }; // MI0280 return new MouseData { X = (x - 120) / 8, Y = ((y - 250) / 13) }; // MI0430 } public static void Stop() { ProcessingThread.Abort(); } } }
C
UTF-8
248
3.234375
3
[]
no_license
#include <stdio.h> int RPM( int a, int b ) { int sum = 0; while( b ) { if( b & 1 ) sum += a; a <<= 1; b >>= 1; } return sum; } int main() { return printf( "%d\n", RPM( 86, 57 ) ); }
Ruby
UTF-8
822
2.796875
3
[]
no_license
require 'nokogiri' require_relative 'character' class CharacterUploader def self.create(character_sheet, user) begin new(character_sheet, user).message rescue "Please upload a valid .xml or .dnd4e file" end end attr_accessor :character, :user def initialize(character_sheet, user) @user = user doc = Nokogiri::XML(character_sheet) details = character_details doc.xpath("//CharacterSheet/Details").first create_character doc.to_s, details end def message "Successfully uploaded #{character.name}" end def character_details(xml) name = xml.xpath('//name').text.strip { name: name } end def create_character(xml, details) @character = Character.create( details.merge( user_id: user.id ) ) character.update_attribute(:xml, xml) end end
Java
UTF-8
1,540
2.28125
2
[]
no_license
package com.zl.test; import com.zl.entity.Employee; import com.zl.mapper.EmployeeMapper; import com.zl.util.RedisUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class employeeTest { @Autowired private EmployeeMapper employeeMapper; @Autowired private RedisTemplate redisTemplate; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisUtil redisUtil; private String str; @Test public void testKey(){ /* Employee employee = new Employee(); employee.setdId(1); employee.setEmail("w4r52342@qq.com"); redisUtil.set("kkkkk",employee);*/ Employee kkkkk = (Employee) redisUtil.get("kkkkk"); System.out.println(kkkkk); } @Test public void testResis() { //操作字符串 //stringRedisTemplate.opsForValue().append("redis", "zl"); Employee empById = employeeMapper.getEmpById(1); //默认保存对象,使用jdk序列化 redisTemplate.opsForValue().set("emp01", empById); //将数据以json保存 //redisTemplate 有默认序列化器 } @Test public void testGetEmp() { Employee empById = employeeMapper.getEmpById(1); System.out.println(empById); } }
PHP
UTF-8
222
2.640625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: cippo * Date: 2/16/2016 * Time: 12:17 AM */ $quote = "To be or not to be, that is the question."; $quote = strtoupper( $quote ); $quote = strtolower( $quote ); echo $quote;
Go
UTF-8
925
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package main import ( "bytes" "flag" "fmt" "io/ioutil" "os" "runtime/pprof" "github.com/wzshiming/gs/exec" ) var profile = flag.String("profile", "", "profile file path") var tree = flag.Bool("tree", false, "show ast tree") func init() { flag.Parse() } func main() { if *profile != "" { f, _ := os.Create(*profile) defer f.Close() pprof.StartCPUProfile(f) // start cpu profile,write to file defer pprof.StopCPUProfile() // stop profile } e := exec.NewExec() for _, filename := range flag.Args() { b, err := ioutil.ReadFile(filename) if err != nil { fmt.Println(err) return } if *tree { v, err := e.Parse(filename, bytes.Runes(b)) if err != nil { fmt.Println(err) return } for _, v := range v { fmt.Println(v) } } else { v, err := e.Cmd(filename, bytes.Runes(b)) if err != nil { fmt.Println(err) return } fmt.Println(v) } } }
Ruby
UTF-8
417
3.328125
3
[]
no_license
require_relative 'hand' class Member INITIAL_BANK = 100 attr_accessor :bank attr_reader :name, :hand, :color def initialize @bank = INITIAL_BANK @hand = Hand.new end def add_card(card) @hand.cards << card @hand.scoring(card) end def bet(value) @bank -= value end def reset @hand.cards = [] @hand.score = 0 end def bankrupt? true if @bank.zero? end end
C#
UTF-8
2,926
2.65625
3
[ "MIT" ]
permissive
using SourceCodeSerializer.Converters; using System; using System.Collections.Immutable; using Xunit; using Xunit.Abstractions; namespace SourceCodeSerializer { public class EnumTests { private readonly ITestOutputHelper _helper; public EnumTests(ITestOutputHelper helper) { _helper = helper; } [Theory] [InlineData(typeof(EnumTest1), true)] [InlineData(typeof(EnumTest2), true)] public void CanConvertTests(Type type, bool expected) { var converter = new EnumConverter(); Assert.Equal(expected, converter.CanConvert(type)); } [Theory] [InlineData(typeof(EnumTest1), EnumTest1.Item1, "SourceCodeSerializer.EnumTest1.Item1")] [InlineData(typeof(EnumTest2), EnumTest2.Item0, "SourceCodeSerializer.EnumTest2.Item0")] [InlineData(typeof(EnumTest2), EnumTest2.Item1, "SourceCodeSerializer.EnumTest2.Item1")] [InlineData(typeof(EnumTest2), EnumTest2.Item2, "SourceCodeSerializer.EnumTest2.Item2")] [InlineData(typeof(EnumTest2), EnumTest2.Item1 | EnumTest2.Item3, "SourceCodeSerializer.EnumTest2.Item1 | SourceCodeSerializer.EnumTest2.Item3")] public void BasicEnumTest(Type type, object value, string expected) { var serializer = new SourceCodeSerializer(); var converter = new EnumConverter(); var result = converter.ConvertToExpression(type, value, serializer); _helper.WriteLine($"Expected: {expected}"); _helper.WriteLine($"Result: {result}"); Assert.Equal(expected, result.ToString()); } [Theory] [InlineData(typeof(EnumTest1), EnumTest1.Item1, "EnumTest1.Item1")] [InlineData(typeof(EnumTest2), EnumTest2.Item0, "EnumTest2.Item0")] [InlineData(typeof(EnumTest2), EnumTest2.Item1, "EnumTest2.Item1")] [InlineData(typeof(EnumTest2), EnumTest2.Item2, "EnumTest2.Item2")] [InlineData(typeof(EnumTest2), EnumTest2.Item1 | EnumTest2.Item3, "EnumTest2.Item1 | EnumTest2.Item3")] public void BasicEnumTestWithUsing(Type type, object value, string expected) { var settings = new SerializerSettings { Usings = ImmutableArray.Create("SourceCodeSerializer") }; var serializer = new SourceCodeSerializer(settings); var converter = new EnumConverter(); var result = converter.ConvertToExpression(type, value, serializer); _helper.WriteLine($"Expected: {expected}"); _helper.WriteLine($"Result: {result}"); Assert.Equal(expected, result.ToString()); } } public enum EnumTest1 { Item1, Item2 }; [Flags] public enum EnumTest2 { Item0 = 0x0, Item1 = 0x1, Item2 = 0x2, Item3 = 0x4 } }
Python
UTF-8
6,586
2.75
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- # The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt # # This example shows how to use dlib's face recognition tool. This tool maps # an image of a human face to a 128 dimensional vector space where images of # the same person are near to each other and images from different people are # far apart. Therefore, you can perform face recognition by mapping faces to # the 128D space and then checking if their Euclidean distance is small # enough. # # When using a distance threshold of 0.6, the dlib model obtains an accuracy # of 99.38% on the standard LFW face recognition benchmark, which is # comparable to other state-of-the-art methods for face recognition as of # February 2017. This accuracy means that, when presented with a pair of face # images, the tool will correctly identify if the pair belongs to the same # person or is from different people 99.38% of the time. # # Finally, for an in-depth discussion of how dlib's tool works you should # refer to the C++ example program dnn_face_recognition_ex.cpp and the # attendant documentation referenced therein. # # # # # COMPILING/INSTALLING THE DLIB PYTHON INTERFACE # You can install dlib using the command: # pip install dlib # # Alternatively, if you want to compile dlib yourself then go into the dlib # root folder and run: # python setup.py install # or # python setup.py install --yes USE_AVX_INSTRUCTIONS # if you have a CPU that supports AVX instructions, since this makes some # things run faster. This code will also use CUDA if you have CUDA and cuDNN # installed. # # Compiling dlib should work on any operating system so long as you have # CMake and boost-python installed. On Ubuntu, this can be done easily by # running the command: # sudo apt-get install libboost-python-dev cmake # # Also note that this example requires scikit-image which can be installed # via the command: # pip install scikit-image # Or downloaded from http://scikit-image.org/download.html. import sys import datetime import os import dlib import glob from skimage import io import cv2 import numpy as np import pickle from time import sleep print dlib.__version__ print dlib.__file__ #print dlib.__path__ from distutils.sysconfig import get_python_lib print(get_python_lib()) win = dlib.image_window() class FaceRecognizer: def __init__(self, predictor_path="shape_predictor_68_face_landmarks.dat", face_rec_model_path="dlib_face_recognition_resnet_model_v1.dat", people_descriptor_file_name="people_descriptor.pk"): print "begin construtor" self.detector = dlib.get_frontal_face_detector() print "begin get_frontal_face_detector" self.sp = dlib.shape_predictor(predictor_path) print "begin face_recognition_model_v1" self.facerec = dlib.face_recognition_model_v1(face_rec_model_path) print "begin people_descriptor_file_name" self.people_descriptor=pickle.load(open(people_descriptor_file_name,"rb")) print "endconstrutor" self.verbose=False def recognizer(self,img): win.clear_overlay() win.set_image(img) # Ask the detector to find the bounding boxes of each face. The 1 in the # second argument indicates that we should upsample the image 1 time. This # will make everything bigger and allow us to detect more faces. dets = self.detector(img, 1) nFaces=len(dets) if self.verbose: print("Number of faces detected: {}".format(nFaces)) faces={} # Now process each face we found. for k, d in enumerate(dets): if self.verbose: print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format( k, d.left(), d.top(), d.right(), d.bottom())) # Get the landmarks/parts for the face in box d. shape = self.sp(img, d) # Draw the face landmarks on the screen so we can see what face is currently being processed. #win.clear_overlay() win.add_overlay(d); win.add_overlay(shape) # Compute the 128D vector that describes the face in img identified by # shape. In general, if two face descriptor vectors have a Euclidean # distance between them less than 0.6 then they are from the same # person, otherwise they are from different people. He we just print # the vector to the screen. face_descriptor = self.facerec.compute_face_descriptor(img, shape); minP=1.0 minK="" for k in self.people_descriptor: t=0 for d in self.people_descriptor[k]: dif=np.array(d)-np.array(face_descriptor) t+=np.linalg.norm(dif) p=t/len(self.people_descriptor[k]) if p<minP: minP=p minK=k faces[minK]=(minP,d,shape) return faces import thread captureProcessed=False def capture(): global captureProcessed,img,img0 while True: #print captureProcessed ret,img0=cap0.read() # if not ret: # print "Error al capturar imagen" # else: # if captureProcessed==True: # #print "Capturando" # img=cv2.cvtColor(img0,cv2.COLOR_BGR2RGB) # capturedImage=True # captureProcessed=False def nombreDia(): h=datetime.datetime.now().hour if h>14 and h<21: return "Buenas tardes" if h>=21 or h<6: return "Buenas noches" if h>=6 and h<=14: return "Buenos días" fr=FaceRecognizer() f="~/face_recognition/marisa_cea/face2.jpg" print("Processing file: {}".format(f)) #img = io.imread(f) #cap0 = cv2.VideoCapture("http://192.168.43.240:8080/video") cap0 = cv2.VideoCapture(0) ret,img0=cap0.read() if not ret: print "Error al capturar imagen" else: img=cv2.cvtColor(img0,cv2.COLOR_BGR2RGB) thread.start_new_thread(capture,()) while True: if not captureProcessed: #now img is global var img=cv2.cvtColor(img0,cv2.COLOR_BGR2RGB) faces=fr.recognizer(img) for name in faces: print name,faces[name] name=name.replace("_"," ") command='~/di.sh "Hola. %s."'%nombreDia() os.system(command) #captureProcessed=True
Swift
UTF-8
733
3
3
[]
no_license
// // Extensions.swift // TabBarDemo // // Created by Admin on 9/26/18. // Copyright © 2018 DemoApp. All rights reserved. // import Foundation import UIKit extension UIColor{ static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor{ return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1.0) } } extension String { func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font : font], context: nil) return ceil(boundingBox.height) } }
JavaScript
UTF-8
827
2.9375
3
[]
no_license
let bookmarks = document.getElementsByClassName('bookmark'); [...bookmarks].forEach(bookmark => { bookmark.style.cursor = 'pointer' bookmark.addEventListener('click', e => { let target = e.target.parentElement let header = new Headers() header.append('Accept', 'Application/JSON') let req = new Request(`/api/bookmark/${target.dataset.post}`,{method:'GET',header, mode:'cors'}) fetch(req).then(res => res.json) .then(date => { if (date.bookmark) { target.innerHTML = `<i class="fas fa-bookmark"></i>` } else { target.innerHTML =`<i class="far fa-bookmark"></i>` } }).catch(e => { console.log(e.response.date.error); alert(e.response.date.error) }) }) });
JavaScript
UTF-8
1,020
2.515625
3
[]
no_license
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import renderer from 'react-test-renderer'; import ShallowRenderer from 'react-test-renderer/shallow' it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<App />, div); ReactDOM.unmountComponentAtNode(div); }); it('should render shallow', () => { const renderer = new ShallowRenderer(); renderer.render(<App user={true}/>); const result = renderer.getRenderOutput(); expect(result).toMatchSnapshot() }); it('should fully render component', () => { const component = renderer.create( <App user={false}/> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }) it('should test nested object', () => { function getObject () { return { name: 'Jack', position: { title: 'D3', salary: '10 00000 $' }, years: '5' } } const actualResult = getObject(); expect(actualResult).toMatchSnapshot() })
Java
UTF-8
1,254
4.03125
4
[]
no_license
package org.launchcode.java.studios.countoccurrences; import java.util.HashMap; import java.util.Map; public class CountOccurrences { public static HashMap<String, Integer> countOccurrences(String[] array) { HashMap<String, Integer> characterCount = new HashMap<>(); for (String i : array) { Integer j = characterCount.get(i); characterCount.put(i, (j == null) ? 1 : (j+1)); } for (Map.Entry<String, Integer> character : characterCount.entrySet()) { System.out.println(character.getKey() + " : " + character.getValue()); } return characterCount; } public static void main (String[] args) { String sentence = "If the product of two terms is zero then common sense says at least one of the two terms has " + "to be zero to start with. So if you move all the terms over to one side, you can put the " + "quadratics into a form that can be factored allowing that side of the equation to equal zero. " + "Once you’ve done that, it’s pretty straightforward from there."; String[] sentenceArray = sentence.split(""); System.out.println(countOccurrences(sentenceArray)); } }
Java
UTF-8
3,105
2.828125
3
[ "Apache-2.0" ]
permissive
package dev.game.spacechaos.engine.hud; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import dev.game.spacechaos.engine.game.BaseGame; import dev.game.spacechaos.engine.time.GameTime; /** * Created by Justin on 08.02.2017. */ public class FilledBar extends BaseHUDWidget { protected String text = ""; protected Color backgroundColor = Color.GREEN; protected Color foregroundColor = Color.RED; protected Color textColor = Color.WHITE; protected float paddingLeft = 0; protected float paddingRight = 0; protected float paddingTop = 0; protected float paddingBottom = 0; protected BitmapFont font = null; protected float percent = 0; protected float value = 0; protected float maxValue = 100; protected float textPaddingBottom = 28; public FilledBar(BitmapFont font) { this.font = font; } public void update(BaseGame game, GameTime time) { // calculate percent this.percent = this.value / this.maxValue; } @Override public void drawLayer0(GameTime time, SpriteBatch batch) { } @Override public void drawLayer1(GameTime time, ShapeRenderer shapeRenderer) { // draw background shapeRenderer.setColor(this.backgroundColor); shapeRenderer.rect(getX(), getY(), getWidth(), getHeight()); float maxWidth = getWidth() - (paddingLeft + paddingRight); float maxHeight = getHeight() - (paddingTop + paddingBottom); float barWidth = maxWidth * percent; float barHeight = maxHeight; // draw foreground shapeRenderer.setColor(this.foregroundColor); shapeRenderer.rect(getX() + paddingBottom, getY() + paddingLeft, barWidth, barHeight); } @Override public void drawLayer2(GameTime time, SpriteBatch batch) { float startX = getX() + (getWidth() / 2) - (this.text.length() * this.font.getSpaceWidth()); float startY = getY() + (getHeight() / 2) - this.font.getLineHeight() + textPaddingBottom; // draw text this.font.setColor(this.textColor); this.font.draw(batch, this.text, startX, startY); } public void setFont(BitmapFont font) { this.font = font; } public String getText() { return this.text; } public void setText(String text) { this.text = text; } public float getValue() { return this.value; } public void setValue(float value) { this.value = value; } public float getMaxValue() { return this.maxValue; } public void setMaxValue(float maxValue) { this.maxValue = maxValue; } public float getPercent() { return this.percent * 100; } public void setBackgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; } public void setForegroundColor(Color foregroundColor) { this.foregroundColor = foregroundColor; } }
TypeScript
UTF-8
1,653
2.6875
3
[]
no_license
import { Component } from '@angular/core'; import { trigger, state, style, transition, animate, keyframes } from '@angular/animations'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], animations: [ trigger('flyInOut', [ state('in', style({transform: 'translateX(0)'})), transition('void => *', [ animate(300, keyframes([ style({opacity: 0, transform: 'translateX(-100%)', offset: 0}), style({opacity: 1, transform: 'translateX(15px)', offset: 0.3}), style({opacity: 1, transform: 'translateX(0)', offset: 1.0}) ])) ]), transition('* => void', [ animate(300, keyframes([ style({opacity: 1, transform: 'translateX(0)', offset: 0}), style({opacity: 1, transform: 'translateX(-15px)', offset: 0.7}), style({opacity: 0, transform: 'translateX(100%)', offset: 1.0}) ])) ]) ]) ] }) export class AppComponent { title = 'Angular Animation'; letters: any[] = ['A', 'B', 'C', 'D']; next: number = 0; staggeringLetters: any[] = []; constructor(){ this.add(); } add() { var addInterval = setInterval(()=> { if(this.next < this.letters.length) { this.staggeringLetters.push(this.letters[this.next++]); } if(this.letters.length == this.staggeringLetters.length) { this.remove(); clearTimeout(addInterval); } }, 1000) } remove() { setInterval(()=> { if(this.staggeringLetters.length > 0) { let i = this.staggeringLetters.length - 1; this.staggeringLetters.splice(i, 1); } }, 1000); } }
JavaScript
UTF-8
385
2.96875
3
[]
no_license
// Load parser using Remarkable library let md = new Remarkable(); // Function to call when saving an html file function saveHTML(htmlVal){ // Log the parsed MD and set it to a variable let $html = md.render(htmlVal); console.log($html); // Create HTML file let blob = new Blob([`${$html}`],{type:'text/html;charset=utf-8'}); // Save created file saveAs(blob,"Untitled.html"); }
Rust
UTF-8
3,778
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0", "BSD-3-Clause", "GPL-1.0-or-later", "LGPL-2.0-or-later" ]
permissive
use proc_macro2::{Ident, Span}; use std::cmp::Ordering; use std::fmt::{self, Display}; use std::hash::{Hash, Hasher}; #[cfg(feature = "parsing")] use crate::lookahead; /// A Rust lifetime: `'a`. /// /// Lifetime names must conform to the following rules: /// /// - Must start with an apostrophe. /// - Must not consist of just an apostrophe: `'`. /// - Character after the apostrophe must be `_` or a Unicode code point with /// the XID_Start property. /// - All following characters must be Unicode code points with the XID_Continue /// property. pub struct Lifetime { pub apostrophe: Span, pub ident: Ident, } impl Lifetime { /// # Panics /// /// Panics if the lifetime does not conform to the bulleted rules above. /// /// # Invocation /// /// ``` /// # use proc_macro2::Span; /// # use syn::Lifetime; /// # /// # fn f() -> Lifetime { /// Lifetime::new("'a", Span::call_site()) /// # } /// ``` pub fn new(symbol: &str, span: Span) -> Self { if !symbol.starts_with('\'') { panic!( "lifetime name must start with apostrophe as in \"'a\", got {:?}", symbol ); } if symbol == "'" { panic!("lifetime name must not be empty"); } if !crate::ident::xid_ok(&symbol[1..]) { panic!("{:?} is not a valid lifetime name", symbol); } Lifetime { apostrophe: span, ident: Ident::new(&symbol[1..], span), } } pub fn span(&self) -> Span { self.apostrophe .join(self.ident.span()) .unwrap_or(self.apostrophe) } pub fn set_span(&mut self, span: Span) { self.apostrophe = span; self.ident.set_span(span); } } impl Display for Lifetime { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { "'".fmt(formatter)?; self.ident.fmt(formatter) } } impl Clone for Lifetime { fn clone(&self) -> Self { Lifetime { apostrophe: self.apostrophe, ident: self.ident.clone(), } } } impl PartialEq for Lifetime { fn eq(&self, other: &Lifetime) -> bool { self.ident.eq(&other.ident) } } impl Eq for Lifetime {} impl PartialOrd for Lifetime { fn partial_cmp(&self, other: &Lifetime) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Lifetime { fn cmp(&self, other: &Lifetime) -> Ordering { self.ident.cmp(&other.ident) } } impl Hash for Lifetime { fn hash<H: Hasher>(&self, h: &mut H) { self.ident.hash(h); } } #[cfg(feature = "parsing")] #[doc(hidden)] #[allow(non_snake_case)] pub fn Lifetime(marker: lookahead::TokenMarker) -> Lifetime { match marker {} } #[cfg(feature = "parsing")] pub mod parsing { use super::*; use crate::parse::{Parse, ParseStream, Result}; #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for Lifetime { fn parse(input: ParseStream) -> Result<Self> { input.step(|cursor| { cursor .lifetime() .ok_or_else(|| cursor.error("expected lifetime")) }) } } } #[cfg(feature = "printing")] mod printing { use super::*; use proc_macro2::{Punct, Spacing, TokenStream}; use quote::{ToTokens, TokenStreamExt}; #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for Lifetime { fn to_tokens(&self, tokens: &mut TokenStream) { let mut apostrophe = Punct::new('\'', Spacing::Joint); apostrophe.set_span(self.apostrophe); tokens.append(apostrophe); self.ident.to_tokens(tokens); } } }
Ruby
UTF-8
795
2.71875
3
[ "MIT" ]
permissive
module Flows class Result # Error for unwrapping non-successful result object class UnwrapError < Flows::Error def initialize(status, data, meta) @status = status @data = data @meta = meta end def message "You're trying to unwrap non-successful result with status `#{@status.inspect}` and data `#{@data.inspect}`\n\ Result metadata: `#{@meta.inspect}`" end end # Error for dealing with failure result as success one class NoErrorError < Flows::Error def initialize(status, data) @status = status @data = data end def message "You're trying to get error data for successful result with status \ `#{@status.inspect}` and data `#{@data.inspect}`" end end end end
PHP
UTF-8
6,290
2.734375
3
[ "MIT" ]
permissive
<?php include 'config.php'?> <?php session_start(); if(isset($_POST["add_to_cart"])) { if(isset($_SESSION["shopping_cart"])) { $item_array_id = array_column($_SESSION["shopping_cart"], "item_sno"); if(!in_array($_GET["sno"], $item_array_id)) { $count = count($_SESSION["shopping_cart"]); $item_array = array( 'item_sno' => $_GET["sno"], 'item_name' => $_POST["hidden_name"], 'item_price' => $_POST["hidden_price"], 'item_quantity' => $_POST["quantity"] ); $_SESSION["shopping_cart"][$count] = $item_array; echo '<script>alert("Item Added to Cart")</script>'; echo '<script>window.location="product.php"</script>'; } else { echo '<script>alert("Item Already Added")</script>'; echo '<script>window.location="product.php"</script>'; } } else { $item_array = array( 'item_sno' => $_GET["sno"], 'item_name' => $_POST["hidden_name"], 'item_language' => $_POST["hidden_language"], 'item_number' => $_POST["hidden_number"], 'item_price' => $_POST["hidden_price"], 'item_quantity' => $_POST["quantity"] ); $_SESSION["shopping_cart"][0] = $item_array; echo '<script>alert("Item Added to Cart")</script>'; echo '<script>window.location="product.php"</script>'; } } // Code for Removing Item from Cart using SESSION Variable. if(isset($_GET["action"])) { if($_GET["action"] == "delete") { foreach($_SESSION["shopping_cart"] as $keys => $values) { if($values["item_sno"] == $_GET["sno"]) { unset($_SESSION["shopping_cart"][$keys]); echo '<script>alert("Item Removed")</script>'; echo '<script>window.location="cart.php"</script>'; } } } } ?> <!DOCTYPE html> <html> <head> <title>My Cart</title> <style type="text/css"> .footer{ margin-top: 320px; } .table{ font-weight: bold; font-size: larger; } .container{ font-weight: bold; font-style:initial; } </style> <?php include 'navbar.html'?> </head> <body class="container-fluid"></br> <h3 align="center">Order Details</h3></br> <div class="row"> <div class="table-responsive col-lg-8"> <table class="table table-bordered table-striped"> <tr class="text-center"> <th>Item Name</th> <th>Item Quantity</th> <th>Price</th> <th>Amount</th> <th>Remove Item</th> </tr> <?php if(!empty($_SESSION["shopping_cart"])) { $total = 0; foreach($_SESSION["shopping_cart"] as $keys => $values) { ?> <tr class="text-center"> <td><?php echo $values["item_name"]; ?></td> <td><?php echo $values["item_quantity"]; ?></td> <td><?php echo $values["item_price"]; ?></td> <td><?php echo number_format($values["item_quantity"] * $values["item_price"], 2); ?></td> <td><a href="cart.php?action=delete&sno=<?php echo $values["item_sno"]; ?>"><span class="text-danger">Remove</span></a></td> </tr> <?php $total = $total + ($values["item_quantity"] * $values["item_price"]); } ?> <tr> <td colspan="3" align="right">Total</td> <td align="right">$ <?php echo number_format($total, 2); ?></td> <td></td> </tr> <?php } ?> </table> </div> <!-- Start of Purchase --> <div class="col-lg-4"> <div class="border bg-light rounded p-4"> <h3 class="text-center">Total</h3> <h4 class="text-left">Grand Total :</h4> <h4 class="text-right">$ <?php echo number_format($total, 2); ?></h4> <?php if(isset($_SESSION['shopping_cart']) && count($_SESSION['shopping_cart'])>0) { ?> <form action="Purchase.php" method="POST"> <div class="form-group"> <label>Full Name</label> <input type="text" name="Full_Name" class="form-control" required> </div> <div class="form-group"> <label>Email Address</label> <input type="email" name="Email" class="form-control" required> </div> <div class="form-group"> <label>Phone Number</label> <input type="number" name="Phone_no" class="form-control" required> </div> <div class="form-group"> <label>Home Address</label> <input type="text" name="Address" class="form-control" required> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="Pay_Mode" value="COD" checked> <label class="form-check-label" for="coddefault"> <b>Cash On Delivery </b> </label> </div><br> <button class="btn btn-success btn-block" name="purchase">Proceed Now</button> </form> <?php } ?> </div> </div> <!-- End of Purchase --> </div> <footer> <?php include 'footer.php'?> </footer> </body> </html>
C
UTF-8
1,666
3.515625
4
[]
no_license
/* COMP3301 2011 - A0 Sample Solution * Sam Kingston, May 2011. */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* prototypes from other .c files */ void do_ls(char *arg); void do_lsr(char *arg); void do_cp(char *src, char *dest); void do_rm(char *arg); static void dispatch_command(char *str) { char *cmd = NULL, *arg1 = NULL, *arg2 = NULL; /* extract the arguments */ cmd = strsep(&str, " "); if (cmd == NULL) { return; } arg1 = strsep(&str, " "); /* used by (optionally) ls and rm */ arg2 = strsep(&str, " "); /* only used by cp */ /* dispatch the work to the helper functions - note they should check the * arguments themselves to be non-NULL */ if (strcmp(cmd, "ls") == 0) { do_ls(arg1); } else if (strcmp(cmd, "lsr") == 0) { do_lsr(arg1); } else if (strcmp(cmd, "cp") == 0) { do_cp(arg1, arg2); } else if (strcmp(cmd, "rm") == 0) { do_rm(arg1); } else { fprintf(stderr, "unrecognised command %s\n", cmd); } } int main(int argc, char **argv __attribute__((unused))) { if (argc != 1) { fprintf(stderr, "shell takes no arguments\n"); exit(1); } char buf[1024]; while (fgets(buf, sizeof(buf), stdin) != NULL) { /* ignore blank lines */ if (strlen(buf) <= 1 || buf[0] == ' ') { continue; } /* ignore too long lines */ if (buf[strlen(buf)-1] != '\n') { fprintf(stderr, "Ignoring line longer than 1024 characters\n"); continue; } buf[strlen(buf)-1] = '\0'; dispatch_command(buf); } return 0; }
Java
UTF-8
6,324
3
3
[]
no_license
package loyal.Battle.Actions; import java.util.ArrayList; import loyal.Battle.Characters.CharacterState.Stat; import loyal.Battle.Characters.CharacterType; import loyal.Battle.Characters.PlayingCharacter; import loyal.entities.CharacterStore; import loyal.entities.GeneratorOfParties; import loyal.entities.SimpleCharacterFactory; import loyal.entities.Warrior; import loyal.entities.Wizard; public class Tester { public static void main(String[] args) { SimpleCharacterFactory factory; CharacterStore store; factory = new SimpleCharacterFactory(); store = new CharacterStore(factory); PlayingCharacter testCharacter = store.orderCharacter("TestCharacterSorcer", CharacterType.WIZARD); PlayingCharacter targetCharacter = store.orderCharacter("TestCharacterWarrior", CharacterType.WARRIOR); WizzardAbilityFactory wizzardAbilityFactory = new WizzardAbilityFactory(); Ability darkOrb = wizzardAbilityFactory.createCharacterAction("dark orb", testCharacter); testCharacter.addAction(darkOrb); ArrayList<PlayingCharacter> arrayListOfTargets = new ArrayList<PlayingCharacter>(); arrayListOfTargets.add(targetCharacter); testCharacter.setTargets(arrayListOfTargets); System.out.println("the target Character Health before the attak is : " + testCharacter.getState().getStat(Stat.HEALTH)); darkOrb.applyAbility(arrayListOfTargets); System.out.println("the target Character Health after the attak is : " + targetCharacter.getState().getStat(Stat.HEALTH)); //printing the the abilities for the wizzard class String [] wizzardAbilities = wizzardAbilityFactory.displayAbilitiesBasedOnType(); PlayingCharacter hunterCharacter = store.orderCharacter("TestCharacterHunter", CharacterType.HUNTER); HunterAbilityFactory hunterAbilityFactory = new HunterAbilityFactory(); Ability sharpEye = hunterAbilityFactory.createCharacterAction("sharp eye", hunterCharacter); hunterCharacter.addAction(sharpEye); ArrayList<PlayingCharacter> arrayListOfTargets2 = new ArrayList<PlayingCharacter>(); arrayListOfTargets2.add(hunterCharacter); sharpEye.applyAbility(arrayListOfTargets2); PlayingCharacter WorrierCharacter = store.orderCharacter("Warrior", CharacterType.WARRIOR); WarriorAbilityFactory warriorFactory = new WarriorAbilityFactory(); PlayingCharacter clericCharacter = store.orderCharacter("cleric", CharacterType.CLERIC); ArrayList<PlayingCharacter> warriorTargets = new ArrayList<PlayingCharacter>(); warriorTargets.add(clericCharacter); warriorTargets.add(testCharacter); Ability desperateMove = warriorFactory.createCharacterAction("desperate move", WorrierCharacter); WorrierCharacter.addAction(desperateMove); System.out.println("the health of the cleric before attak is:" + clericCharacter.getState().getStat(Stat.HEALTH)); System.out.println("the health of the cleric before attak is:" + testCharacter.getState().getStat(Stat.HEALTH)); desperateMove.applyAbility(warriorTargets); System.out.println("the health of the cleric after attak is:" + clericCharacter.getState().getStat(Stat.HEALTH)); System.out.println("the health of the cleric after attak is:" + testCharacter.getState().getStat(Stat.HEALTH)); System.out.println("the health of the warrior after performing desperate move is: " + WorrierCharacter.getState().getStat(Stat.HEALTH)); PlayingCharacter ClericCharacter = store.orderCharacter("Warrior", CharacterType.CLERIC); ClericAbilityFactory clericAbilityFactory = new ClericAbilityFactory(); Ability lightningSpear = clericAbilityFactory.createCharacterAction("lightning spear", ClericCharacter); ClericCharacter.addAction(lightningSpear); ArrayList<PlayingCharacter> ClericTargets = new ArrayList<PlayingCharacter>(); ClericTargets.add(WorrierCharacter); System.out.println("Warrior health before lightning attack: " + WorrierCharacter.getState().getStat(Stat.HEALTH)); ClericCharacter.getActions().get(0).applyAbility(ClericTargets); System.out.println("Warrior health after lightning attack: " + WorrierCharacter.getState().getStat(Stat.HEALTH)); GeneratorOfParties partyGenerator = new GeneratorOfParties(); ArrayList<PlayingCharacter> party = partyGenerator.generateParty(); PlayingCharacter warriorCharacter = store.orderCharacter("TestCharacterWarrior", CharacterType.WARRIOR); System.out.println("before desperate move"); for(int i = 0; i < party.size(); i++) { System.out.println(party.get(i).getName() + " health is: "+ party.get(i).getState().getStat(Stat.HEALTH)); } desperateMove.applyAbility(party); System.out.println("after desperate move"); for(int i = 0; i < party.size(); i++) { System.out.println(party.get(i).getName() + " health is: "+ party.get(i).getState().getStat(Stat.HEALTH)); } System.out.println(); ArrayList<PlayingCharacter> partyThatHasAbilities = partyGenerator.generateParty(); ArrayList<PlayingCharacter> partyThatHasAbilitiesTarget = partyGenerator.generateParty(); for(int i = 0; i < partyThatHasAbilitiesTarget.size(); i++) { System.out.println(partyThatHasAbilities.get(i).getName() + " health is: "+ partyThatHasAbilitiesTarget.get(i).getState().getStat(Stat.HEALTH)); } CharacterAction ability = partyThatHasAbilities.get(0).getActions().get(3); ability.applyAbility(partyThatHasAbilitiesTarget); System.out.println(); for(int i = 0; i < partyThatHasAbilitiesTarget.size(); i++) { System.out.println(partyThatHasAbilitiesTarget.get(i).getName() + " health is: "+ partyThatHasAbilitiesTarget.get(i).getState().getStat(Stat.HEALTH)); } ArrayList<PlayingCharacter> enemyParty = partyGenerator.generateEnemyParty(); CharacterAction ability2 = partyThatHasAbilities.get(1).getActions().get(2); for(int i = 0; i < enemyParty.size(); i++) { System.out.println(enemyParty.get(i).getName() + " health is: "+ enemyParty.get(i).getState().getStat(Stat.HEALTH)); } ability2.applyAbility(enemyParty); for(int i = 0; i < enemyParty.size(); i++) { System.out.println(enemyParty.get(i).getName() + " health is: "+ enemyParty.get(i).getState().getStat(Stat.HEALTH)); } } }
Java
UTF-8
245
2.109375
2
[]
no_license
package practice.car.entity; public class Gasoline95 { public String getName() { return name; } public Integer getPrice() { return price; } private String name="95号汽油"; private Integer price=7; }
JavaScript
UTF-8
9,687
2.703125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
/** * Route Manager manages route create/edit operations * */ define(function (require) { "use strict"; var $ = require('jquery'); var L = require('leaflet'); var RouteManager = function (args) { this.initialize(args); }; RouteManager.prototype.initialize = function (args) {}; RouteManager.prototype.deleteMarker = function (args) { var lineIndex = args.lineIndex; var pointIndex = args.pointIndex; var geometry = args.geometry; var coordinates, lineStrings; if (geometry.get('type') === 'MultiLineString') { var type = 'MultiLineString'; lineStrings = geometry.get('coordinates'); // Array of line strings var newLineStrings = []; var nextLine, previousLine, lastPointInLine, firstPointInLine, onlyOneLineInRoute; $.each(lineStrings, function (i, lineString) { /* The points in the polyline change when Direction service is called. * Setting a large value then and adjusting it here solves that problem. */ if (pointIndex > lineString.length - 1) { pointIndex = lineString.length - 1; } firstPointInLine = pointIndex === 0; lastPointInLine = pointIndex === lineString.length - 1; onlyOneLineInRoute = lineStrings.length === 1; if (i == lineIndex) { if (onlyOneLineInRoute) { // Deleting the start or end of the only line in the route. type = 'Point'; newLineStrings = lineString[pointIndex]; } else if (i === 0) { /// Deleting start or end of first line in ourte if (lastPointInLine) { // combine the first line with the next line. nextLine = lineStrings[i + 1]; lineStrings[i + 1] = [lineString[0], nextLine[nextLine.length - 1]]; } // Nothing to do if firstPointInLine. This line will not get copied to new array. } else if (i === lineStrings.length - 1) { // Deleting start or end from the last line in the route if (firstPointInLine) { // combine the last line with the previous line. // Remove the previous line from newLineStrings. previousLine = newLineStrings.pop(); lineString = [previousLine[0], lineString[lineString.length - 1]]; newLineStrings.push(lineString) } // Nothing to do if lastPointInLine. This line will not get copied to new array. } else if (i > 0 && i < lineStrings.length - 1) { // combine the adjacent lines // Remove the previous line from newLineStrings. previousLine = newLineStrings.pop(); // Replace the points of the next line with starting point of the // previous line and the last point of the next line. This will // trigger directions to be called if snap-to-roads is enabled. nextLine = lineStrings[i + 1]; lineStrings[i + 1] = [previousLine[0], nextLine[nextLine.length - 1]]; } } else { newLineStrings.push(lineString) } }); geometry.set({'type': type, 'coordinates': newLineStrings}); } else { geometry.set({'type': '', 'coordinates': []}); } geometry.trigger('change:coordinates'); }; RouteManager.prototype.moveMarker = function (args) { var geometry = args.geometry; var point = args.point; var dragPosition = args.dragPosition; var lineIndex = args.lineIndex; var latLng = args.latLng; var lineString; if (geometry.get('type') === 'Point') { geometry.set('coordinates', point); } else if (geometry.get('type') === 'MultiLineString') { var lineStrings = geometry.get('coordinates'); if (lineStrings.length > 0) { lineString = lineStrings[lineIndex]; if (dragPosition === 'start') { lineString = [point, lineString[lineString.length - 1]]; lineStrings[lineIndex] = lineString; if (lineIndex > 0) { var previousLine = lineStrings[lineIndex - 1]; lineStrings[lineIndex - 1] = [previousLine[0], point]; } } else if (dragPosition === 'middle') { var newLineStrings = []; $.each(lineStrings, function(i, lineString){ if (i === lineIndex) { point = [latLng.lng, latLng.lat, 0, 0]; newLineStrings.push([lineString[0], point]); newLineStrings.push([point, lineString[lineString.length - 1]]); } else { newLineStrings[i] = lineString; } }); lineStrings = newLineStrings; } else if (dragPosition === 'end') { lineString = [lineString[0], point]; lineStrings[lineIndex] = lineString; if (lineIndex < lineStrings.length - 1) { var nextLine = lineStrings[lineIndex + 1]; lineStrings[lineIndex + 1] = [point, nextLine[nextLine.length - 1]] } } geometry.set('coordinates', lineStrings); geometry.trigger('change:coordinates'); } } }; RouteManager.prototype.addPoint = function (args) { var geometry = args.geometry; var newPoint = args.point; var newLineString, lineStrings; var coordinates = geometry.get('coordinates'); if (geometry.get('type') === 'MultiLineString') { // Array of linestrings // which are arrays of points // which are arrays of ordinates lineStrings = geometry.get('coordinates'); // Array of line strings // Get the last point of the last line. var lineString = lineStrings[lineStrings.length - 1]; // get last line of line strings var lastPoint = lineString[lineString.length - 1]; // last point of the last line newLineString = [lastPoint, newPoint]; // Previous point + new point lineStrings.push(newLineString); // Reset the coordinates to trigger coordinates change event. geometry.set({'coordinates': lineStrings}); geometry.trigger('change:coordinates'); } else { // Store the first click as a 'Point' if (coordinates.length == 0) { geometry.set({'type': 'Point', 'coordinates': newPoint}); } else { // Convert to 'MultiLineString' on second click. newLineString = [coordinates, newPoint]; // Array of points in a line string. geometry.set({'type': 'MultiLineString', 'coordinates': [newLineString]}); } } }; RouteManager.prototype.updateLine = function (args) { var geometry = args.geometry; var polyline = args.polyline; var lineIndex = args.lineIndex; var lineStrings = geometry.get('coordinates'); lineStrings[lineIndex] = polyline; var distanceMeters = 0; if (lineIndex > 0) { var previousLine = lineStrings[lineIndex - 1]; // set last point of previous line to first point of changed line and recommpute distance var secondToLastPoint = previousLine[previousLine.length - 2]; distanceMeters = secondToLastPoint[2]; var firstPoint = polyline[0]; distanceMeters += L.latLng(secondToLastPoint[1], secondToLastPoint[0]).distanceTo(L.latLng(firstPoint[1], firstPoint[0])); polyline[0][2] = distanceMeters; previousLine[previousLine.length - 1] = polyline[0]; } var prevPoint; if (lineIndex < lineStrings.length - 1) { var nextLine = lineStrings[lineIndex + 1]; // set first point of next line to last point of changed line nextLine[0] = polyline[polyline.length - 1]; for (var i = lineIndex; i < lineStrings.length; i++) { prevPoint = null; // Assign distances to points $.each(lineStrings[i], function (i, point) { var latLng = L.latLng(point[1], point[0]); if (prevPoint != null) { distanceMeters += latLng.distanceTo(prevPoint); point[2] = distanceMeters; } else { // zero or distanceMeters for last point in previous line point[2] = distanceMeters; } prevPoint = latLng; }); } } geometry.set({'coordinates': lineStrings}); geometry.trigger('change:coordinates'); }; return RouteManager; });
PHP
UTF-8
5,165
2.875
3
[]
no_license
<?php declare(strict_types=1); namespace Kev\TicTacToe\Module\Game\Domain; use Kev\TicTacToe\Module\Move\Domain\Move; use Kev\TicTacToe\Module\Move\Domain\Position; use Kev\Types\Aggregate\AggregateRoot; use function sprintf; final class Game extends AggregateRoot { const MAX_MOVES = 8; const POSSIBLE_COMBINATIONS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; private $id; private $xPlayerId; private $oPlayerId; private $moves; private $winner; private $isFinished; private function __construct(GameId $id, PlayerId $xPlayerId, PlayerId $oPlayerId) { $this->id = $id; $this->xPlayerId = $xPlayerId; $this->oPlayerId = $oPlayerId; $this->moves = []; $this->winner = null; $this->isFinished = false; } public static function start(GameId $id, PlayerId $xPlayerId, PlayerId $oPlayerId): Game { $game = new self($id, $xPlayerId, $oPlayerId); $game->record( new GameWasCreatedDomainEvent( $id->value(), [ 'xPlayerId' => $xPlayerId->value(), 'oPlayerId' => $oPlayerId->value(), ] ) ); return $game; } public function id(): GameId { return $this->id; } public function xPlayerId(): PlayerId { return $this->xPlayerId; } public function oPlayerId(): PlayerId { return $this->oPlayerId; } public function winner(): ?PlayerId { return $this->winner; } public function isFinished(): bool { return $this->isFinished; } public function addMove(Move $move): void { $this->checkMaxOfMovesAreNotExceeded(); $this->checkMoveWasMadeByOneOfThisPlayers($move->playerId()); $this->checkMoveGameIsSameAsThis($move->gameId()); $this->checkThatMovePositionIsNotAlreadyTaken($move->position()); $this->checkMovePlayerIsNotSameAsLastOne($move->playerId()); $this->moves[] = $move; $this->isFinished = count($this->moves) === self::MAX_MOVES; $this->ifThereIsAWinnerFinishTheGame(); } private function checkMaxOfMovesAreNotExceeded(): void { if (count($this->moves) >= self::MAX_MOVES) { throw new GameMovesExceededException('No more moves allowed'); } } private function checkMoveWasMadeByOneOfThisPlayers(PlayerId $playerId): void { if (!$playerId->equals($this->xPlayerId) && !$playerId->equals($this->oPlayerId)) { throw new PlayerWhoDidMoveIsNotAGamePlayerException( sprintf('Player <%s> is not a player of <%s> game', $playerId->value(), $this->id->value()) ); } } private function checkMoveGameIsSameAsThis(GameId $gameId): void { if (!$this->id->equals($gameId)) { throw new MoveDoNotBelongsToSpecifiedGameException( sprintf('Given move do not belong to game with <%s> id', $this->id->value()) ); } } private function checkThatMovePositionIsNotAlreadyTaken(Position $position): void { foreach ($this->moves as $move) { if ($move->position()->equalsTo($position)) { throw new PositionAlreadyTakenException(sprintf('Position <%u> already taken', $position->value())); } } } private function checkMovePlayerIsNotSameAsLastOne(PlayerId $playerId): void { if (empty($this->moves)) return; $lastMove = end($this->moves); if ($playerId->equals($lastMove->playerId())) { throw new PlayerCanNotMakeConsecutiveMovesException('Player can not make two consecutive moves'); } } private function ifThereIsAWinnerFinishTheGame(): void { if (empty($this->moves) || count($this->moves) < 5) return; if ($this->thereIsAWinner()) { $this->isFinished = true; $this->setLastPlayerAsAWinner(); } } private function thereIsAWinner(): bool { if ($this->isFinished) return !empty($this->winner); $lastPlayer = (end($this->moves))->playerId(); $playerMovePositions = $this->getMovePositionsByPlayer($lastPlayer); foreach (self::POSSIBLE_COMBINATIONS as $combination) { if (!array_diff($combination, $playerMovePositions)) { $this->winner = $lastPlayer; return true; } } return false; } private function getMovePositionsByPlayer(PlayerId $lastPlayer): array { $positions = []; foreach ($this->moves as $move) { if ($move->playerId()->equals($lastPlayer)) { $positions[] = $move->position()->value(); } } return $positions; } private function setLastPlayerAsAWinner(): void { $lastMove = end($this->moves); $this->winner = $lastMove->playerId(); } }
Java
UTF-8
3,971
4.125
4
[]
no_license
package com.implement.pepcoding.dp; public class PalindromicSubstring { /* * Time complexity : O(n^2). This gives us a runtime complexity of O(n^2). * Space complexity : O(n^2). It uses O(n^2) space to store the table. */ public static int countSubstringDP(String s) { int strLength = s.length(); if (strLength == 0) return 0; /* * palindrome[i][j] will be false if substring str[i..j] is not * palindrome Else table[i][j] will be true */ boolean palindrome[][] = new boolean[strLength][strLength]; int count = 0; // Trivial case: Single letter palindromes for (int i = 0; i < strLength; i++) { palindrome[i][i] = true; count++; } // Finding palindrome of 2 characters for (int i = 0; i < strLength - 1; i++) { if (s.charAt(i) == s.charAt(i + 1)) { palindrome[i][i + 1] = true; count++; } } // Finding palindromes of lengths greater than 2 for (int curr_len = 3; curr_len <= strLength; curr_len++) { // Fix the starting index for (int start = 0; start + curr_len <= strLength; start++) { // Get ending of substring from start and current length int end = start + curr_len - 1; if (s.charAt(start) == s.charAt(end) && // The first and last // characters should // match palindrome[start + 1][end - 1]) { // Rest of the // substring should // be a palindrome palindrome[start][end] = true; count++; } } } return count; } /* * Time complexity : O(n^2). This gives us a runtime complexity of O(n^2). * Space complexity : O(n^2). It uses O(n^2) space to store the table. */ public static int countSubstringDPII(String s) { int n = s.length(); if (n == 0) return 0; /* * palindrome[i][j] will be false if substring str[i..j] is not * palindrome Else table[i][j] will be true */ boolean dp[][] = new boolean[n][n]; int count = 0; // Gap = 0 to n - 1 OR length = 1 to n for (int g = 0; g < n; g++) { // Traverse diagonally with loop ending in last column for (int i = 0, j = g; j < dp[0].length; i++, j++) { // Trivial case: Single letter is always a palindrome if (g == 0) { dp[i][j] = true; } // Trivial case: String of 2 characters else if (g == 1) { dp[i][j] = s.charAt(i) == s.charAt(j); } else { if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1] == true) { dp[i][j] = true; } else { dp[i][j] = false; } } if (dp[i][j]) { count++; } } } return count; } /* * Time complexity : O(n^2). This gives us a runtime complexity of O(n^2). * Space complexity : O(1). It uses constant space. * * Using Center and Expand around it */ public static int countSubstringsExpandAoundCenter(String s) { if (s == null || s.length() < 1) return 0; int count = 0; for (int i = 0; i < s.length(); i++) { count = count + expandAroundCenter(s, i, i); count = count + expandAroundCenter(s, i, i + 1); } return count; } private static int expandAroundCenter(String s, int start, int end) { int count = 0; while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) { start--; end++; count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub String s; s = "forgeeksskeegfor"; System.out.println("DP1 : " + countSubstringDP(s) + ", " + "DP2 : " + countSubstringDPII(s) + ", " + "Expand Around Center : " + countSubstringsExpandAoundCenter(s)); s = "abc"; System.out.println("DP1 : " + countSubstringDP(s) + ", " + "DP2 : " + countSubstringDPII(s) + ", " + "Expand Around Center : " + countSubstringsExpandAoundCenter(s)); s = "aaa"; System.out.println("DP1 : " + countSubstringDP(s) + ", " + "DP2 : " + countSubstringDPII(s) + ", " + "Expand Around Center : " + countSubstringsExpandAoundCenter(s)); } }
Python
UTF-8
914
3.375
3
[]
no_license
# https://leetcode.com/problems/hamming-distance/?tab=Description def hammingDistance( x, y): """ :type x: int :type y: int :rtype: int """ x2=bin(x)[2:].zfill(32) y2=bin(y)[2:].zfill(32) hamming = 0 # print x2,y2 for i in range (32) : # print i if x2[i]!= y2[i] : hamming+=1 # print i print hamming hammingDistance(56,23) # class Solution(object): # def hammingDistance(self, x, y): # """ # :type x: int # :type y: int # :rtype: int # """ # x2=bin(x)[2:].zfill(32) # y2=bin(y)[2:].zfill(32) # hamming = 0 # # print x2,y2 # for i in range (32) : # # print i # if x2[i]!= y2[i] : # hamming+=1 # # print i # return hamming
Java
UTF-8
12,902
2.34375
2
[]
no_license
/* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenFlexo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.fge.graphics; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; import java.util.Observable; import java.util.logging.Logger; import javax.swing.ImageIcon; import org.openflexo.fge.FGEIconLibrary; import org.openflexo.fge.GraphicalRepresentation; import org.openflexo.fge.GraphicalRepresentation.GRParameter; import org.openflexo.fge.notifications.FGENotification; import org.openflexo.inspector.HasIcon; import org.openflexo.localization.FlexoLocalization; import org.openflexo.xmlcode.XMLSerializable; public class ForegroundStyle extends Observable implements XMLSerializable, Cloneable { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(ForegroundStyle.class.getPackage().getName()); public static enum Parameters implements GRParameter { color, lineWidth, capStyle, joinStyle, dashStyle, noStroke, useTransparency, transparencyLevel } private boolean noStroke = false; private Color color; private double lineWidth; private JoinStyle joinStyle; private CapStyle capStyle; private DashStyle dashStyle; private boolean useTransparency = false; private float transparencyLevel = 0.5f; // Between 0.0 and 1.0 private Stroke stroke; private double strokeScale; public static enum JoinStyle implements HasIcon { /** * Joins path segments by extending their outside edges until they meet. */ JOIN_MITER, /** * Joins path segments by rounding off the corner at a radius of half the line width. */ JOIN_ROUND, /** * Joins path segments by connecting the outer corners of their wide outlines with a straight segment. */ JOIN_BEVEL; @Override public ImageIcon getIcon() { if (this == JOIN_MITER) { return FGEIconLibrary.JOIN_MITER_ICON; } else if (this == JOIN_ROUND) { return FGEIconLibrary.JOIN_ROUND_ICON; } else if (this == JOIN_BEVEL) { return FGEIconLibrary.JOIN_BEVEL_ICON; } return null; } } public static enum CapStyle implements HasIcon { /** * Ends unclosed subpaths and dash segments with no added decoration. */ CAP_BUTT, /** * Ends unclosed subpaths and dash segments with a round decoration that has a radius equal to half of the width of the pen. */ CAP_ROUND, /** * Ends unclosed subpaths and dash segments with a square projection that extends beyond the end of the segment to a distance equal * to half of the line width. */ CAP_SQUARE; @Override public ImageIcon getIcon() { if (this == CAP_BUTT) { return FGEIconLibrary.CAP_BUTT_ICON; } else if (this == CAP_ROUND) { return FGEIconLibrary.CAP_ROUND_ICON; } else if (this == CAP_SQUARE) { return FGEIconLibrary.CAP_SQUARE_ICON; } return null; } } public static enum DashStyle implements HasIcon { PLAIN_STROKE, SMALL_DASHES, MEDIUM_DASHES, MEDIUM_SPACED_DASHES, BIG_DASHES, DOTS_DASHES, DOT_LINES_DASHES; @Override public ImageIcon getIcon() { if (this == PLAIN_STROKE) { return FGEIconLibrary.PLAIN_STROKE_ICON; } else if (this == SMALL_DASHES) { return FGEIconLibrary.SMALL_DASHES_ICON; } else if (this == MEDIUM_DASHES) { return FGEIconLibrary.MEDIUM_DASHES_ICON; } else if (this == MEDIUM_SPACED_DASHES) { return FGEIconLibrary.MEDIUM_SPACED_DASHES_ICON; } else if (this == BIG_DASHES) { return FGEIconLibrary.BIG_DASHES_ICON; } else if (this == DOTS_DASHES) { return FGEIconLibrary.DOTS_DASHES_ICON; } else if (this == DOT_LINES_DASHES) { return FGEIconLibrary.DOTS_LINES_DASHES_ICON; } return null; } /** * Returns the array representing the lengths of the dash segments. Alternate entries in the array represent the user space lengths * of the opaque and transparent segments of the dashes. As the pen moves along the outline of the <code>Shape</code> to be stroked, * the user space distance that the pen travels is accumulated. The distance value is used to index into the dash array. The pen is * opaque when its current cumulative distance maps to an even element of the dash array and transparent otherwise. * * @return the dash array. */ public float[] getDashArray() { if (this == PLAIN_STROKE) { return null; } else if (this == SMALL_DASHES) { float[] da = { 3, 2 }; return da; } else if (this == MEDIUM_DASHES) { float[] da = { 5, 3 }; return da; } else if (this == MEDIUM_SPACED_DASHES) { float[] da = { 5, 5 }; return da; } else if (this == BIG_DASHES) { float[] da = { 10, 5 }; return da; } else if (this == DOTS_DASHES) { float[] da = { 1, 4 }; return da; } else if (this == DOT_LINES_DASHES) { float[] da = { 15, 3, 3, 3 }; return da; } return null; } /** * Returns the current dash phase. The dash phase is a distance specified in user coordinates that represents an offset into the * dashing pattern. In other words, the dash phase defines the point in the dashing pattern that will correspond to the beginning of * the stroke. * * @return the dash phase as a <code>float</code> value. */ public float getDashPhase() { if (this == PLAIN_STROKE) { return 0; } else if (this == SMALL_DASHES) { return 0; } else if (this == MEDIUM_DASHES) { return 0; } else if (this == MEDIUM_SPACED_DASHES) { return 0; } else if (this == BIG_DASHES) { return 0; } else if (this == DOTS_DASHES) { return 0; } else if (this == DOT_LINES_DASHES) { return 0; } return 0; } } public ForegroundStyle() { super(); noStroke = false; color = Color.BLACK; lineWidth = 1.0; joinStyle = JoinStyle.JOIN_MITER; capStyle = CapStyle.CAP_SQUARE; dashStyle = DashStyle.PLAIN_STROKE; } public ForegroundStyle(Color aColor) { this(); color = aColor; } public static ForegroundStyle makeDefault() { return new ForegroundStyle(); } public static ForegroundStyle makeNone() { ForegroundStyle returned = new ForegroundStyle(); returned.setNoStroke(true); return returned; } public static ForegroundStyle makeStyle(Color aColor) { return new ForegroundStyle(aColor); } public static ForegroundStyle makeStyle(Color aColor, float aLineWidth) { ForegroundStyle returned = new ForegroundStyle(aColor); returned.setLineWidth(aLineWidth); return returned; } public static ForegroundStyle makeStyle(Color aColor, float aLineWidth, JoinStyle joinStyle, CapStyle capStyle, DashStyle dashStyle) { ForegroundStyle returned = new ForegroundStyle(aColor); returned.setLineWidth(aLineWidth); returned.setJoinStyle(joinStyle); returned.setCapStyle(capStyle); returned.setDashStyle(dashStyle); return returned; } public static ForegroundStyle makeStyle(Color aColor, float aLineWidth, DashStyle dashStyle) { ForegroundStyle returned = new ForegroundStyle(aColor); returned.setLineWidth(aLineWidth); returned.setDashStyle(dashStyle); return returned; } public CapStyle getCapStyle() { return capStyle; } public void setCapStyle(CapStyle aCapStyle) { if (requireChange(this.color, aCapStyle)) { CapStyle oldCapStyle = capStyle; this.capStyle = aCapStyle; stroke = null; setChanged(); notifyObservers(new FGENotification(Parameters.capStyle, oldCapStyle, aCapStyle)); } } public Color getColor() { return color; } public void setColor(Color aColor) { if (requireChange(this.color, aColor)) { java.awt.Color oldColor = color; this.color = aColor; setChanged(); notifyObservers(new FGENotification(Parameters.color, oldColor, aColor)); } } public void setColorNoNotification(Color aColor) { this.color = aColor; } public DashStyle getDashStyle() { return dashStyle; } public void setDashStyle(DashStyle aDashStyle) { if (requireChange(this.color, aDashStyle)) { DashStyle oldDashStyle = dashStyle; this.dashStyle = aDashStyle; stroke = null; setChanged(); notifyObservers(new FGENotification(Parameters.dashStyle, oldDashStyle, dashStyle)); } } public JoinStyle getJoinStyle() { return joinStyle; } public void setJoinStyle(JoinStyle aJoinStyle) { if (requireChange(this.joinStyle, aJoinStyle)) { JoinStyle oldJoinStyle = joinStyle; this.joinStyle = aJoinStyle; stroke = null; setChanged(); notifyObservers(new FGENotification(Parameters.joinStyle, oldJoinStyle, aJoinStyle)); } } public double getLineWidth() { return lineWidth; } public void setLineWidth(double aLineWidth) { if (requireChange(this.lineWidth, aLineWidth)) { double oldLineWidth = lineWidth; lineWidth = aLineWidth; stroke = null; setChanged(); notifyObservers(new FGENotification(Parameters.lineWidth, oldLineWidth, aLineWidth)); } } public boolean getNoStroke() { return noStroke; } public void setNoStroke(boolean aFlag) { if (requireChange(this.noStroke, aFlag)) { boolean oldValue = noStroke; this.noStroke = aFlag; setChanged(); notifyObservers(new FGENotification(Parameters.noStroke, oldValue, aFlag)); } } public Stroke getStroke(double scale) { if (stroke == null || scale != strokeScale) { if (dashStyle == DashStyle.PLAIN_STROKE) { stroke = new BasicStroke((float) (lineWidth * scale), capStyle.ordinal(), joinStyle.ordinal()); } else { float[] scaledDashArray = new float[dashStyle.getDashArray().length]; for (int i = 0; i < dashStyle.getDashArray().length; i++) { scaledDashArray[i] = (float) (dashStyle.getDashArray()[i] * scale * lineWidth); } float scaledDashedPhase = (float) (dashStyle.getDashPhase() * scale * lineWidth); stroke = new BasicStroke((float) (lineWidth * scale), capStyle.ordinal(), joinStyle.ordinal(), 10, scaledDashArray, scaledDashedPhase); } strokeScale = scale; } return stroke; } public float getTransparencyLevel() { return transparencyLevel; } public void setTransparencyLevel(float aLevel) { if (requireChange(this.transparencyLevel, aLevel)) { float oldValue = transparencyLevel; this.transparencyLevel = aLevel; setChanged(); notifyObservers(new FGENotification(Parameters.transparencyLevel, oldValue, aLevel)); } } public boolean getUseTransparency() { return useTransparency; } public void setUseTransparency(boolean aFlag) { if (requireChange(this.useTransparency, aFlag)) { boolean oldValue = useTransparency; this.useTransparency = aFlag; setChanged(); notifyObservers(new FGENotification(Parameters.useTransparency, oldValue, aFlag)); } } @Override public ForegroundStyle clone() { try { ForegroundStyle returned = (ForegroundStyle) super.clone(); return returned; } catch (CloneNotSupportedException e) { // cannot happen since we are clonable e.printStackTrace(); return null; } } @Override public String toString() { return "ForegroundStyle " + Integer.toHexString(hashCode()) + " [noStroke=" + noStroke + ",lineWidth=" + lineWidth + ",color=" + color + ",joinStyle=" + joinStyle + ",capStyle=" + capStyle + ",dashStyle=" + dashStyle + ",useTransparency=" + useTransparency + ",transparencyLevel=" + transparencyLevel + "]"; } public String toNiceString() { if (getNoStroke()) { return FlexoLocalization.localizedForKey(GraphicalRepresentation.LOCALIZATION, "no_stroke"); } else { return lineWidth + "pt, " + color; } } @Override public boolean equals(Object obj) { if (obj instanceof ForegroundStyle) { // logger.info("Equals called for ForegroundStyle !!!!!!!!!"); ForegroundStyle fs = (ForegroundStyle) obj; return getNoStroke() == fs.getNoStroke() && getLineWidth() == fs.getLineWidth() && getColor() == fs.getColor() && getJoinStyle() == fs.getJoinStyle() && getCapStyle() == fs.getCapStyle() && getDashStyle() == fs.getDashStyle() && getUseTransparency() == fs.getUseTransparency() && getTransparencyLevel() == fs.getTransparencyLevel(); } return super.equals(obj); } private boolean requireChange(Object oldObject, Object newObject) { if (oldObject == null) { if (newObject == null) { return false; } else { return true; } } return !oldObject.equals(newObject); } }
Python
UTF-8
577
3.859375
4
[]
no_license
destructor: =========== Inverse of constructor. automatically destroy the object. in python we have automatic carbage collection mechanism. so we dont need to write code neccessary. but if you think write it is posiible. __del__() call destructor: del obj_name """ class Human: def __init__(self): self.name="Livewire" def showDetails(self): print("name : ",self.name) def __del__(self):#destructor self.name="no name" print("name : ",self.name) h=Human() h.showDetails() del h#call Destructor
C
UTF-8
1,388
2.8125
3
[ "MIT" ]
permissive
/* * cli.h * * Created on: Mar 13, 2018 * Author: nickyang */ #ifndef CLI_H_ #define CLI_H_ #define CLI_ARG_COUNT_MAX 16 //Number of Args supported. #define CLI_ARGS_SIZE_MAX 16 //Maximum Length of a single args typedef enum CLI_RET { CLI_SUCCESS = 0, CLI_FAILURE = -1, } CLI_RET; typedef enum OPT_TYPE { OPT_END = 0x00, //End of options OPT_HELP = 0x01, //Show help text of all options. OPT_COMMENT = 0x02, //Option value is comments, will print help string only. OPT_INT = 0x10, //Option value is integer OPT_STRING = 0x11, //Option value is string OPT_BOOL = 0x12, //Option value is boolean } OPT_TYPE; typedef int CliCallBack(int argc, char **args); typedef struct stCliOption { OPT_TYPE OptType; //Option type const char ShortName; //Option short name, e.g. 't' const char *LongName; //Option long name, e.g. "test" const char *HelpText; //Option help text, e.g. "Run the test" void *PtrValue; //Pointer to store option value CliCallBack *CallBack; //Function call back } stCliOption; CLI_RET Cli_getString(char *string); CLI_RET Cli_getArgsFromString(char *string, int *argc, char *args[]); int Cli_parseArgs(int argc, char *args[], stCliOption options[]); #endif /* CLI_H_ */
Java
UTF-8
5,296
2.296875
2
[]
no_license
package operations; import java.sql.*; import java.util.ArrayList; import model.Transaction; import javax.swing.JOptionPane; //import com.sun.org.apache.bcel.internal.classfile.PMGClass; import oracle.jdbc.pool.OracleDataSource; public class POSOperations { private Statement stmt; private ResultSet rset; private Connection conn; private PreparedStatement pstmt; public POSOperations(Connection c) { conn = c; } public ResultSet queryProduct(String prodInput) throws SQLException { String sql = "SELECT p.prod_id,d.dvd_name,d.dvd_sale_price FROM product p, DIGITAL_PRODUCT dp, dvd d where p.PROD_ID = dp.PROD_ID AND dp.DIG_ID = d.DIG_ID AND p.prod_id = '" + prodInput + "'" + "union SELECT p.prod_id,c.album_name,c.cd_sale_price FROM product p, DIGITAL_PRODUCT dp, cd c where p.PROD_ID = dp.PROD_ID AND dp.DIG_ID = c.DIG_ID AND p.prod_id = '" + prodInput + "'" + "union SELECT p.prod_id,g.game_name,g.game_sale_price FROM product p, DIGITAL_PRODUCT dp, game g where p.PROD_ID = dp.PROD_ID AND dp.DIG_ID = g.DIG_ID AND p.prod_id = '" + prodInput + "'" + "union SELECT p.prod_id,e.manufacturer||' - '||e.model,c.CONSOLE_SALE_PRICE FROM product p, electronic e, console c where p.PROD_ID = e.PROD_ID AND e.elec_id = c.elec_ID AND p.prod_id = '" + prodInput + "'" + "union SELECT p.prod_id,e.manufacturer||' - '||e.model,sd.sd_SALE_PRICE FROM product p, electronic e, sound_dock sd where p.PROD_ID = e.PROD_ID AND e.elec_id = sd.elec_ID AND p.prod_id = '" + prodInput + "'" + "union SELECT p.prod_id,e.manufacturer||' - '||e.model,hp.HEADPHONE_SALE_PRICE FROM product p, electronic e, headphones hp where p.PROD_ID = e.PROD_ID AND e.elec_id = hp.elec_ID AND p.prod_id = '" + prodInput + "'"; try { stmt = conn.createStatement(); rset = stmt.executeQuery(sql); } catch(SQLException e) { System.out.println("Couldn't find product"); } return rset; } public String queryTransid() { int trans_id = 0; try { String queryTransid = "SELECT trans_id FROM TRANSACTION GROUP BY trans_id"; stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); rset = stmt.executeQuery(queryTransid); rset.afterLast(); if (rset.previous()) { trans_id = Integer.parseInt(rset.getString(1)) + 1; } } catch(SQLException e) { System.out.println(e); } return Integer.toString(trans_id); } public ResultSet displayProduct(String prodInput)throws SQLException { queryProduct(prodInput); return rset; } public void voidProduct(String prodInput, ArrayList<Transaction> t)throws SQLException { for (int i = 0;i < t.size(); i++) { if(prodInput == t.get(i).getTransID()) { t.remove(i); System.out.println(t.get(i).getTransID()); } } } public void insertTran(ArrayList<Transaction> t) { //trans_id NUMBER NOT NULL, trans_date DATE, trans_type VARCHAR2(1) CHECK(trans_type IN('S','R')), total_cost NUMBER(30,2))" String insert = "INSERT INTO transaction(trans_id, trans_date, trans_type, total_cost, quantity, emp_id, prod_id) VALUES(?,?,?,?,?,?,?)"; try { pstmt = conn.prepareStatement(insert); for(int i = 0; i< t.size();i++) { pstmt.setString(1, t.get(i).getTransID()); pstmt.setString(2, t.get(i).getDate()); pstmt.setString(3, t.get(i).getTransType()); pstmt.setDouble(4, t.get(i).getTotalCost()); pstmt.setInt(5, t.get(i).getQuantity()); pstmt.setString(6,t.get(i).getEmpID()); pstmt.setString(7,t.get(i).getProdID()); pstmt.execute(); } } catch(SQLException e) { e.printStackTrace(); } } public void updateCurrentStock(ArrayList<Transaction> t) { for(int i = 0; i < t.size(); i++) { String s = "SELECT prod_id, current_stock FROM product WHERE prod_id = '" + t.get(i).getProdID() + "'"; try { pstmt = conn.prepareStatement(s,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); rset = pstmt.executeQuery(); rset.next(); int stock = rset.getInt(2); //if return +1 , if sale -1 if(t.get(i).getTransType().equals("R")) { stock += t.get(i).getQuantity(); } else { stock -= t.get(i).getQuantity(); } rset.updateInt(2,stock); rset.updateRow(); } catch(SQLException e) { System.out.println(e.getMessage()); } } } public String getEmployeeID(String pin) { String id = ""; try { stmt = conn.createStatement(); String sqlStatement = "SELECT emp_id FROM EMPLOYEE WHERE pin_num = '" +pin+"'" ; rset = stmt.executeQuery(sqlStatement); rset.next(); id = rset.getString(1); } catch (Exception ex) { System.out.println("ERROR: " + ex.getMessage()); } return id; } public String getUserName(String empID) { String name= ""; try { stmt = conn.createStatement(); String sqlStatement = "SELECT f_name FROM EMPLOYEE WHERE emp_id = '" +empID+"'" ; rset = stmt.executeQuery(sqlStatement); rset.next(); name = rset.getString(1); } catch (Exception ex) { System.out.println("ERROR: " + ex.getMessage()); } return name; } }
Markdown
UTF-8
4,618
2.609375
3
[ "CC-BY-NC-ND-4.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
# SS14 | 从年轻到懂事的文科生 - 这是一个 90 后上山吃苦的故事. - 说的是, 三步并作一步的年轻人, 在成熟担当的大师兄帮助下, 搞定日期转换的故事... ### 0. 见色起意 - 开源潮流下, 年轻人也被洗脑, 以为程序改变世界. - 以为参加蟒营, 1 个半月即可习得'穿山遁甲'之技. - 于是乎, 伪装需要 gitlab api 的陪伴, 无理要求查看自己个儿操弄 issue 的个数. - 满嘴谎话得宣称, 按自然周查看个人 gitlab 发布 issue 个数,即可获得自我学习行为的理性评价. - 当然, 这是扯淡... 好在蟒营开放的氛围, 一向崇尚'犯错是最好的学习路径',给了年轻人检验自己荒唐想法的机会. ![3py-bear-need](http://ydlj.zoomquiet.top/ipic/2019-11-24-101camp3py-bear-need.png?imageView2/2/w/420) ### 1. 鲁莽惹事 - 项目套路不外乎输入/处理/输出. - 和天下大部分没有耐性的年轻人一样, 三步作一步是她的首要策略. - 能不能用一行/一段代码, 一次性完成项目需求? - 令人惊讶的是,其实是可以的... - 比如,目前的需求是,获得按自然周排列的 api 数据. - gitlab 提供使用 url 获取目标时间段的 api. - 问题是, url 需要的是用字符串输入的时间段. - 年轻人展现了她惊人的沙雕才华,手动搬砖输入大批字符串, 以下为目标时间段. ``` # 通过收入输入目标时间段字符串,获得按自然周排列的 api wks=[ 'after=2019-09-01&before=2019-09-21', 'after=2019-09-22&before=2019-09-29', 'after=2019-09-30&before=2019-10-06', 'after=2019-10-07&before=2019-10-13', 'after=2019-10-14&before=2019-10-20', 'after=2019-10-21&before=2019-10-27', 'after=2019-10-28&before=2019-11-03'] for s in wks: res = requests.get('https://gitlab.com/api/v4/users/4552272/events?target_type=issue&action=created&%s' % s,headers={'Private-Token': password}) _json = res.json() ``` - 此招搬砖后, 年轻人得到了颇为穷酸的输出,7 周内她自己创建 issue 的个数. - 可是问题是, 一旦需要得到新自然周数据,全部的 url 又要全部手动输入一轮, 非长久之计... ![issues_in6weeks](https://user-images.githubusercontent.com/19412465/68080585-bbde2680-fe39-11e9-9b07-61cab1d76cc5.png) ### 2. 半路获救 - 和大多数俗套故事一样, 总有基础扎实经验丰富的大师兄,把这群成事不足的沙雕后生们打捞上岸. - 大师兄说, 转换日期这事儿不用自己扛, 师傅早有工具. - 更关键的是, 三步并作一步, 这心态不好, 山中砍柴是门手艺, 急不来... - 大师兄的策略是, 先拿回所有 api, 统计的时候再按自然周进行统计. - 而目标时间段的字符串, 可以用函数直接转换为以自然周为标记的字符串. - 这两个字符串之间的桥梁可以是 tuple. - 大师兄代码如下. ``` # 通过 tuple 将原本难以肉眼识别的时间段转为易为识别的自然周 # 输入 >>>from datetime import datetime >>>date = '2019-10-23' # <class 'str'> # 处理 >>>date_tuple = datetime.strptime(date,"%Y-%m-%d").isocalendar() >>>print(date_tuple) # 输出 (2019, 45, 2) # <class 'tuple'> # 输入 >>>date_tuple = (2019, 45, 2) # 处理 >>>year_week_day = "%d年第%d周第%d日" % (date_tuple[0],date_tuple[1],date_tuple[2]) >>>print(year_week_day) # 输出 2019年第45周第2日 #<class 'str'> ``` - 大师兄出手后,小团队迎来了丰收的喜悦. ![polbar](https://user-images.githubusercontent.com/19412465/68080564-5c801680-fe39-11e9-8160-129ad2c44185.PNG) ### 3. 蟒营感悟 - 想必大家也已料到, 俺即为这个年轻人,是个在参加蟒营前,从未接触过代码实战的文科生.'真小白'一枚. - 皓首穷经二十载, 蟒营带给俺无法磨灭的'苦痛'印象(当然,这是黄连苦口利于心的好事). - '苦痛'大约可以总结为如下三点. - 破纸上谈兵 + 蟒营完全实战.用自己个儿直觉的作法,完成真实需求. + 深刻体会到,自己的代码虽然能成事, 但经常后患无穷... - 破闭门造车 + 苦熬功能做不出的时候, 真需要大师兄的救场指路. + 和写书不一样, 团队才是工程质量的保证. - 破羞于言表 + 大部分问题,无论多幼稚,只要能表述清楚,就是个好问题. + 自己有啥想不明白的, 立刻吼出来.大师兄只有空救助那些叫声大的鸭子. - 为何参加蟒营,而不是填鸭式教学班? - 因为这里,才有真正的项目,和靠谱的大师兄. ### Changelog - 1hr 熊本 细节 - .5hr 熊本 框架
C
UTF-8
255
2.859375
3
[]
no_license
#include<stdio.h> //authors : Arsal fadilah V.01 int main(){ int angka; //input scanf("%d", &angka); //proses dan ouput if(angka%2!=0){ printf("ganjil\n"); } else{ printf("genap\n"); } return 0; }
Java
UTF-8
1,872
2.796875
3
[]
no_license
import java.awt.event.*; import javax.swing.*; import javax.swing.filechooser.*; /** controleur du sous menu d'édition de niveaux (getion des interaction avec l'interface). */ public class ControleSubBuildMenu1 implements ActionListener{ private Fenetre mainFenetre = null; private Fenetre fenetre = null; ControleSubBuildMenu1(Fenetre main, Fenetre menu){ super(); mainFenetre = main; fenetre = menu; } /** Gestion de evenement de l'interface.*/ @Override public void actionPerformed(ActionEvent e){ String name = ((JButton)e.getSource()).getText(); if(name.equals("retour")){ this.mainFenetre.setVisible(true); this.mainFenetre.setLocation(this.fenetre.getLocationOnScreen()); this.fenetre.dispose(); }else if(name.equals("charger")){ JFileChooser chooser = new JFileChooser("./MAP/"); FileNameExtensionFilter filter = new FileNameExtensionFilter("Labyrinthe file (.lab)", "lab"); chooser.setFileFilter(filter); Fenetre tmp = new Fenetre("Choisir fichier"); tmp.setLocation(this.fenetre.getLocationOnScreen()); int returnVal = chooser.showOpenDialog(tmp); this.fenetre.dispose(); if(returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); MapLoader data = new MapLoader(chooser.getSelectedFile()); Grille map = new Grille(data.getSize(), data.getMap(), this.mainFenetre); //Outils tool = new Outils(map); }else{ System.out.println("loding file failed!"); this.fenetre.setVisible(true); } }else if(name.equals("nouveau")){ this.fenetre.setVisible(false); String dial = JOptionPane.showInputDialog(null, "Choisissez la taille ..."); try{ Grille map = new Grille(Integer.parseInt(dial), this.fenetre); }catch(NumberFormatException t){ this.fenetre.setVisible(true); } } } }
Python
UTF-8
1,047
3.59375
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Apr 01 15:47:41 2017 @author: Elani """ #118. Pascal's Triangle class Solution(object): def generate(self, numRows): #:type numRows: int #:rtype: List[List[int]] if numRows == 0: return [] elif numRows == 1: return [[1]] else: res=[[1]] for i in xrange(1,numRows): if i == 1: row_i = [1,1] else: row_i =[1] for j in xrange(1,len(res[i-1])): row_i.append(res[i-1][j]+res[i-1][j-1]) row_i.append(1) res.append(row_i) return res """ Another solution: resultset = [[1]* (i+1) for i in range(numRows)] for i in range(numRows): for j in range(1, i): resultset[i][j] = resultset[i-1][j-1] + resultset[i-1][j] return resultset """ s = Solution() print 'hh' print s.generate(5)