language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
2,645
2.6875
3
[ "MIT" ]
permissive
/** * @file http.js * @brief The http module of the HTTP subsystem. * @author Yiwei Chiao (ywchiao@gmail.com) * @date 07/18/2017 created. * @date 06/04/2018 last modified. * @version 0.1.0 * @since 0.1.0 * @copyright MIT, © 2017-2018 Yiwei Chiao * @details * * The http module of the HTTP subsystem. */ 'use strict'; const get_headers = (token) => { const headers = new Headers({ Accept: 'application/json', 'Content-Type': 'application/json; charset=UTF-8' }); if (token.hasOwnProperty('auth')) { headers.append('Authorization', token.auth); } // fi if (token.hasOwnProperty('account')) { headers.append('Account-ID', token.account); } // fi return headers; }; // get_headers() const get_url = (url, args={}) => { const query = []; for (const key in args) { if (args.hasOwnProperty(key)) { const k = encodeURIComponent(key); const v = encodeURIComponent(args[key]); query.push(`${k}=${v}`); } // fi } // od url += (query.length) ? `?${ query.join('&')}` : ''; return url; }; // get_url() const HTTP = Object.create({ token: {}, HTTP_OK: 200, HTTP_203: 203, HTTP_204: 204, }); HTTP.seal = function (token, auth, account) { token.auth = auth; token.account = account; }; HTTP.get = function (url, args={}, token={}) { return fetch( get_url(url, args), { method: 'GET', headers: get_headers(token), } ); }; HTTP.head = function (url, token={}) { return fetch( url, { method: 'HEAD', headers: get_headers(token), } ); }; HTTP.patch = function (url, data={}, token={}) { return fetch( url, { method: 'PATCH', headers: get_headers(token), body: JSON.stringify(data) } ); }; HTTP.post = function (url, dat={}, token={}) { console.log(`token: ${ token.auth}`); return fetch( url, { method: 'POST', headers: get_headers(token), body: JSON.stringify(data) } ); }; HTTP.put = function (url, data={}, token={}) { return fetch( url, { method: 'PUT', headers: get_headers(token), body: JSON.stringify(data) } ); }; HTTP.query = function (url, data={}, token={}) { console.log(`query => token: ${ token.auth}`); return fetch( url, { method: 'POST', headers: get_headers(token), body: JSON.stringify(data) } ) .then(response => { let json = {}; if (response.status === 200) { json = response.json(); } return json; }) }; export default (() => { return Object.create(HTTP); })(); // http.js
Markdown
UTF-8
1,252
3.203125
3
[]
no_license
# Rocket maze This is my first Samsung Watch (Tizen) app. It's a game inspired by an old game called [Crazy Gravity](https://classicreload.com/win9x-crazy-gravity.html). Basically the goal is to fly your rocketship from the starting position to the ending position without crashing into a wall. Crashing into a wall results in a spectacular explosion :) ![image](https://user-images.githubusercontent.com/36840705/110826338-425c1100-8295-11eb-972c-d51fd8416be3.png) ![image](https://user-images.githubusercontent.com/36840705/110826363-48ea8880-8295-11eb-908c-d1be58c4e449.png) The control inputs are as follows: - Rotate bezel: Rotates the rocket - Tap screen: Fire engine - Back button: Respawns the rocket after you crash The game currently has 3 levels, but is still very much a work in progress. ## Try it in a browser Since this is a completely normal HTML+JS+CSS app, it's also playable in the browser, although the experience is not as good, especially regarding the speed at which you can rotate the ship. The game is available [here](https://jgosar.github.io/rocket-maze/index.html). Key mappings for testing the game on the PC are as follows: - Bezel rotate left => A - Bezel rotate right => D - Tap screen => W - Back button => Esc
Markdown
UTF-8
4,694
2.765625
3
[]
no_license
# Sobre dudas y creencias - Francis responde - 238 >Estimado Francis, soy consciente de que esta pregunta sigue muy de cerca a la última que hice. Debo hacer una breve introducción. Es sobre la duda, específicamente sobre la duda después de haber visto la Verdad con toda claridad. Tras muchas experiencias menores, la Verdad se reveló como mi verdadera identidad más allá de toda duda y permaneció ahí sin esfuerzo, cercana y real. Este estado inquebrantable persistió durante seis días, hasta que me puse físicamente muy enfermo. Entonces cedió y desapareció. Me he recuperado totalmente, pero la solidez que yo pensaba era definitiva ha desaparecido. La sensación de algo final, de seguridad, desapareció. Las dudas sobre mi papel como hacedor y decisor han retornado. Pienso en las dudas de Jesús al final del evangelios en relación a si el hecho de que tuviera que morir era la voluntad del Ser, del Padre. De acuerdo con la narración, después de orar, él parece aceptar su destino. Lo que me toca es que Jesús parece muy humano, con dudas, aunque claramente capaz de resolverlas. También he leído que muchos maestros Zen dicen que la verdadera dificultad consiste en mantener nuestra práctica de forma duradera, tanto pre como post-iluminación. Que exista un estado duradero final de realización del Ser libre de dudas parece no tener nada que ver. Se que enseñas que la iluminación conduce eventualmente a la estabilización en la realización del ser, que asumo es inquebrantable. Mi pregunta es: ¿conlleva este estado alguna práctica para ser mantenido, o para volver a el si es aparentemente perdido, y es mediante esa práctica que los sabios permanecen libres de duda? (se que nunca puede ser verdaderamente perdido dado que es la verdad de lo que somos.) Siento que mientras exista un cuerpo humano, inevitablemente ciertos samskaras saldrán a la superficie, quizás más frecuentemente dudas. De hecho, encuentro que todavía tengo algunos hábitos mentales recurrentes que provienen de la ignorancia, aunque he visto que son, en última instancia, falsos. Estos hábitos incluyen dudas sobre mi verdadera identidad. Por supuesto, unas veces parecen más convincentes que otras. ¿Es el estado final un camino sin fin o un sentido de Verdad perfectamente sólido, o ambos simultáneamente? Y ¿está libre de dudas? Gracias por tus palabras de sabiduría y Verdad. Bendiciones, Jay Estimado Jay, Una duda existe solo en referencia a una creencia, duda y creencia son como las dos caras de una misma moneda. ¿Para que sirve una creencia? ¿Podemos vivir sin creencias? Si vivimos nuestra vida desde la creencia de ser una consciencia separada y limitada experimentamos sufrimiento. Si la vivimos desde la creencia de que somos la conciencia universal, todavía experimentaremos duda, que es también una forma de sufrimiento, dado que la posibilidad de ser separado no ha sido eliminada. Tenemos que ver claramente que la mente por si misma no tiene acceso a la Verdad, y por esa razón, no puede alcanzar la certeza. La certeza no puede existir como un concepto, solamente como una experiencia de la Verdad que reside más allá de la mente. Pensamos: "Si al menos pudiera tener certeza, entonces eso sería el fin de mi sufrimiento"; buscas la Verdad en el ámbito de los conceptos y acabas apegado a una creencia que no produce la felicidad que buscamos. Una mente feliz no es una mente con creencias y dudas, sino una mente silenciosa y libre. Volvamos a la pregunta que nos hicimos antes: ¿Podemos vivir sin creencias? Vivir sin creencias no significa vivir sin pensamientos ni conceptos. Significa simplemente no estar apegado a ellos. Más concretamente y en relación a la principal duda filosófica a la que aludiste en tu pregunta: ¿Podemos vivir sin tapar con una respuesta ya preparada "si" o "no" la pregunta: "¿es nuestra consciencia, eso que está percibiendo estas palabras justo ahora, limitada, condicionada, separada?"? ¿Podemos vivir sin saber? La revelación de la verdad requiere la humildad de no saber. Esto es cierto en la Ciencia, y también en la Sabiduría, que es la ciencia de la felicidad. Cuando realmente no conocemos la respuesta, estamos abiertos a todas las posibilidades, y en esta humildad y honestidad, la verdad del momento, que es todo lo que la limitada mente humana necesita y puede recibir se ofrecerá a si misma, como una intuición mental o como un acontecimiento aparentemente fortuito en el mundo. La compresión inundará la mente de claridad y silencio, y el corazón de alegría y paz. En el desconocer las cosas, está el conocer a Dios. Con afecto, Francis _Traducido por Pedro Brañas_
Java
UTF-8
549
2.453125
2
[ "MIT" ]
permissive
package edu.gatech.hypower; import java.io.IOException; import java.io.OutputStream; import javax.swing.JTextArea; public class PhysicloudConsoleStream extends OutputStream { private JTextArea PhysicloudConsole; public PhysicloudConsoleStream(JTextArea TextAreaFromClojure) { this.PhysicloudConsole = TextAreaFromClojure; } @Override public void write(int b) throws IOException { PhysicloudConsole.append(String.valueOf((char)b)); PhysicloudConsole.setCaretPosition(PhysicloudConsole.getDocument().getLength()); } }
C++
UTF-8
458
2.75
3
[]
no_license
/* * @Author: your name * @Date: 2021-05-03 16:52:24 * @LastEditTime: 2021-05-03 17:21:28 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \Programs\Hello World\myFirstApp.cpp */ #include <iostream> using namespace std; int main() { cout << (int)'a' << endl; cout << int('a') << endl; cout << int('A') << endl; cout << char(65) << endl; cout << "enter 5 letters: "; cout << 'a' << endl; }
JavaScript
UTF-8
1,821
3.53125
4
[]
no_license
var name = "Nguyen Van Vuong"; document.writeln("Learning about toUpperCase: "+name.toUpperCase()+"<br>"); var name2 = "Đại Học Bách Khoa Đà Nẵng"; document.writeln("Learning about slice: "+name.slice(3,12)+"<br>"); var name3 = "Trường Đại Học Bách Khoa Đà Nẵng - Khoa Công Nghệ Thông Tin"; document.writeln("Learning about substr: " + name.substr(4,10)); var name4 = "Nguyễn Văn Vương Lớp 12T2 Đại Học Bách Khoa Đà Nẵng"; document.writeln("<br>Learning about substring: " + name4.substring(3, 33)); var txt = "Hello World"; document.writeln("<p>Learning about atribute Big: " + txt.big() + "</p>"); document.writeln("<p>Learning about atribute Small: " + txt.small() + "</p>"); document.writeln("<p>Learning about atribute Bold: " + txt.bold() + "</p>"); document.writeln("<p>Learning about atribute Italic: " + txt.italics() + "</p>"); document.writeln("<p>Learning about atribute Blink: " + txt.blink() + "</p>"); document.writeln("<p>Learning about atribute fixed: " + txt.fixed() + "</p>"); document.writeln("<p>Learning about atribute Strike: " + txt.strike() + "</p>"); document.writeln("<p>Learning about atribute Font Color: " + txt.fontcolor("red") + "</p>"); document.writeln("<p>Learning about atribute Font Size: " + txt.fontsize(14) + "</p>"); document.writeln("<p>Link:" + txt.link("https://www.google.com.vn/") + "</p>"); document.writeln("<h1>Learning about String Object</h1>"); var number = "One;Two;Three;Four;Five;Six;Seven;Eight;Nine;Ten"; var numberx = number.split(";"); for(i=0;i<numberx.length;i++){ document.write(numberx[i].toString()); document.write("<br>"); } document.write("Tìm kiếm một chuỗi con bên trong chuỗi: "); var str = "Hello World"; document.write("Learning about indexOf: "+str.indexOf("Hello") + "<br>"); document.write("Learning about indexOf: "+str.indexOf("hello") + "<br>"); document.write("Learning about indexOf: "+str.indexOf("World") + "<br>");
C
UTF-8
288
3.328125
3
[]
no_license
#include <stdio.h> int main(void) { int wiek; float majatek; char zwierzatko[40]; printf("Podaj swoj wiek, majatek i ulubione zwierzatko.\n"); scanf_s("%d %f", &wiek, &majatek); scanf_s("%s", zwierzatko, 40); printf("%d, %.0f zl, %s\n.", wiek, majatek, zwierzatko); return 0; }
Java
UTF-8
1,151
2.515625
3
[]
no_license
package confdb.data; /** * EDAliasReference * --------------- * @author Bogdan Sataric * * CMSSW framework EDAlias reference. */ public class EDAliasReference extends Reference { // // construction // /** standard constructor */ public EDAliasReference(ReferenceContainer container, EDAliasInstance edalias) { super(container, edalias); } // // member functions // /** Object: toString() */ public String toString() { return parent().toString(); } /** number of parameters */ public int parameterCount() { EDAliasInstance edalias = (EDAliasInstance) parent(); return edalias.parameterCount(); } /** get i-th parameter */ public Parameter parameter(int i) { EDAliasInstance edalias = (EDAliasInstance) parent(); return edalias.parameter(i); } /** index of a certain parameter */ public int indexOfParameter(Parameter p) { EDAliasInstance edalias = (EDAliasInstance) parent(); return edalias.indexOfParameter(p); } /** number of unset tracked parameters */ public int unsetTrackedParameterCount() { EDAliasInstance edalias = (EDAliasInstance) parent(); return edalias.unsetTrackedParameterCount(); } }
Python
UTF-8
494
3.21875
3
[]
no_license
class Solution: def findTheDifference(self, s: str, t: str) -> str: d = {} for i in range(len(s)): if s[i] not in d: d[s[i]] = 0 d[s[i]] -= 1 for i in range(len(t)): if t[i] in d: d[t[i]] += 1 if d[t[i]] > 0: return t[i] else: return t[i] return ''
C#
UTF-8
5,273
2.8125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using NetTopologySuite.Geometries; using NetTopologySuite.IO.VectorTiles.Tiles; using NetTopologySuite.Operation.Overlay; [assembly: InternalsVisibleTo("NetTopologySuite.IO.VectorTiles.Tests")] namespace NetTopologySuite.IO.VectorTiles.Tilers { internal static class LineStringTiler { /// <summary> /// Returns all the tiles this linestring is part of. /// </summary> /// <param name="lineString">The linestring.</param> /// <param name="zoom">The zoom.</param> /// <returns>An enumerable of all tiles.</returns> /// <remarks>It's possible this returns too many tiles, it's up to the 'Cut' method to exactly decide what tiles a linestring belongs in.</remarks> public static IEnumerable<ulong> Tiles(this LineString lineString, int zoom) { // always return the tile of the first coordinate. var previousTileId = Tile.CreateAroundLocationId(lineString.Coordinates[0].Y, lineString.Coordinates[0].X, zoom); yield return previousTileId; // return all the next tiles. HashSet<ulong> tiles = null; for (var c = 1; c < lineString.Coordinates.Length; c++) { var coordinate = lineString.Coordinates[c]; var tileId = Tile.CreateAroundLocationId(coordinate.Y, coordinate.X, zoom); // only return changed ids. if (tileId == previousTileId) continue; // always two tiles or more, create hashset. // make sure to return only unique tiles. if (tiles == null) tiles = new HashSet<ulong> {previousTileId}; // if the tiles are not neighbours then also return everything in between. if (!Tile.IsDirectNeighbour(tileId, previousTileId)) { // determine all tiles between the two. var previousCoordinate = lineString.Coordinates[c - 1]; var previousTile = new Tile(previousTileId); var previousTileCoordinates = previousTile.SubCoordinates(previousCoordinate.Y, previousCoordinate.X); var nextTile = new Tile(tileId); var nextTileCoordinates = nextTile.SubCoordinates(coordinate.Y, coordinate.X); foreach (var (x, y) in Shared.LineBetween(previousTileCoordinates.x, previousTileCoordinates.y, nextTileCoordinates.x, nextTileCoordinates.y)) { var betweenTileId = Tile.CalculateTileId(zoom, x, y); if (tiles.Contains(betweenTileId)) continue; tiles.Add(betweenTileId); yield return betweenTileId; } } else { if (tiles.Contains(tileId)) continue; tiles.Add(tileId); yield return tileId; } previousTileId = tileId; } } /// <summary> /// Cuts the given linestring in one of more segments. /// </summary> /// <param name="tilePolygon">The tile polygon.</param> /// <param name="lineString">The linestring.</param> /// <returns>One or more segments.</returns> public static IEnumerable<LineString> Cut(this Polygon tilePolygon, LineString lineString) { var op = new OverlayOp(lineString, tilePolygon); var intersection = op.GetResultGeometry(SpatialFunction.Intersection); if (intersection.IsEmpty) { yield break; } switch (intersection) { case LineString ls: // intersection is a linestring. yield return ls; yield break; case GeometryCollection gc: { foreach (var geometry in gc.Geometries) { switch (geometry) { case LineString ls0: yield return ls0; break; case Point _: // The linestring only has a single point in this tile // We skip it // TODO check if this is correct continue; default: throw new Exception( $"{nameof(LineStringTiler)}.{nameof(Cut)} failed: A geometry was found in the intersection that wasn't a {nameof(LineString)}."); } } yield break; } default: throw new Exception($"{nameof(LineStringTiler)}.{nameof(Cut)} failed: Unknown result."); } } } }
Java
UTF-8
5,111
2.109375
2
[]
no_license
package com.rds.upc.web.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import lombok.Setter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.rds.upc.model.RdsUpcPermitNodeModel; import com.rds.upc.model.RdsUpcUserModel; import com.rds.upc.service.RdsUpcPermitService; import com.rds.upc.web.common.RdsUpcConstantUtil; import com.rds.upc.web.common.RdsUpcUUIDUtil; /** * * @ClassName: RdsUpcPermitController * @Description: 菜单管理Controller * @author yxb * @date 2015年4月27日 * */ @Controller @RequestMapping("upc/permit") public class RdsUpcPermitController extends RdsUpcAbstractController{ @Setter @Autowired private RdsUpcPermitService rdsUpcPermitService; /** * 根据用户的角色信息赋予用户相应权限 * @param params * @param request * @return */ @RequestMapping("queryUserPermitModel") @ResponseBody public Object queryPermitModelByParentCode(@RequestBody Map<String, Object> params,HttpServletRequest request){ RdsUpcUserModel user = (RdsUpcUserModel)request.getSession().getAttribute("user"); Object node = params.get("node")==null?"":params.get("node").toString(); Object parentscode = params.get("parentcode"); String roleType = user.getRoletype(); Map<String,Object> map = new HashMap<String, Object>(); map.put("permittype", roleType); if(node != "" && !node.equals("root")) { map.put("parentcode", node); }else { map.put("parentcode", parentscode); } List<Object> lists = rdsUpcPermitService.queryModule(map); List<Object> result = new ArrayList<Object>(); RdsUpcPermitNodeModel model = new RdsUpcPermitNodeModel(); if(parentscode.toString().equals("")){ model.setId("0"); model.setText("业务功能"); model.setLeaf(false); result.add(model); }else{ model = new RdsUpcPermitNodeModel(); for(int i = 0 ; i <lists.size() ; i ++) { model = (RdsUpcPermitNodeModel)lists.get(i); result.add(model); } } return result; } /** * 根据父类代码查询所有的子菜单 * @param params * @return */ @RequestMapping("queryPermitModelByParentCode1") @ResponseBody public Object queryPermitModelByParentCode1(@RequestBody Map<String, Object> params){ Object result = rdsUpcPermitService.queryPermitModelByParentCode(params); return result; } /** * 查询所有菜单信息 * @param params * @return * @throws Exception */ @RequestMapping("queryall") @ResponseBody public Object queryAll(@RequestBody Map<String, Object> params) throws Exception{ Object result = rdsUpcPermitService.queryAll(params); return result; } /** * 保存菜单信息 * @param params * @return */ @RequestMapping("savepermitmodule") @ResponseBody public Object savePermitModule(@RequestBody Map<String, Object> params){ try { boolean result = rdsUpcPermitService.savePermitModule(params); return this.setModel(result, result?RdsUpcConstantUtil.SAVE_SUCCESS:RdsUpcConstantUtil.SAVE_FAILED); } catch (Exception e) { e.printStackTrace(); return this.setModel(true, false, RdsUpcConstantUtil.EXCEPTION + "\n" + e.getMessage()); } } /** * 删除菜单 * @param params * @return */ @RequestMapping("delete") @ResponseBody public Object delete(@RequestBody Map<String, Object> params){ try { rdsUpcPermitService.delete(params); return this.setModel(true, RdsUpcConstantUtil.DELETE_SUCCESS); } catch (Exception e) { e.printStackTrace(); return this.setModel(true, false, e.getMessage()); } } /** * 保存更新菜单信息 * @param params * @return */ @RequestMapping("save") @ResponseBody public Object save(@RequestBody Map<String, Object> params){ Object permitcode = params.get("permitcode"); if(permitcode==null||permitcode.equals("")){ return insert(params); }else { return update(params); } } private Object insert(Map<String, Object> params){ try { params.put("permitcode", RdsUpcUUIDUtil.getUUID()); int result = rdsUpcPermitService.insert(params); if (result > 0) { return this.setModel(true, RdsUpcConstantUtil.INSERT_SUCCESS); } else { return this.setModel(false, RdsUpcConstantUtil.INSERT_FAILED); } } catch (Exception e) { e.printStackTrace(); return this.setModel(true, false, RdsUpcConstantUtil.EXCEPTION + "\n" + e.getMessage()); } } private Object update(Map<String, Object> params){ try { int result = rdsUpcPermitService.update(params); if (result > 0) { return this.setModel(true, RdsUpcConstantUtil.UPDATE_SUCCESS); } else { return this.setModel(false, RdsUpcConstantUtil.UPDATE_FAILED); } } catch (Exception e) { e.printStackTrace(); return this.setModel(true, false, e.getMessage()); } } }
Java
UTF-8
4,091
2.4375
2
[]
no_license
/** * */ package com.softsec.tase.store.util.db; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.MongoClient; import com.mongodb.ServerAddress; import com.mongodb.WriteConcern; import com.softsec.tase.common.util.StringUtils; import com.softsec.tase.store.Configuration; import com.softsec.tase.store.Constants; /** *@author yanwei *@time: 2012-11-6 上午11:01:01 *@description Mongodb连接工厂类 * */ /** * */ public class MongodbConnFactory { private static final Logger LOGGER = LoggerFactory.getLogger(MongodbConnFactory.class); private static final String MONGODB_URIS = Configuration.get(Constants.MONGODB_URIS, "localhost:27017"); private static final String DBNAME = Configuration.get(Constants.MONGODB_NAME, "tase"); private static final String USERNAME = Configuration.get(Constants.MONGODB_USERNAME, "softsec"); private static final String PASSWORD = Configuration.get(Constants.MONGODB_PASSWORD, "62283748"); private static final DB mongodb; static { // parse mongodb server uri String[] serverArray = MONGODB_URIS.trim().split(";"); if (serverArray.length > 1) { List<ServerAddress> serverAddrList = new ArrayList<ServerAddress>(); for (String server : serverArray) { if (!StringUtils.isEmpty(server)) { try { serverAddrList.add(new ServerAddress(server.split(":")[0].trim(), Integer.parseInt(server.split(":")[1]))); System.out.println(serverAddrList); } catch (NumberFormatException nfe) { LOGGER.error("Failed to parse mongodb server configuration : " + MONGODB_URIS + " : " + nfe.getMessage(), nfe); throw new RuntimeException("Failed to parse mongodb server configuration : " + MONGODB_URIS + " : " + nfe.getMessage(), nfe); } catch (UnknownHostException uhe) { LOGGER.error("Failed to connect mongodb server : " + MONGODB_URIS + " : " + uhe.getMessage(), uhe); throw new RuntimeException("Failed to connect mongodb server : " + MONGODB_URIS + " : " + uhe.getMessage(), uhe); } } } // mongodb connection configuration // initialize mongo client MongoClient client = new MongoClient(serverAddrList); mongodb = client.getDB(DBNAME); // Exceptions are raised for network issues, and server errors; waits for at least 2 servers for the write operation // for production use mongodb.setWriteConcern(WriteConcern.REPLICAS_SAFE); } else { try { MongoClient client = new MongoClient(serverArray[0].split(":")[0].trim(), Integer.parseInt(serverArray[0].split(":")[1])); mongodb = client.getDB(DBNAME); // Exceptions are raised for network issues, and server errors; waits on a server for the write operation // for development use mongodb.setWriteConcern(WriteConcern.SAFE); } catch (NumberFormatException nfe) { LOGGER.error("Failed to parse mongodb server configuration : " + MONGODB_URIS + " : " + nfe.getMessage(), nfe); throw new RuntimeException("Failed to parse mongodb server configuration : " + MONGODB_URIS + " : " + nfe.getMessage(), nfe); } catch (UnknownHostException uhe) { LOGGER.error("Failed to connect mongodb server : " + MONGODB_URIS + " : " + uhe.getMessage(), uhe); throw new RuntimeException("Failed to connect mongodb server : " + MONGODB_URIS + " : " + uhe.getMessage(), uhe); } } if (!mongodb.authenticate(USERNAME, PASSWORD.toCharArray())) { LOGGER.error("Invalid username or password to login mongodb : " + MONGODB_URIS); throw new RuntimeException("Invalid username or password to login mongodb : " + MONGODB_URIS); } } /** * */ public MongodbConnFactory() { } public static final DB getDB () { return mongodb; } public static final DBCollection getCollection (String collectionName) { return mongodb.getCollection(collectionName); } }
Shell
UTF-8
735
3.234375
3
[ "Apache-2.0", "MIT" ]
permissive
#!/bin/bash VERSION=`date "+%Y%m%d%H"` APP_NAME="node_exporter" GO_ARCH=`go env| grep GOARCH|awk -F\" '{print $2}'` cd `dirname $0` WORKDIR=`pwd| sed 's#.*/src#/go/src#g'` docker run --rm -it -v ${GOPATH}:/go -w ${WORKDIR} golang:latest go build -o ${APP_NAME}-${VERSION}.linux.${GO_ARCH} -v echo "Linux Packaging Binaries..." mkdir -p tmp/${APP_NAME} mv ${APP_NAME}-${VERSION}.linux.${GO_ARCH} tmp/${APP_NAME}/ #cp -rp config/config.yml tmp/${APP_NAME}/ mkdir -p ./dist/ #tar -czf $@ -C tmp $(APP_NAME); tar -cvzf ${APP_NAME}-${VERSION}.linux.${GO_ARCH}.tar.gz -C tmp . mv ${APP_NAME}-${VERSION}.linux.${GO_ARCH}.tar.gz ./dist/ rm -rf tmp echo echo "Package ${APP_NAME}-${VERSION}.linux.${GO_ARCH}.tar.gz saved in dist directory"
JavaScript
UTF-8
2,661
2.578125
3
[ "Apache-2.0" ]
permissive
var config = require('dgeni/lib/utils/config').Config; var processor = require('../../processors/inline-tags'); var di = require('di'); var log = require('winston'); describe("inline-tags processor", function() { it("should be called 'inline-tags'", function() { expect(processor.name).toEqual('inline-tags'); }); it("should run after docs are rendered and before writing files", function() { expect(processor.runAfter).toEqual(['docs-rendered']); expect(processor.runBefore).toEqual(['writing-files']); }); describe("process", function() { it("should parse the inline tags from the renderedContent", function() { // The processor is mostly only interested in the renderedContent but the other fields are // used in error reporting var doc = { file: 'a/b/c.js', startingLine: 123, renderedContent: 'abc def\n' + 'xyz {@unhandledTag some description} fgh\n' + '{@handledTag other description}' }; var docs = [doc]; var tagsFound = []; var mockInlineTagDefinition = { name: 'handledTag', handlerFactory: function(docs) { return function(doc, tagName, tagDescription) { tagsFound.push({ name: tagName, description: tagDescription }); return '<Tag Handled>'; }; } }; // We spy on log.warn since this will be called on each missing handler spyOn(log, 'warn'); // Create the injector that the processor will use var injector = new di.Injector([ { docs: ['value', docs] } ]); // Provide a mock inline tag handler config.set('processing.inlineTagDefinitions', [mockInlineTagDefinition]); // Run the processor processor.init(config); var results = processor.process(docs, injector); // This processor should not return anything. All its work is done on the docs, in place expect(results).toBeUndefined(); // We expect the unhandled tag to be reported expect(log.warn).toHaveBeenCalled(); expect(log.warn.calls[0].args[0]).toMatch(/No handler provided for inline tag "\{@unhandledTag some description\}"/); // We expect the handler to have been invoked for the handledTag expect(tagsFound).toEqual([ { name: 'handledTag', description: 'other description' } ]); // We expect the unhandled tag to habe been left alone and the handled tag to have been replaced expect(doc.renderedContent).toEqual( 'abc def\n' + 'xyz {@unhandledTag some description} fgh\n' + '<Tag Handled>' ); }); }); });
C
UTF-8
1,514
3.25
3
[]
no_license
// // Created by apple on 2017/3/17. // #include <stdio.h> #include <string.h> #include <stdbool.h> static char* mystrtok(char *pstr, char *split) { char *px = pstr; _Bool isfind = true; while(*px != '\0') { char *p1 = px; char *p2 = split; isfind = true; while(*p2 != '\0') { if(*p2 != *p1) { isfind = false; break; } p2++; p1++; } if(isfind) { //px指向字符串split在字符串pstr中开始的位置 *px = '\0'; break; } else { px++; } } if(isfind) //找到了 { return pstr; } return NULL; //没有找到就返回NULL } int mainstrtok(int argc, char* argv[]) { { char str[100] = "123,qwr,hello,wrod"; // char *px = strtok(str, ","); // printf("%s\n", px); for(char *px = strtok(str, ","); px != NULL; px = strtok(px + strlen(px) + strlen(","), ",")) { printf("%s\n", px); } printf("\n"); char str1[100] = "nihao hello one hello two hello three"; // char *px = mystrtok(str1, "hello"); // printf("%s\n", px); for(char *px = mystrtok(str1, "hello"); px != NULL; px = mystrtok(px + strlen(px) + strlen("hello"), "hello")) { printf("%s\n", px); } printf("\n"); } return 0; }
SQL
UTF-8
7,373
3.265625
3
[]
no_license
/*==============================================================*/ /* DBMS name: PostgreSQL 8 */ /* Created on: 23/02/2016 16:12:01 */ /*==============================================================*/ /*==============================================================*/ /* Table: CARRERA */ /*==============================================================*/ create table CARRERA ( COD_CARR INT4 not null, COD_FACU INT4 not null, NOMB_CARR CHAR(100) null, TIPO_CARR CHAR(100) null, VERSION_CARR INT4 null, REGION_CARR CHAR(100) null, constraint PK_CARRERA primary key (COD_CARR) ); /*==============================================================*/ /* Index: CARRERA_PK */ /*==============================================================*/ create unique index CARRERA_PK on CARRERA ( COD_CARR ); /*==============================================================*/ /* Index: RELATIONSHIP_4_FK */ /*==============================================================*/ create index RELATIONSHIP_4_FK on CARRERA ( COD_FACU ); /*==============================================================*/ /* Table: DESIGNADO */ /*==============================================================*/ create table DESIGNADO ( COD_DOC VARCHAR(10) not null, COD_MATERIA VARCHAR(20) not null, COD_CARR INT4 not null, constraint PK_DESIGNADO primary key (COD_DOC, COD_MATERIA, COD_CARR) ); /*==============================================================*/ /* Index: POR_UN_FK */ /*==============================================================*/ create index POR_UN_FK on DESIGNADO ( COD_DOC ); /*==============================================================*/ /* Index: DICTA_MATERIA_FK */ /*==============================================================*/ create index DICTA_MATERIA_FK on DESIGNADO ( COD_MATERIA ); /*==============================================================*/ /* Index: PERTENECE_FK */ /*==============================================================*/ create index PERTENECE_FK on DESIGNADO ( COD_CARR ); /*==============================================================*/ /* Table: DOCENTE */ /*==============================================================*/ create table DOCENTE ( COD_DOC VARCHAR(10) not null, CI_DOC INT4 null, NOMB_DOC CHAR(100) null, APELLIDO_PAT CHAR(100) null, APELLIDO_MAT CHAR(100) null, DIRECCION_DOC VARCHAR(50) null, TEL_DOC INT4 null, CEL_DOC INT4 null, EMAIL_DOC CHAR(300) null, constraint PK_DOCENTE primary key (COD_DOC) ); /*==============================================================*/ /* Index: DOCENTE_PK */ /*==============================================================*/ create unique index DOCENTE_PK on DOCENTE ( COD_DOC ); /*==============================================================*/ /* Table: FACULTAD */ /*==============================================================*/ create table FACULTAD ( COD_FACU INT4 not null, NOMB_FACU CHAR(300) null, constraint PK_FACULTAD primary key (COD_FACU) ); /*==============================================================*/ /* Index: FACULTAD_PK */ /*==============================================================*/ create unique index FACULTAD_PK on FACULTAD ( COD_FACU ); /*==============================================================*/ /* Table: MATERIA */ /*==============================================================*/ create table MATERIA ( COD_MATERIA VARCHAR(20) not null, NOMB_MATERIA VARCHAR(100) null, NIVEL VARCHAR(30) null, ELECTIVA CHAR(2) null, SIGLA VARCHAR(20) null, constraint PK_MATERIA primary key (COD_MATERIA) ); /*==============================================================*/ /* Index: MATERIA_PK */ /*==============================================================*/ create unique index MATERIA_PK on MATERIA ( COD_MATERIA ); /*==============================================================*/ /* Table: PRE_REQUISITO */ /*==============================================================*/ create table PRE_REQUISITO ( COD_MATERIA VARCHAR(20) not null, MAT_COD_MATERIA VARCHAR(20) not null, constraint PK_PRE_REQUISITO primary key (COD_MATERIA, MAT_COD_MATERIA) ); /*==============================================================*/ /* Index: PRE_REQUISITO_PK */ /*==============================================================*/ create unique index PRE_REQUISITO_PK on PRE_REQUISITO ( COD_MATERIA, MAT_COD_MATERIA ); /*==============================================================*/ /* Index: ES_MATERIA_FK */ /*==============================================================*/ create index ES_MATERIA_FK on PRE_REQUISITO ( COD_MATERIA ); /*==============================================================*/ /* Index: ES_PRE_REQUISTO_FK */ /*==============================================================*/ create index ES_PRE_REQUISTO_FK on PRE_REQUISITO ( MAT_COD_MATERIA ); alter table CARRERA add constraint FK_CARRERA_RELATIONS_FACULTAD foreign key (COD_FACU) references FACULTAD (COD_FACU) on delete restrict on update restrict; alter table DESIGNADO add constraint FK_DESIGNAD_DICTA_MAT_MATERIA foreign key (COD_MATERIA) references MATERIA (COD_MATERIA) on delete restrict on update restrict; alter table DESIGNADO add constraint FK_DESIGNAD_PERTENECE_CARRERA foreign key (COD_CARR) references CARRERA (COD_CARR) on delete restrict on update restrict; alter table DESIGNADO add constraint FK_DESIGNAD_POR_UN_DOCENTE foreign key (COD_DOC) references DOCENTE (COD_DOC) on delete restrict on update restrict; alter table PRE_REQUISITO add constraint FK_PRE_REQU_ES_MATERI_MATERIA foreign key (COD_MATERIA) references MATERIA (COD_MATERIA) on delete restrict on update restrict; alter table PRE_REQUISITO add constraint FK_PRE_REQU_ES_PRE_RE_MATERIA foreign key (MAT_COD_MATERIA) references MATERIA (COD_MATERIA) on delete restrict on update restrict;
Java
UTF-8
31,514
1.921875
2
[ "Apache-2.0" ]
permissive
package edu.harvard.iq.policymodels.parser.decisiongraph; import edu.harvard.iq.policymodels.parser.decisiongraph.DecisionGraphRuleParser; import edu.harvard.iq.policymodels.parser.decisiongraph.DecisionGraphTerminalParser; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstAnswerSubNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstAskNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstCallNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstConsiderOptionSubNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstConsiderNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstContinueNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstEndNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstImport; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstInfoSubNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstNodeHead; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstPartNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstRejectNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstSectionNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstSetNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstTermSubNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstTextSubNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.AstTodoNode; import edu.harvard.iq.policymodels.parser.decisiongraph.ast.ParsedFile; import java.util.Arrays; import static java.util.Arrays.asList; import java.util.Collections; import java.util.List; import org.jparsec.Parser; import org.jparsec.Parsers; import org.jparsec.error.ParserException; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author michael */ public class DecisionGraphRuleParserTest { public DecisionGraphRuleParserTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void nodeHeadNoId() { Parser<AstNodeHead> joe = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.nodeHead("end")); assertEquals(new AstNodeHead(null, "end"), joe.parse("end")); assertEquals(new AstNodeHead(null, "end"), joe.parse(" end")); assertEquals(new AstNodeHead(null, "end"), joe.parse("end ")); assertEquals(new AstNodeHead(null, "end"), joe.parse(" end <-- sut ")); } @Test public void nodeHeadWithId() { Parser<AstNodeHead> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.nodeHead("end")); assertEquals(new AstNodeHead("id", "end"), sut.parse(">id<end")); assertEquals(new AstNodeHead("id", "end"), sut.parse(">id< end")); assertEquals(new AstNodeHead("id", "end"), sut.parse(">id< end")); assertEquals(new AstNodeHead("id", "end"), sut.parse(" >id< end ")); assertEquals(new AstNodeHead("177", "end"), sut.parse(" >177< end ")); assertEquals(new AstNodeHead("abcdEFG123-._", "end"), sut.parse(" >abcdEFG123-._< end ")); } @Test public void endNodeWithId() { Parser<AstEndNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.END_NODE); assertEquals(new AstEndNode("123"), sut.parse("[>123< end]")); assertEquals(new AstEndNode("123"), sut.parse("[ >123< end]")); assertEquals(new AstEndNode("123"), sut.parse("[>123< end ]")); assertEquals(new AstEndNode("123"), sut.parse("[>123<end]")); assertEquals(new AstEndNode("123"), sut.parse("[>123<\nend]")); assertEquals(new AstEndNode("123"), sut.parse("[>123< <-- That's the id? " + "\nend]")); } @Test public void endNodeNoId() { Parser<AstEndNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.END_NODE); assertEquals(new AstEndNode(null), sut.parse("[end]")); assertEquals(new AstEndNode(null), sut.parse("[ end]")); assertEquals(new AstEndNode(null), sut.parse("[ end ]")); assertEquals(new AstEndNode(null), sut.parse("[end ]")); assertEquals(new AstEndNode(null), sut.parse("[\nend]")); assertEquals(new AstEndNode(null), sut.parse("[<-- What, no id? " + "\nend]")); } @Test public void todoNodeWithId() { Parser<AstTodoNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.TODO_NODE); assertEquals(new AstTodoNode("123", "finalize this"), sut.parse("[>123< todo: finalize this]")); assertEquals(new AstTodoNode("123", "finalize this"), sut.parse("[ >123< todo:\nfinalize this ]")); assertEquals(new AstTodoNode("123", "finalize this"), sut.parse("[>123<todo:finalize this]")); } @Test public void todoNodeNoId() { Parser<AstTodoNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.TODO_NODE); assertEquals(new AstTodoNode(null, "finalize this"), sut.parse("[ todo: finalize this]")); assertEquals(new AstTodoNode(null, "finalize this"), sut.parse("[todo:\nfinalize this]")); assertEquals(new AstTodoNode(null, "finalize this"), sut.parse("[todo:finalize this]")); } @Test public void callNodeNoId() { Parser<AstCallNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.CALL_NODE); assertEquals(new AstCallNode(null, "abcd#$%"), sut.parse("[ call: abcd#$%]")); assertEquals(new AstCallNode(null, "abcd#$%"), sut.parse("[call:\nabcd#$%]")); assertEquals(new AstCallNode(null, "abcd#$%"), sut.parse("[call:abcd#$%]")); } @Test public void callNodeWITHId() { Parser<AstCallNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.CALL_NODE); assertEquals(new AstCallNode("CN", "abcd#$%"), sut.parse("[>CN< call: abcd#$%]")); assertEquals(new AstCallNode("CN", "abcd#$%"), sut.parse("[>CN< call:\nabcd#$%]")); assertEquals(new AstCallNode("CN", "abcd#$%"), sut.parse("[>CN<call:abcd#$%]")); } @Test public void rejectNodeWithId() { Parser<AstRejectNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.REJECT_NODE); assertEquals(new AstRejectNode("123", "finalize this"), sut.parse("[>123< reject: finalize this]")); assertEquals(new AstRejectNode("123", "finalize this"), sut.parse("[ >123< reject:\nfinalize this ]")); assertEquals(new AstRejectNode("123", "finalize this"), sut.parse("[>123<reject:finalize this]")); } @Test public void rejectNodeNoId() { Parser<AstRejectNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.REJECT_NODE); assertEquals(new AstRejectNode(null, "finalize this"), sut.parse("[ reject: finalize this]")); assertEquals(new AstRejectNode(null, "finalize this"), sut.parse("[reject:\nfinalize this]")); assertEquals(new AstRejectNode(null, "finalize this"), sut.parse("[reject:finalize this\n\n\n]")); assertEquals(new AstRejectNode(null, "finalize\nthis"), sut.parse("[ reject: finalize\nthis]")); assertEquals(new AstRejectNode(null, "finalize 16 of these !@#!%!#$!$"), sut.parse("[ reject: finalize 16 of these !@#!%!#$!$]")); } @Test public void rejectNodeWithCommas() { Parser<AstRejectNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.REJECT_NODE); String rejectText = "unfortunately, we cannot accept your dataset. You're likely breaching §7.6.1(ii) of BANANAA. Can we ask why?"; assertEquals(new AstRejectNode(null, rejectText), sut.parse("[reject: " + rejectText + "]")); } @Test public void sectionNodeNoId() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<AstSectionNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.sectionNode(bodyParser)); assertEquals(new AstSectionNode(null, new AstInfoSubNode("bla bla"), asList(new AstTodoNode(null, "bla"))), sut.parse("[ section: {title: bla bla}\n[todo: bla] ]")); assertEquals(new AstSectionNode(null, asList(new AstTodoNode(null, "bla"))), sut.parse("[ section: \n\n [todo: bla]\n\n\n ]")); assertEquals(new AstSectionNode(null, new AstInfoSubNode("bla bla"), asList(new AstTodoNode(null, "bla"))), sut.parse("[section:{title: bla bla}[todo: bla]]")); } @Test public void sectionNodeWithId() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<AstSectionNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.sectionNode(bodyParser)); assertEquals(new AstSectionNode("id", new AstInfoSubNode("bla bla"), asList(new AstTodoNode(null, "bla"))), sut.parse("[>id< section: {title: bla bla}\n[todo: bla] ]")); assertEquals(new AstSectionNode("id", asList(new AstTodoNode(null, "bla"))), sut.parse("[>id<section: \n\n [todo: bla]\n\n\n ]")); assertEquals(new AstSectionNode("id", new AstInfoSubNode("bla bla"), asList(new AstTodoNode(null, "bla"))), sut.parse("[>id<section:{title: bla bla}[todo: bla]]")); } @Test(expected = ParserException.class) public void partNodeNoId() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<AstPartNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.partNode(bodyParser)); sut.parse("[-- {title: bla bla}\n[todo: bla] ]"); } @Test public void partNodeWithId() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<AstPartNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.partNode(bodyParser)); assertEquals(new AstPartNode("id", asList(new AstTodoNode(null, "bla"))), sut.parse("[-->id< [todo: bla] --]")); assertEquals(new AstPartNode("id", asList(new AstTodoNode(null, "bla"))), sut.parse("[-->id< \n\n [todo: bla]\n\n\n --]")); assertEquals(new AstPartNode("id", asList(new AstTodoNode(null, "bla"))), sut.parse("[-->id<[todo: bla]--]")); } @Test public void continueNodeWithId() { Parser<AstContinueNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.CONTINUE_NODE); assertEquals(new AstContinueNode("123"), sut.parse("[>123< continue]")); assertEquals(new AstContinueNode("123"), sut.parse("[ >123< continue]")); assertEquals(new AstContinueNode("123"), sut.parse("[>123< continue ]")); assertEquals(new AstContinueNode("123"), sut.parse("[>123<continue]")); assertEquals(new AstContinueNode("123"), sut.parse("[>123<\ncontinue]")); assertEquals(new AstContinueNode("123"), sut.parse("[>123< <-- That's the id? " + "\ncontinue]")); } @Test public void continueNodeWithoutId() { Parser<AstContinueNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.CONTINUE_NODE); assertEquals(new AstContinueNode(null), sut.parse("[ continue]")); assertEquals(new AstContinueNode(null), sut.parse("[ continue ]")); assertEquals(new AstContinueNode(null), sut.parse("[continue]")); assertEquals(new AstContinueNode(null), sut.parse("[\ncontinue]")); assertEquals(new AstContinueNode(null), sut.parse("[ <-- That's the id? " + "\ncontinue]")); } @Test public void atomicAssignmentSlotTest() { Parser<AstSetNode.AtomicAssignment> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.ATOMIC_ASSIGNMENT_SLOT); assertEquals(new AstSetNode.AtomicAssignment(asList("s"), "v"), sut.parse("s=v")); assertEquals(new AstSetNode.AtomicAssignment(asList("s"), "v"), sut.parse("s =v")); assertEquals(new AstSetNode.AtomicAssignment(asList("s"), "v"), sut.parse("s= v")); assertEquals(new AstSetNode.AtomicAssignment(asList("s"), "v"), sut.parse("s = v ")); assertEquals(new AstSetNode.AtomicAssignment(asList("s"), "v"), sut.parse("s = v")); assertEquals(new AstSetNode.AtomicAssignment(asList("top", "mid", "bottom"), "aValue"), sut.parse("top/mid/bottom=aValue")); assertEquals(new AstSetNode.AtomicAssignment(asList("top", "mid", "bottom"), "aValue"), sut.parse("top / mid / bottom = aValue")); } @Test public void atomicAssignmentSlotKeywordTest() { Parser<AstSetNode.AtomicAssignment> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.ATOMIC_ASSIGNMENT_SLOT); assertEquals(new AstSetNode.AtomicAssignment(asList("gsk"), "set"), sut.parse("gsk=set")); assertEquals(new AstSetNode.AtomicAssignment(asList("ask"), "set"), sut.parse("ask=set")); assertEquals(new AstSetNode.AtomicAssignment(asList("ask", "askyy", "askset", "askMMset"), "set"), sut.parse("ask/askyy/askset/askMMset=set")); } @Test public void aggregateAssignmentSlotTest() { Parser<AstSetNode.AggregateAssignment> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.AGGREGATE_ASSIGNMENT_SLOT); assertEquals(new AstSetNode.AggregateAssignment(asList("s"), Arrays.asList("v")), sut.parse("s+=v")); assertEquals(new AstSetNode.AggregateAssignment(asList("top", "mid", "bottom"), asList("val1", "val2", "val3")), sut.parse("top/mid/bottom+=val1, val2, val3")); } @Test public void aggregateAssignmentSlotWithKeywordsTest() { Parser<AstSetNode.AggregateAssignment> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.AGGREGATE_ASSIGNMENT_SLOT); assertEquals(new AstSetNode.AggregateAssignment(asList("set"), Arrays.asList("ask")), sut.parse("set+=ask")); assertEquals(new AstSetNode.AggregateAssignment(asList("xset"), Arrays.asList("xask")), sut.parse("xset+=xask")); assertEquals(new AstSetNode.AggregateAssignment(asList("setx"), Arrays.asList("askx")), sut.parse("setx+=askx")); assertEquals(new AstSetNode.AggregateAssignment(asList("xsetx"), Arrays.asList("xaskx")), sut.parse("xsetx+=xaskx")); assertEquals(new AstSetNode.AggregateAssignment(asList("xsetxsetx"), Arrays.asList("xaskxsetx")), sut.parse("xsetxsetx+=xaskxsetx")); } @Test public void setNodeSimple() { Parser<AstSetNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.SET_NODE); AstSetNode expected = new AstSetNode(null, asList(new AstSetNode.AtomicAssignment(asList("k"), "v"))); assertEquals(expected, sut.parse("[set: k=v]")); assertEquals(expected, sut.parse("[set:k=v]")); assertEquals(expected, sut.parse("[set: k=v ]")); } @Test public void setNodeSimpleWithId() { Parser<AstSetNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.SET_NODE); AstSetNode expected = new AstSetNode("Set-._", asList(new AstSetNode.AtomicAssignment(asList("k"), "v"))); assertEquals(expected, sut.parse("[>Set-._<set: k=v]")); assertEquals(expected, sut.parse("[>Set-._< set: k=v]")); assertEquals(expected, sut.parse("[>Set-._< set: k = v ]")); } @Test public void setNodeSimpleAggregate() { Parser<AstSetNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.SET_NODE); AstSetNode expected = new AstSetNode("Set-._", asList(new AstSetNode.AggregateAssignment(asList("k"), asList("v")))); assertEquals(expected, sut.parse("[>Set-._<set: k+=v]")); assertEquals(expected, sut.parse("[>Set-._< set: k += v]")); assertEquals(expected, sut.parse("[>Set-._< set: k+=v ]")); } @Test public void setNodeAggregate() { Parser<AstSetNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.SET_NODE); AstSetNode expected = new AstSetNode("anId", asList(new AstSetNode.AggregateAssignment(asList("k"), asList("v1", "v2")))); assertEquals(expected, sut.parse("[>anId<set: k += v1, v2]")); assertEquals(expected, sut.parse("[>anId<set: k+=v1, v2]")); assertEquals(expected, sut.parse("[>anId<set: k+=v1,v2]")); expected = new AstSetNode("anId", asList(new AstSetNode.AggregateAssignment(asList("k1", "k2"), asList("v")))); assertEquals(expected, sut.parse("[>anId< set: k1/k2 += v]")); assertEquals(expected, sut.parse("[>anId< set: k1/k2+=v ]")); expected = new AstSetNode("anId", asList(new AstSetNode.AggregateAssignment(asList("k1", "k2", "k3"), asList("v1", "v2", "v3")))); assertEquals(expected, sut.parse("[>anId< set: k1/k2/k3 += v1, v2, v3]")); assertEquals(expected, sut.parse("[>anId< set: k1/k2/k3 += v1,v2,v3]")); assertEquals(expected, sut.parse("[>anId<set:k1/k2/k3+=v1,v2,v3]")); } @Test public void setNode() { Parser<AstSetNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.SET_NODE); AstSetNode expected = new AstSetNode("anId", asList(new AstSetNode.AggregateAssignment(asList("k"), asList("v1", "v2")), new AstSetNode.AggregateAssignment(asList("j", "j2"), asList("v")), new AstSetNode.AtomicAssignment(asList("r"), "vee"), new AstSetNode.AggregateAssignment(asList("l1", "l2", "l3"), asList("v1", "v2", "v3")))); assertEquals(expected, sut.parse("[>anId<set: k += v1, v2; j/j2+=v; r=vee; l1/l2/l3+=v1,v2,v3 ]")); } @Test public void textSubNode() { Parser<AstTextSubNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.TEXT_SUBNODE); assertEquals(new AstTextSubNode("lorem ipsum"), sut.parse("{text: lorem ipsum}")); assertEquals(new AstTextSubNode("lorem 333ipsum"), sut.parse("{text: lorem 333ipsum}")); assertEquals(new AstTextSubNode("lorem ]]]ipsum"), sut.parse("{text: lorem ]]]ipsum}")); assertEquals(new AstTextSubNode("38905673n;jlqrsgh-12957gh1kqjng5379sa fqwrgwgt <> ouou 5"), sut.parse("{text: 38905673n;jlqrsgh-12957gh1kqjng5379sa fqwrgwgt <> ouou 5}")); } @Test public void termSubNode() { Parser<AstTermSubNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.TERM_SUBNODE); assertEquals(new AstTermSubNode("lorem", "lorem ipsum"), sut.parse("{lorem: lorem ipsum}")); assertEquals(new AstTermSubNode("lorem ipsum", "lorem 333ipsum"), sut.parse("{lorem ipsum: lorem 333ipsum}")); assertEquals(new AstTermSubNode("lorem", "lorem ]]]ipsum"), sut.parse("{lorem: lorem ]]]ipsum}")); } @Test public void importNode() { Parser<AstImport> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.IMPORT); assertEquals(new AstImport("SimpleValue", "pp1"), sut.parse("[#import pp1: SimpleValue]")); assertEquals(new AstImport("C://User/Docs/dg1.dg", "pp2"), sut.parse("[#import pp2: C://User/Docs/dg1.dg]")); assertEquals(new AstImport("/users/joe/pm/pm-9/dg.dg", "pp3"), sut.parse("[#import pp3: /users/joe/pm/pm-9/dg.dg]")); assertEquals(new AstImport("C://file with space", "pp4"), sut.parse("[#import pp4: C://file with space]")); } @Test public void termsSubNode() { Parser<List<AstTermSubNode>> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.TERMS_SUBNODE); assertEquals(Collections.<AstTermSubNode>emptyList(), sut.parse("{terms:}")); assertEquals(asList(new AstTermSubNode("lorem", "lorem ipsum")), sut.parse("{terms: {lorem: lorem ipsum}}")); List<AstTermSubNode> expectedTermList = asList(new AstTermSubNode("lorem", "lorem ipsum"), new AstTermSubNode("dolor", "lorem 333ipsum"), new AstTermSubNode("Gobala cabana", "#dolor sit #amet")); assertEquals(expectedTermList, sut.parse("{terms: {lorem: lorem ipsum}{dolor: lorem 333ipsum}{Gobala cabana: #dolor sit #amet}}")); assertEquals(expectedTermList, sut.parse("{terms:{lorem: lorem ipsum}\n" + "{dolor: lorem 333ipsum} \n" + "{Gobala cabana: #dolor sit #amet}}")); assertEquals(expectedTermList, sut.parse("{terms:{lorem: lorem ipsum}\n" + "{dolor: lorem 333ipsum} <-- can someone validate this?!\n" + "{Gobala cabana: #dolor sit #amet}}")); assertEquals(expectedTermList, sut.parse("{terms:{lorem: lorem ipsum}\n" + "<* {dolor: lorem 333ipsum} old version, can we remove this? *>\n" + "{dolor: lorem 333ipsum} <-- can someone validate this?!\n" + "{Gobala cabana: #dolor sit #amet}}")); } @Test public void answerNodeTest() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<AstAnswerSubNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.answerSubNode(bodyParser)); assertEquals(new AstAnswerSubNode("yes", asList(new AstTodoNode("td", "do this"), new AstTodoNode("te", "do that"))), sut.parse("{yes: [>td< todo:do this][>te< todo: do that]}")); assertEquals(new AstAnswerSubNode("Dorothy Stein", asList(new AstTodoNode("td", "do this"), new AstTodoNode("te", "do that"))), sut.parse("{Dorothy Stein: [>td< todo:do this][>te< todo: do that]}")); } @Test public void answersNodeTest() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<List<AstAnswerSubNode>> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.answersSubNode(bodyParser)); assertEquals(asList(new AstAnswerSubNode("yes", asList(new AstTodoNode("td", "do this"), new AstTodoNode("te", "do that")))), sut.parse("{answers: {yes: [>td< todo:do this][>te< todo: do that]}}")); assertEquals(asList(new AstAnswerSubNode("yes", asList(new AstTodoNode("td", "do this"))), new AstAnswerSubNode("no", asList(new AstTodoNode("td", "do this"), new AstTodoNode("te", "do that"))), new AstAnswerSubNode("maybe so", asList(new AstTodoNode("td", "do this"), new AstEndNode(null)))), sut.parse("{answers: " + "{yes: [>td< todo:do this]}" + "{no: [>td< todo:do this][>te< todo: do that]}" + "{maybe so: [>td< todo:do this][end]}" + "}")); } @Test public void testConsiderNode() { String program = "[>44< consider:\n" + " {slot:Greeting } \n" + " {options: \n" + " {hello:[set: Subject+= world] \n}}" + " {else: [set:Subject+=planet] }]\n" + "[end]"; List<? extends AstNode> expected = asList(new AstConsiderNode("44", asList("Greeting"), asList(new AstConsiderOptionSubNode( asList("hello"), asList(new AstSetNode(null, asList(new AstSetNode.AggregateAssignment(asList("Subject"), asList("world"))))))), asList(new AstSetNode(null, asList(new AstSetNode.AggregateAssignment(asList("Subject"), asList("planet")))))), new AstEndNode(null) ); Parser<ParsedFile> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.graphParser()); assertEquals(expected, sut.parse(program).getAstNodes()); } @Test public void testWhenNode() { String program = "[>44< when:\n" + " {Greeting=hello:[set: Subject+= world] \n}" + " {else: [set:Subject+=planet] }]\n" + "[end]"; List<? extends AstNode> expected = asList(new AstConsiderNode("44", null, asList(new AstConsiderOptionSubNode( asList(new AstSetNode.AtomicAssignment(asList("Greeting"), "hello")), asList(new AstSetNode(null, asList(new AstSetNode.AggregateAssignment(asList("Subject"), asList("world"))))))), asList(new AstSetNode(null, asList(new AstSetNode.AggregateAssignment(asList("Subject"), asList("planet")))))), new AstEndNode(null) ); Parser<ParsedFile> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.graphParser()); assertEquals(expected, sut.parse(program).getAstNodes()); } @Test public void askNodeTest() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<AstAskNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.askNode(bodyParser)); assertEquals(new AstAskNode("id", new AstTextSubNode("why do that?"), asList(new AstTermSubNode("that", "a thingy")), asList(new AstAnswerSubNode("yes", asList(new AstEndNode(null))), new AstAnswerSubNode("no", asList(new AstEndNode("no-end"))))), sut.parse("[>id< ask:" + " {text: why do that?} " + " {terms: {that: a thingy} }" + " {answers: " + " {yes: [end]} " + " {no: [>no-end< end]} " + "}]")); assertEquals(new AstAskNode("id", new AstTextSubNode("why do that?"), null, asList(new AstAnswerSubNode("yes", asList(new AstEndNode(null))), new AstAnswerSubNode("no", asList(new AstEndNode("no-end"))))), sut.parse("[>id< ask:" + " {text: why do that?} " + " {answers: " + " {yes: [end]} " + " {no: [>no-end< end]} " + "}]")); } @Test public void sectionNodeTest() { Parser<List<? extends AstNode>> bodyParser = Parsers.or(DecisionGraphRuleParser.END_NODE, DecisionGraphRuleParser.TODO_NODE).many().cast(); Parser<AstSectionNode> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.sectionNode(bodyParser)); assertEquals(new AstSectionNode("id", new AstInfoSubNode("TO-DO List"), asList(new AstTodoNode(null, "first thing"), new AstTodoNode(null, "second thing"))), sut.parse("[>id< section:" + " {title: TO-DO List} " + " [todo: first thing]" + " [todo: second thing] " + "]")); } @Test public void smallProgramTest() { String program = "[>44< ask:\n" + " {text: Do the data concern living persons?} <-- The big question here\n" + " {answers: \n" + " {yes:\n" + " [set: identity=personData] <--- Oh, no you don't\n" + " [call: medRecs ]\n" + " [todo: Arrest and Conviction Records]}\n" + " {no: [set:identity=noPersonData] }\n" + " {not sure: [reject:please check]}}]\n" + "[call: dua]\n" + "[end]"; List<? extends AstNode> expected = asList( new AstAskNode("44", new AstTextSubNode("Do the data concern living persons?"), null, asList(new AstAnswerSubNode("yes", asList(new AstSetNode(null, asList(new AstSetNode.AtomicAssignment(asList("identity"), "personData"))), new AstCallNode(null, "medRecs"), new AstTodoNode(null, "Arrest and Conviction Records"))), new AstAnswerSubNode("no", asList(new AstSetNode(null, asList(new AstSetNode.AtomicAssignment(asList("identity"), "noPersonData"))))), new AstAnswerSubNode("not sure", asList(new AstRejectNode(null, "please check"))))), new AstCallNode(null, "dua"), new AstEndNode(null) ); Parser<ParsedFile> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.graphParser()); assertEquals(expected, sut.parse(program).getAstNodes()); } @Test public void parsedFileTest_singleImport() { String program = "[#import somefile: C://somefile]\n" + "[todo: something]"; Parser<ParsedFile> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.graphParser()); List<AstImport> imports = Arrays.asList( new AstImport("C://somefile", "somefile")); List<AstNode> nodes = Arrays.asList( new AstTodoNode(null, "something") ); ParsedFile actual = sut.parse(program); assertEquals( imports, actual.getImports() ); assertEquals( nodes, actual.getAstNodes() ); } @Test public void parsedFileTest_doubleImport() { String program = "[#import somefile: C://somefile]\n" + "[#import someOtherFile: C://somefile2]\n" + "[todo: something]"; Parser<ParsedFile> sut = DecisionGraphTerminalParser.buildParser(DecisionGraphRuleParser.graphParser()); List<AstImport> imports = Arrays.asList( new AstImport("C://somefile", "somefile"), new AstImport("C://somefile2", "someOtherFile")); List<AstNode> nodes = Arrays.asList( new AstTodoNode(null, "something") ); ParsedFile actual = sut.parse(program); assertEquals( imports, actual.getImports() ); assertEquals( nodes, actual.getAstNodes() ); } }
Python
UTF-8
3,706
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- from colorthief import ColorThief from collections import Counter from colour import Color from colorthief import ColorThief import webbrowser import unirest import json import csv import urllib import urllib2, cookielib import os import sys import glob reload(sys) sys.setdefaultencoding('utf-8') colorsToSave = [] colorsBlackList = ['beige', 'white', 'black', 'gainsboro', 'Alabaster', 'smoke', 'gray', 'lavender', 'silver', 'ghost', 'snow'] def getColorsFromFile(filePath): fileInfo = ColorThief(filePath) dominantColor = fileInfo.get_color(quality=1) palette = fileInfo.get_palette(color_count=6) colorsFromFile = [] colorsFromFile.append('#%02x%02x%02x' % dominantColor) for i in palette: colorsFromFile.append('#%02x%02x%02x' % i) return colorsFromFile def colorIsAllowed(colorHex): for i in range(len(colorsBlackList)): if colorsBlackList[i].lower().replace(" ", "") in colorHex.lower().replace(" ", ""): return False return True def getRelevant(listValue, ignoreColor='#FFFFFF'): aux = [0, 0] for i in listValue: if (i != ignoreColor and listValue[i] > aux[1]): aux[0] = i aux[1] = listValue[i] return aux[0] def showColorInfo(colorHex, mode='json'): if mode == 'json': urlRequest = urllib.urlopen("http://www.thecolorapi.com/id?hex="+colorHex[1:7]+"&format=json") return json.loads(urlRequest.read().decode()) elif mode == 'html': webbrowser.open('http://www.color-hex.com/color/'+colorHex[1:7]) def getColor(stringToSearch, secondaryColor = False, showColorInfoHTML = False): print "\n\n==========================================================\n\n" print "Looking images for: "+stringToSearch directory = "download/"+stringToSearch # if not os.path.exists(directory): # exit fileList = [] for file in os.listdir(directory): fileList.append(directory + '/' + file) listColorHex = [] listColorName = [] print "\nChecking File and getting colors from:" for i in range(0, len(fileList)): print "\n%s (%s/%s) - %s" % (stringToSearch, i+1, len(fileList), fileList[i]) colors = getColorsFromFile(fileList[i]) if colors: for z in range(0, len(colors)): actualColor = showColorInfo(colors[z]) closestColorHEX = actualColor['name']['closest_named_hex'] closestColorName = actualColor['name']['value'] if colorIsAllowed(closestColorName.lower()): print ("-> " + colors[z] + ' - ' + closestColorName) listColorName.append(closestColorHEX) listColorHex.append(colors[z]) if z == 0: listColorName.append(closestColorHEX) listColorHex.append(colors[z]) listColorName.append(closestColorHEX) listColorHex.append(colors[z]) elif z == 1: listColorName.append(closestColorHEX) listColorHex.append(colors[z]) else: print "-> Bad Request (400)" print "" # if (listColorName and listColorHex): if listColorHex: colorName = Counter(listColorName) colorName = Color(getRelevant(colorName)) colorHex = Counter(listColorHex) colorHex = getRelevant(colorHex) if secondaryColor: sColorHex = getRelevant(Counter(listColorHex), ignoreColor=colorName) print "Color could be: \n-> %s and %s" % (colorName, sColorHex) if showColorInfoHTML: showColorInfo(colorHex, 'html') showColorInfo(sColorHex, 'html') return [colorHex, sColorHex] else: print "Color could be: \n-> %s" % (colorHex) if showColorInfoHTML: showColorInfo(colorHex, 'html') return colorHex getColor('Votorantim', True, True)
Java
UTF-8
2,980
2.40625
2
[]
no_license
package edu.utm.dao.cliente; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Named; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import edu.utm.bd.domain.Cliente; import edu.utm.bd.mappers.ClienteMapper; @Named public class ClienteDaoImpl implements ClienteDao { SqlSession sqlSession; @Autowired public void setSqlSession(SqlSession sqlSession){ this.sqlSession=sqlSession; } @Override public List<Cliente> findAllClientes() { List <Cliente> list=null; try{ ClienteMapper clienteMapper = sqlSession.getMapper(ClienteMapper.class); list=clienteMapper.findAllClientes(); for(Cliente c:list){ System.out.println("Id: "+c.getIdCliente()); System.out.println("Nombre: "+c.getNombre()); } return list; }catch(Exception e){ System.out.println("Error: "+ e); } return null; } @Override public Cliente findClienteByRFC(String rfc) { Cliente cliente=null; try{ ClienteMapper clienteMapper = sqlSession.getMapper(ClienteMapper.class); cliente= clienteMapper.findClienteByRFC(rfc); System.out.print("Cliente por RFC --"); System.out.print("Id: "+cliente.getIdCliente()); System.out.println("RFC: "+cliente.getRfc()); return cliente; }catch(Exception e){ System.out.println("Error: "+ e); } return null; } @Override public List<Cliente> findClienteByNombre(String nombre) { List <Cliente> list=null; try{ ClienteMapper clienteMapper = sqlSession.getMapper(ClienteMapper.class); list=clienteMapper.findClienteByNombre(nombre); for(Cliente c:list){ System.out.print("Cliente por Nombre --"); System.out.print("id: "+c.getIdCliente()); System.out.println("Nombre: "+c.getNombre()); } return list; }catch(Exception e){ System.out.println("Error: "+ e); } return null; } @Override public void updateCliente(Cliente cliente) { try{ ClienteMapper clienteMapper = sqlSession.getMapper(ClienteMapper.class); clienteMapper.updateCliente(cliente); } catch(Exception e){ System.out.println("Error: "+e); } } public void insertCliente(Cliente cliente) { try{ ClienteMapper clienteMapper = sqlSession.getMapper(ClienteMapper.class); clienteMapper.insertCliente(cliente); } catch(Exception e){ System.out.println("Error: "+e); } } public void deleteCliente(int id) { try{ ClienteMapper clienteMapper = sqlSession.getMapper(ClienteMapper.class); clienteMapper.deleteCliente(id); System.out.println("Cliente Eliminado: "+id); } catch(Exception e){ System.out.println("Error: "+e); FacesMessage msg = new FacesMessage("Error","Error al eliminar cliente "); FacesContext.getCurrentInstance().addMessage(null,msg); } } }
Markdown
UTF-8
417
2.5625
3
[ "MIT" ]
permissive
# hausaSentiment Sentiment Prediction of Hausa comments using Lexicon &amp; Machine Learning Twitter Dataset was first extracted and preprocessed! R programming was first used to create sentiment scores for comments, whereby negative comments have negative scored while positive comments have positive scores. Machine Learning was then used to train a model for prediction of both positive and negative comments.
PHP
UTF-8
379
2.71875
3
[]
no_license
<?php namespace App\Controllers; abstract class Controller { /** * @param array $vars * @return mixed */ protected function render(array $vars = []) { extract($vars); ob_start(); require(__DIR__ . "/../views/{$this->viewName()}.php"); return ob_get_clean(); } abstract public function viewName(): string; }
JavaScript
UTF-8
2,003
2.640625
3
[]
no_license
/* eslint-disable */ const common = {}; /* common.loadingObjects = {}; // 参数 id: 需要loading遮罩覆盖的元素 id ,body 元素直接传入body字符串即可 // 作用:会在 id所对应的元素/body 上添加loading效果 common.setLoading = (id = 'body') => { common.removeLoading(id); let ele, loadingStyles = 'ajax-async-loading'; if (id !== 'body') { // 局部 ele = document.getElementById(id); const computedStyle = getComputedStyle(ele, null); if (!computedStyle || !computedStyle.position || computedStyle.position != 'absolute') { ele.style.position = 'relative'; ele.style.height = '100%'; } loadingStyles += ' load-child'; // 效果处理 ele.style.webkitFilter = 'blur(1px)'; ele.style.filter = 'blur(1px)'; ele.style.opacity = '0.7'; } else { // 全局 ele = document.body; loadingStyles += ' loadingStyles'; // 删除其他所有 Object.keys(common.loadingObjects) .forEach((key) => { common.removeLoading(key); }); } const loadingEle = document.createElement('div'); loadingEle.setAttribute('class', loadingStyles); loadingEle.innerHTML = '<div class="ajax-async-spin-container">' + ' <p>' + ' <i class="fa fa-spinner fa-pulse fa-2x fa-fw margin-bottom ajax-async-spin"></i>' + ' </p>' + '</div>'; ele.appendChild(loadingEle); common.loadingObjects[id] = loadingEle; }; // 参数 id: 需要loading遮罩覆盖的元素 id ;body 为 'body' // 作用:删除 id所对应的元素/body上的loading效果 common.removeLoading = (id = 'body') => { if (common.loadingObjects[id]) { // 效果处理 const loadingObj = common.loadingObjects[id].parentNode; loadingObj.style.webkitFilter = ''; loadingObj.style.filter = ''; loadingObj.style.opacity = ''; common.loadingObjects[id].parentNode.removeChild(common.loadingObjects[id]); delete common.loadingObjects[id]; } }; */ export default common;
Python
UTF-8
3,096
2.5625
3
[]
no_license
import sys import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Circle po = 6.7e-7 e_0 = 8.85e-12 a = 5 # Grid of x, y points on a Cartesian grid nx, ny = 64, 64 XMAX, YMAX = 40, 40 x = np.linspace(-XMAX, XMAX, nx) y = np.linspace(-YMAX, YMAX, ny) X, Y = np.meshgrid(x, y) r, phi = np.hypot(X, Y), np.arctan2(Y, X) theta = [np.linspace(0,np.pi,nx) for x in range(0, nx)] multi = po/(4*np.pi*e_0*r**3) # Vectores unitarios ru = np.array([np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi),np.cos(theta)]) thetau = np.array([np.cos(theta)*np.cos(phi),np.cos(theta)*np.sin(phi),-np.sin(theta)]) norm = np.cos(theta)/np.cos(theta) phiu = np.array([-np.sin(phi)*norm,np.cos(phi)*norm,np.cos(theta)*0]) # Cartesian axis system with origin at the dipole (m) Theta = np.linspace(0,np.pi,100) #r = np.linspace(0.1,2*np.pi,200) def potencial(n): a1 = a a2 = -a1 V1 = np.abs(po/(4*np.pi*e_0)*r*np.cos(theta)/(r**2-a1*r*np.sin(theta)*np.sin(phi)+a1**2/4)**(3/2)) V2 = np.abs(po/(4*np.pi*e_0)*r*np.cos(theta)/(r**2-a2*r*np.sin(theta)*np.sin(phi)+a2**2/4)**(3/2)) fig = plt.figure() ax = fig.add_subplot(111) # Draw contours at values of Phi given by levels levels = np.array([10**pw for pw in np.linspace(0,5,20)]) levels = sorted(list(-levels) + list(levels)) # Monochrome plot of potential ax.contour(x, y, V1+V2,levels=levels, colors='k', linewidths=2) ax.set_title(r"Potencial--dipolos$^2$", fontsize=20) plt.show() #potencial(0) def CampoE(eje1,eje2): nombres = ["$x$","$y$","$z$"] rep1 = 4*r**2-4*a*r*np.sin(theta)*np.sin(phi)+a**2 Br1 = -po*np.cos(theta)*(2*a*r*np.sin(theta)*np.sin(phi)-8*r**2+a**2)/(2*np.pi*e_0*(rep1)**(5/2))*ru Btheta1 = -po/(2*np.pi*e_0)*((6*r*a*np.sin(phi)*np.cos(theta)**2-np.sin(theta)*(rep1))/(rep1)**(5/2))*thetau Bphi1 = (1/np.tan(theta))*po/(12*np.pi*e_0)*((r*a*np.sin(phi)*np.sin(theta)/rep1**(5/2)))*phiu # rep2 = np.abs(4*r**+4*a*r*np.sin(theta)*np.sin(phi)+a**2) Br2 = po*np.cos(theta)*(2*a*r*np.sin(theta)*np.sin(phi)+8*r**2-a**2)/(2*np.pi*e_0*(rep2)**(5/2))*ru Btheta2 = po/(2*np.pi*e_0)*((6*r*a*np.sin(phi)*np.cos(theta)**2+np.sin(theta)*(rep2))/(rep2)**(5/2))*thetau Bphi2 = (1/np.tan(theta))*po/(12*np.pi*e_0)*((r*a*np.sin(phi)*np.sin(theta)/rep2**(5/2)))*phiu fig, ax = plt.subplots() Hax = Br1[eje1]+Btheta1[eje1]+Bphi1[eje1]+Br2[eje1]+Btheta2[eje1]+Bphi2[eje1] Bax = Br1[eje2]+Btheta1[eje2]+Bphi1[eje2]+Br2[eje2]+Btheta2[eje2]+Bphi2[eje2] # Plot the streamlines with an appropriate colormap and arrow style color = 3* np.log2(np.hypot(Br1[2], Btheta1[1])) ax.streamplot(x, y, Hax, Bax, color=color, linewidth=1, cmap=plt.cm.inferno,density=2, arrowstyle='->', arrowsize=1.5) # Add a filled circle for the Earth; make sure it's on top of the streamlines. # ax.add_patch(Circle((0,0), RE, color='b', zorder=100)) ax.set_xlabel(nombres[eje1]) ax.set_ylabel(nombres[eje2]) ax.set_xlim(-XMAX, XMAX) ax.set_ylim(-YMAX, YMAX) ax.set_title ("Campo eléctrico dipolo") plt.show() CampoE(1,2)
Java
UTF-8
2,060
2.09375
2
[]
no_license
package pt.ua.easyCaching; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MenuUserActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.menu_user); Button mapButton = (Button) findViewById(R.id.map_button); Button cacheButton = (Button) findViewById(R.id.cache_button); Button statisticsButton = (Button) findViewById(R.id.statistics_button); Button competitionsButton = (Button) findViewById(R.id.competitions_button); Button twitterButton = (Button) findViewById(R.id.twitter_button); mapButton.setOnClickListener(this); cacheButton.setOnClickListener(this); statisticsButton.setOnClickListener(this); competitionsButton.setOnClickListener(this); twitterButton.setOnClickListener(this); } public void onClick(View v) { if(v.getId() == R.id.map_button) startActivity(new Intent(MenuUserActivity.this, Map.class)); else if(v.getId() == R.id.twitter_button) startActivity(new Intent(MenuUserActivity.this, TwitterActivity.class)); else if(v.getId() == R.id.cache_button) { Intent i = new Intent(MenuUserActivity.this, HideCacheActivity.class); i.putExtra("previous", "user"); startActivity(i); } else if(v.getId() == R.id.statistics_button) { SharedPreferences settings = getSharedPreferences("MYPREFS", 0); int userID = settings.getInt("userID", 0); Intent i = new Intent(MenuUserActivity.this,UserStatsActivity.class); i.putExtra("userID", userID); i.putExtra("competitionID", 1); startActivity(i); } else if(v.getId() == R.id.competitions_button) { Intent i = new Intent(MenuUserActivity.this, ViewCompetitionsActivity.class); i.putExtra("previous", "user"); startActivity(i); } } }
C#
GB18030
6,647
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Xml; namespace WWStock.App { public partial class SetupForm : Form { Dictionary<string, string> stockSH = new Dictionary<string, string>(); Dictionary<string, string> stockSHIndex = new Dictionary<string, string>(); Dictionary<string, string> stockSZ = new Dictionary<string, string>(); Dictionary<string, string> stockSZIndex = new Dictionary<string, string>(); Dictionary<string, string> stockUser = new Dictionary<string, string>(); public SetupForm() { InitializeComponent(); } private void btnCancel_Click(object sender, EventArgs e) { Close(); } private void btnOK_Click(object sender, EventArgs e) { // save selected list SaveUserData(Application.StartupPath + "\\StockUser.xml"); Close(); } private void SaveUserData(string strFileName) { XmlTextWriter w = new XmlTextWriter(strFileName, Encoding.Unicode); w.Formatting = Formatting.Indented; w.WriteStartDocument(); w.WriteStartElement("settings"); foreach (ListViewItem item in lvSelected.Items) { w.WriteStartElement("stock"); w.WriteElementString("code", item.SubItems[0].Text); w.WriteElementString("name", item.SubItems[1].Text); w.WriteEndElement(); } w.WriteEndElement(); w.WriteEndDocument(); w.Close(); } private void SetupForm_Load(object sender, EventArgs e) { // load stock info files LoadDataFile(); // populate category lvCategory.Items.Add(new ListViewItem("֤Ʊ")); lvCategory.Items.Add(new ListViewItem("֤Ʊ")); lvCategory.Items.Add(new ListViewItem("ָ֤")); lvCategory.Items.Add(new ListViewItem("ָ֤")); // populate stock list PopulateListView(stockSH, lvStock); // populate selected list PopulateListView(stockUser, lvSelected); } private void PopulateListView(Dictionary<string, string> dict, ListView lv) { foreach (KeyValuePair<string, string> pair in dict) { ListViewItem item = new ListViewItem(pair.Key); item.SubItems.Add(pair.Value); lv.Items.Add(item); } } private void LoadDataFile() { PopulateDictionary(Application.StartupPath + "\\StockSH.xml", stockSH); PopulateDictionary(Application.StartupPath + "\\StockSHIndex.xml", stockSHIndex); PopulateDictionary(Application.StartupPath + "\\StockSZ.xml", stockSZ); PopulateDictionary(Application.StartupPath + "\\StockSZIndex.xml", stockSZIndex); PopulateDictionary(Application.StartupPath + "\\StockUser.xml", stockUser); } private bool PopulateDictionary(string strFileName, Dictionary<string, string> dict) { try { dict.Clear(); string code = ""; string name = ""; XmlDocument doc = new XmlDocument(); doc.Load(strFileName); XmlNodeList nodes = doc.GetElementsByTagName("stock"); foreach (XmlNode node in nodes) { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name == "code") { code = childNode.InnerText; } if (childNode.Name == "name") { name = childNode.InnerText; } } dict.Add(code, name); } } catch (Exception) { return false; } return true; } private void lvCategory_SelectedIndexChanged(object sender, EventArgs e) { lvStock.Items.Clear(); if (lvCategory.SelectedItems.Count < 1) return; switch (lvCategory.SelectedItems[0].Index) { case 0: PopulateListView(stockSH, lvStock); break; case 1: PopulateListView(stockSZ, lvStock); break; case 2: PopulateListView(stockSHIndex, lvStock); break; case 3: PopulateListView(stockSZIndex, lvStock); break; default: break; } } private void lvStock_DoubleClick(object sender, EventArgs e) { if (!CheckExistence(lvStock.SelectedItems[0], lvSelected)) { lvSelected.Items.Add((ListViewItem)lvStock.SelectedItems[0].Clone()); } } private void lvSelected_DoubleClick(object sender, EventArgs e) { lvSelected.Items.Remove(lvSelected.SelectedItems[0]); } private void btnAdd_Click(object sender, EventArgs e) { foreach (ListViewItem item in lvStock.SelectedItems) { if (!CheckExistence(item, lvSelected)) { lvSelected.Items.Add((ListViewItem)item.Clone()); } } } private void btnRemove_Click(object sender, EventArgs e) { foreach (ListViewItem item in lvSelected.SelectedItems) { lvSelected.Items.Remove(item); } } private void btnReset_Click(object sender, EventArgs e) { lvSelected.Items.Clear(); } private void btnMoveUp_Click(object sender, EventArgs e) { } private void btnMoveDown_Click(object sender, EventArgs e) { } private bool CheckExistence(ListViewItem lvi, ListView lv) { foreach (ListViewItem item in lv.Items) { if (item.Text.CompareTo(lvi.Text) == 0) { return true; } } return false; } } }
Markdown
UTF-8
5,042
3.078125
3
[]
no_license
# Insert / Select ## 데이터 삽입 : INSERT - INSERT INTO 테이블명 [(속성 리스트)] VALUES (속성의 값 리스트); DB에서는 작은 따옴표를 무조건 써야 한다 ```mysql INSERT INTO 부서 (부서번호, 부서이름) VALUES (1, '홍보부'); ``` ```mysql INSERT INTO MEMBER (NUM, NAME, EMAIL, PHONE) VALUES (1, 'A', 'aaa@gmail.com', '010-0001'); INSERT INTO MEMBER (NAME, EMAIL, NUM, PHONE) VALUES ('B', 'bbb@gmail.com', 2, '010-0002'); INSERT INTO MEMBER (NUM, NAME, EMAIL, PHONE) VALUES (3, 'C', 'ccc@gmail.com', '010-0003'); INSERT INTO MEMBER (NAME, NUM) VALUES ('D', 4); ``` ![image-20200120134718687](database03insert_select.assets/image-20200120134718687.png) 기본키 지정이 되어 있기 때문에 중복 데이터가 들어가려 하면 에러가 뜬다 ## 데이터 조회 : SELECT > SELECT [DISTINCT] 속성 리스트 FROM 테이블 리스트 - 속성 리스트 나열하기 귀찮으면 *로 대체 가능 - `SELECT * FROM 고객;` - `DESC 고객;` - 속성 리스트를 확인 ### 1. 중복데이터 걸러내기 : DISTINCT 중복데이터를 걸러내고 하나씩 데이터를 출력하려면 DISTINCT를 활용한다 ```mysql SELECT DISTINCT (제조업체) FROM 제품; SELECT DISTINCT 제조업체, 제품명 FROM 제품; ``` ### 2. 속성명 변경 출력 : AS - SELECT 속성명 [AS] 변경속성 FROM 테이블 - 테이블이 가진 기존 속성명을 지정한 속성명으로 변경하여 출력 가능 - [AS] 생략하고 띄어쓰기로 구분해도 가능 - ```mysql SELECT 제품명, 단가 AS '가격' FROM 제품; SELECT DISTINCT DNAME AS '부서명', LOC AS '부서위치' FROM DEPT; ``` ### 3. 산술식 이용하기 - ```mysql SELECT 제품명, 단가, 단가+500 AS 조정단가 FROM 제품; SELECT SAL*1.1 AS '급여인상', SAL * 12 + IFNULL(COMM, 0) AS '연봉' FROM EMP; # IFNULL 함수 맛보기 ``` - ![image-20200120154807424](database03insert_select.assets/image-20200120154807424.png) ### 4. 조건에 해당하는 데이터 검색 : WHERE - SELECT [DISTINCT] 속성 리스트 FROM 테이블 리스트 [WHERE 조건]; - SELECT에는 WHERE이 필수적으로 따라온다고 생각할 정도로 많이 사용 - 데이터베이스에서 `=`은 대입이 아닌 같다는 것을 의미한다 ```mysql SELECT 제품명, 재고량, 단가 FROM 제품 WHERE 제조업체 = '한빛제과'; # 제조업체가 한빛제과인 제품을 출력하겠다 SELECT * FROM 주문 WHERE 수량 >= 30 AND 배송지 = '강원도 춘천시'; ``` - BETWEEN 을 통해 범위를 지정해 주는 것도 가능하다 ```mysql SELECT 제품명, 단가, 제조업체 FROM 제품 WHERE 단가 BETWEEN 2000 AND 3000; ``` - 괄호로 묶어주는 것도 가능 ```mysql SELECT * FROM EMP WHERE (MGR = 7698 OR MGR = 7839) AND DEPTNO = 10; ``` - 괄호가 없는 경우 OR을 기준으로 앞 뒤로 분리가 되기 때문에 결과가 다르게 나타난다 ### 5. 부분적으로 일치하는 데이터 검색 : LIKE - 데이터를 검색 할 때 LIKE는 필수다. 이거 안쓰면 정규식의 MATCH와 같은 기능밖에 하지 못한다. - `%` : 뭐가 오든 아무것도 오지 않든 상관없다는 의미. 정규식의 *과 비슷. - `_` : 언더스코어를 쓰면 이 개수 만큼의 문자 길이의 문자열 검색 - ```mysql #직업이 세글자 , 아이디에 A포함하는 사람 찾기 SELECT * FROM 고객 WHERE 직업 LIKE '___' AND 고객아이디 LIKE '%a%' #사원명의 2번째 글자에 'I'가 있는 사원명과 급여 검색 SELECT ENAME, SAL FROM EMP WHERE ENAME LIKE '_I%'; ``` ### 6. NULL 데이터 검색 : IS NULL / IS NOT NULL - NULL은 실행 명령을 자꾸 무시해버리기 때문에 제어해줘야 하는데 이때 `=` 기호를 사용하면 안된다. `IS`를 써야 함. ```mysql SELECT * FROM 고객 WHERE 나이 IS NULL; SELECT * FROM 고객 WHERE 나이 IS NOT NULL; ``` - LIKE와 함께 활용 ```mysql SELECT * FROM EMP WHERE COMM IS NOT NULL AND HIREDATE LIKE '1981-02%'; ``` - 2월 이후 입사 한 사람을 찾기 위해서는 `HIREDATE > '1981-02';`라고 활용도 가능하다 ### 7. 데이터 검색 후 정렬 : ORDER BY > SELECT [DISTINCT] 속성 리스트 FROM 테이블 [WHERE 조건] [ORDER BY 속성 리스트 [ASC | DESC]]; - 데이터베이스는 데이터의 순서를 정하지 않는다. 이 때 우리가 원하는 순서로 지정하고 싶을 때 OREDER BY를 활용 - 오름차순 : ASC, 내림차순 : DESC ```mysql SELECT 주문고객, 주문제품, 수량, 주문일자 FROM 주문 WHERE 수량 >= 10 ORDER BY 주문제품 ASC, 수량 DESC; ``` - 오름차순 - ### 8. 출력 개수 제한 : LIMIT - ```mysql SELECT * FROM EMP LIMIT 0, 5; --INDEX 0번 부터 ~ 5개를 출력한다는 의미 ``` - SELECT 순서 체크 ```mysql SELECT * FROM EMP WHERE DEPTNO = 30 ORDER BY SAL DESC LIMIT 0, 5; SELECT * FROM EMP WHERE DEPTNO = 30 ORDER BY SAL DESC LIMIT 5, 5; ```
Java
UTF-8
2,318
1.835938
2
[]
no_license
package com.arkainfoteck.dabagalli.activitys; import android.database.Cursor; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.arkainfoteck.dabagalli.R; import com.arkainfoteck.dabagalli.adopters.FoodAdopter; import com.arkainfoteck.dabagalli.adopters.SliderUtils; import com.arkainfoteck.dabagalli.adopters.ViewPagerAdapter; import com.arkainfoteck.dabagalli.models.FoodModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; public class SaveData extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_save_data); } public void reda(){ RequestQueue rq = Volley.newRequestQueue(SaveData.this); StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://dabbagalli.com/index.php/api/get_food_catgeres", new Response.Listener<String>() { public void onResponse(String response) { try { JSONArray jsonObject = new JSONArray(response); } catch (JSONException e) { e.printStackTrace(); } } ; }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { // TODO Auto-generated method stub // pd.hide(); } }) { @Override public Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); return params; } }; rq.add(stringRequest); } }
Java
UTF-8
758
2.125
2
[]
no_license
package com.devon.demo.springaoppractice; import com.devon.demo.pojointercept.Login; import com.devon.demo.pojointercept.LoginFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringAopPracticeApplicationTests { @Autowired private Service service; @Test public void shouldApplyCustomAnnotation() throws InterruptedException { service.serve(); } @Test public void pojoInterceptTest(){ Login login = LoginFactory.createLogin(); login.login("user", "secret"); //login.logout(); } }
JavaScript
UTF-8
287
2.515625
3
[]
no_license
import React from "react"; function Joke(props) { let question = props.joke.question; if (question == null) { question = "Default"; } return ( <div> Question: {question} <br /> PunchLine: {props.joke.punchLine} </div> ); } export default Joke;
PHP
UTF-8
2,390
2.828125
3
[]
no_license
<?php namespace pandaac\OAuth2OtLand\Providers; use Psr\Http\Message\ResponseInterface; use pandaac\OAuth2OtLand\Entities\User; use League\OAuth2\Client\Token\AccessToken; use League\OAuth2\Client\Provider\AbstractProvider; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; class OtLand extends AbstractProvider { /** * Holds the API base URL. * * @var string */ protected $baseUrl = 'https://otland.net/api'; /** * Returns the base URL for authorizing a client. * * Eg. https://oauth.service.com/authorize * * @return string */ public function getBaseAuthorizationUrl() { return sprintf('%s/oauth/authorize', $this->baseUrl); } /** * Returns the base URL for requesting an access token. * * Eg. https://oauth.service.com/token * * @param array $params * @return string */ public function getBaseAccessTokenUrl(array $params) { return sprintf('%s/oauth/token', $this->baseUrl); } /** * Returns the URL for requesting the resource owner's details. * * @param AccessToken $token * @return string */ public function getResourceOwnerDetailsUrl(AccessToken $token) { return sprintf('%s/users/me?oauth_token=%s', $this->baseUrl, $token->getToken()); } /** * Returns the default scopes used by this provider. * * This should only be the scopes that are required to request the details * of the resource owner, rather than all the available scopes. * * @return array */ protected function getDefaultScopes() { return ['read']; } /** * Checks a provider response for errors. * * @throws IdentityProviderException * @param ResponseInterface $response * @param array|string $data Parsed response data * @return void */ protected function checkResponse(ResponseInterface $response, $data) { // ... } /** * Generates a resource owner object from a successful resource owner * details request. * * @param array $response * @param AccessToken $token * @return ResourceOwnerInterface */ protected function createResourceOwner(array $response, AccessToken $token) { return new User((array) $response); } }
Java
UTF-8
2,270
3.1875
3
[]
no_license
package org.chandra.zebra.interview.bowling.game.validation; import org.chandra.zebra.interview.bowling.game.exceptions.InvalidInputDataException; import java.util.List; import java.util.function.Predicate; import java.util.logging.Logger; import static org.chandra.zebra.interview.bowling.game.constants.Constants.*; /** * The class that implements the Input Validator interface and defines the methods to validate the input data. */ public class InputValidatorImpl implements InputValidator { private static final Logger LOGGER = Logger.getLogger(InputValidatorImpl.class.getName()); /** * A Predicate Functional interface to check if the pins bowled value in the input is valid. */ Predicate<String> validPinsBowled = x-> x.equals(FOUL) || Integer.parseInt(x) >= 0 || Integer.parseInt(x) <= 10; /** * Validates the input scores and throws and exception if any score is found invalid * * @param scores the scores */ @Override public void validateInputScores(List<String[]> scores) { if(scores.size() <10) { throw new InvalidInputDataException(BAD_DATA_LESS_LINES + " The current file has only "+ scores.size() + " lines."); }else{ scores.stream().forEach(x-> validateEachScore(x)); } } /** * Validates the data in each line and throws and exception if any data is found invalid * * @param data the data of each line */ private void validateEachScore(String[] data) { if(data.length != 2) { throw new InvalidInputDataException(MISSING_ATTRIBUTES); }else { validatePinsBowled(data[1]); } } /** * Validates the pins bowled in each line and throws and exception if any value is found invalid * * @param pinsBowled the pins bowled values of each line */ private void validatePinsBowled(String pinsBowled) { try { if (!validPinsBowled.test(pinsBowled)){ throw new InvalidInputDataException(BAD_DATA_PINS_BOWLED); } }catch (NumberFormatException e){ LOGGER.severe(e.getMessage()); throw new InvalidInputDataException(BAD_DATA_PINS_BOWLED); } } }
C++
UTF-8
2,614
3.0625
3
[]
no_license
#pragma once #include <memory> #include <atomic> #define MMAP_ALLOCATOR 0 class MemoryCounter { public: typedef std::size_t size_type; MemoryCounter(size_type limit) : bytes_allocated(0), limit_(limit) {} void allocate(size_type delta) { auto result = (bytes_allocated += delta); if(result > limit_) { deallocate(delta); throw std::bad_alloc(); } } void deallocate(size_type delta) { bytes_allocated -= delta; } size_type capacity() const { return limit_ - bytes_allocated; } void limit(size_type l) { // Must not be called in a multithreaded context. if(l<bytes_allocated) throw std::bad_alloc(); limit_ = l; } size_type limit() const { return limit_; } size_type size() const { return bytes_allocated; } private: // Invariant: 0<=bytes_allocated<=limit std::atomic<std::size_t> bytes_allocated; size_type limit_; }; template<typename T> class CountedAllocator { public: CountedAllocator(MemoryCounter &mc) : counter(mc) {} // Construct from another allocator template<class O> CountedAllocator(const CountedAllocator<O>&o) : counter(o.counter), alloc(o.alloc) { } typedef T value_type; typedef const T *const_pointer; typedef T *pointer; typedef const T &const_reference; typedef T &reference; typedef typename std::allocator<T>::difference_type difference_type; typedef typename std::allocator<T>::size_type size_type; pointer allocate(size_type n) { counter.allocate(n * sizeof(T)); try { return alloc.allocate(n); } catch(...) { counter.deallocate(n * sizeof(T)); throw; } } void deallocate(pointer p, size_type count) { alloc.deallocate(p, count); counter.deallocate(count * sizeof(T)); } size_type max_size() const { return counter.capacity()/sizeof(T); } template<class Other> struct rebind { typedef CountedAllocator<Other> other; }; MemoryCounter & counter; std::allocator<T> alloc; bool operator!=(const CountedAllocator & other) const { return &counter != &other.counter; } }; #if MMAP_ALLOCATOR #include "persist.h" #define PERSIST_ALLOCATOR persist::fast_allocator using AllocatorData = persist::shared_memory; #else using AllocatorData = MemoryCounter; #define PERSIST_ALLOCATOR CountedAllocator #endif
Java
UTF-8
162
1.945313
2
[]
no_license
package com.company; public class Pantalon extends Prenda{ public Pantalon(String marca, String modelo) { super(marca, modelo); } }
C
ISO-8859-1
503
3.609375
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { //Faa um algoritmo para calcular o volume de uma esfera de raio R, // em que R um valor fornecido pelo usurio. float raio,volume; printf("Digite o raio da esfera: "); scanf("%f",&raio); volume= 4 * 3.14 *pow(raio,3) /3; printf("O volume total do cilindro eh:%.2f",volume); return 0; }
Java
UTF-8
974
3.9375
4
[]
no_license
package com.corejava; public class March11_Loops { public static void main(String[] args) { checkPrime(); } public static void checkEvenOrOdd() { int num = 48; if( num % 2 == 0) { System.out.println("The number is Even "); } else { System.out.println("The number is odd"); } } public static void checkEven1To100() { int num = 1; while ( num < 100) { if( num % 2 == 0) { System.out.println("The number "+num+" is Even"); } num++; } } public static void checkPrime() { int num = 49; int x = 2; boolean isPrime = false; while ( x < num) { if( num % x == 0) { isPrime = false; break; } else { isPrime = true; } x++; } if ( isPrime ) { System.out.println("The number is prime"); } else { System.out.println("The number is not prime"); } } }
C++
UTF-8
803
3.265625
3
[]
no_license
// // 2-2part4.cpp // HW2 // // Created by Rukmaiah Bhupalam on 1/19/13. // Copyright (c) 2013 Nihar Bhupalam. All rights reserved. // #include <iostream> #include <algorithm> #include <vector> using namespace std; template <class myType> myType findMedian(vector<myType> vec){ int size=vec.size(); if(size%2 !=0){ nth_element (vec.begin(), vec.begin()+(size-1)/2, vec.end()); return vec[(size-1)/2]; } else{ nth_element (vec.begin(), vec.begin()+(size-1)/2, vec.end()); myType first=vec[(size-1)/2]; nth_element (vec.begin(), vec.begin()+(size-1)/2+1, vec.end()); myType second=vec[(size-1)/2+1]; return (first+second)/2; } } int main(){ vector<double> myvector={1, 3, -1, 7, 4, 5,22, 33}; cout<<findMedian(myvector)<<endl; }
Markdown
UTF-8
20,534
2.625
3
[]
no_license
# React Course Progress of the course React Hooks, and redux context **Summary Of course:** I am Gabriel Jiménez a cybersecurity student and I love programming, so I started to learn Javascript, to be able to develop projects and web applications, and I decided to create this summary to rethink the concepts, if you really want to learn and understand the most demanding language in the world, go to link of the repository and adquire this magnificent course. Let's go! ## Table of Contents - [What is React or Reactjs?](#what-is-react-or-reactjs) - [What is a Component?](#components) - [Javascript Essential](#javascript-essential) # What is React or Reactjs Is a library of Javascript, to create user interfaces, react work in Front-end, to create Webs apps. React is development for Facebook. The heart of React are Components. # Components You can divide your code in components. # From Reacjs.org # Components Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM. # Reactive React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable and easier to debug. # Who use React? Udemy.com | Platzi.com | Asana.com | Facebook.com | Twitter | Instagram | Microsoft | Outlook | Spotfy| Twitter | Dropbox # Javascript Essential - Var let and Const - Scope in Javascript - Template Strings in Javascript - Function and other types of function - Function with parameters - Arrow Functions - Object in Javascript - Object Literal - Object Constructor - Prototypes - Object DEstructuring - Object literal Enhacemnt - Function in a Object - Arrays/.map and Object.keys - Spread Operator - Arrays methods .Filter/.find/.reduce - Promise - Promise with AJAX - Class - Module ES6 # Introduction a webpack **Webpack** is a bundler of modules for apps modern Javascript. With webpack you can incorporate dependencies such as css files, javsacript modules, other javascript libraries in your project, you will also have a local server with live reload. In addtion to transpiling your modern javascript code to previous versions of javascript for greater compatibility with BABEL. ![webpack](https://github.com/g4brieljs/React-course/blob/master/02-Webpack/webpack.png) **Etry** un punto de entrada que especifica que módulo debe utilizar webpack para comenzar a crear la gráfica de dependencias, webpack se encargará de saber que dependencias tiene este módulo. Por lo normal el punto de entrada y la configuración se guardan en un archivo, aunque ne la versión 4 ya no es nesesario. **Outpu** la salida le dirá webpack, en que parte debe almacenar el bundle que se ha creado. Normalmente la entrada esta en una carpeta llamada src / y la salida a una carpeta llamada dist/ **Loaders** webpack solo entiende arcvhivos javascript, pero con lo loaders puedes cargar otros formatos como sass, less, imagenes, html. importar archivos css es algo que gulp o grunt no pueden hacer y que le da mucho mayor pode r awebpack sobre estas herramientas. **test** que le dice al archivo webpack que archivo debe ser transformados. **use** que le dice al archivo webpack que loader estamos utilizando para este archivo. **plugins** LOs loaders nos permiten utilizar distinto tipos de módulos y otros formatos. pero los plugins realizan otro tipo de tareas tales como optimizar el bundle, administración avanzada de los assets. Un plugin se instala via NPM y se importa al archivo webpack con la palabra require(); **Package JSON** con este file you can share you dependencies with other programer. `npm init` **Install dependencies** `npm instal webpack --save-dev` **--save-dev** es para que se almacenar en tu package.JSON # First bundle ```javascript const path = require('path'); // entry / output / loaders / module.exports = { // entradas entry: './src/index.js', // salidas output: { // crea el archivo filename: 'bundle.js', // crea la carpeta path: path.join(__dirname, '/dist') } } ``` `node_modules\.bin\webpack src\index.js` # Create a script on Webpack ``` javascript "scripts": { "build" : "webpack --mode development" }, ``` # transpillar the code with babel `$ sudo npm install --save-dev babel-core babel-loader babel-preset-env` `$ sudo npm install -D babel-loader @babel/core @babel/preset-env` ```javascript // loaders module: { //tests rules: [ { test: /\.js$/, //excludes esto escluira la carpeta node_modules exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/env'] } } } ] } ``` # watch in Webpack `"watch": "webpack --w --mode development"` # Import css on Webpack Install these dependencies: -`npm instal --save-dev style-loader css-loader` ```javascript // other rule { // esto busca css y le aplica el loader test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' } ] } ``` `import '.../css/style.css';` // Esto improta la hoja de estilo dentro del modulo, esto no se puede con js vanilla, se necesita webpack y los modulos necesarios # Import sass with webpack `npm install --save-dev sass-loader` `npm install -g node-sass` `npm install --save-dev node-sass` ```javascript // other rule { // esto busca css y le aplica el loader test: /\.scss$/, use: [ {loader: 'style-loader'}, {loader: 'css-loader'}, {loader: 'sass-loader'} ] } ``` # Create multiple bundles ```javascript // entradas entry: { index: './src/js/index.js', aboutUs: './src/js/aboutUs.js' }, // salidas output: { // crea el archivo filename: '[name].bundle.js', // crea la carpeta path: path.join(__dirname, '/dist') }, ``` # Add common chunks The common chunks, permiten que las librerias, o frameworks que agreguemos a nuestro webpack se vayan al common bundle, es como el archivo central, entonces los otros .js bundle seran para los codigos que generan cada archivo ```javascript // common Chunks optimization: { splitChunks: { cacheGroups: { // commons: { // que archivos vamos a utilizar // todo lo que este en node modules // esto es una expresion regular para que todo el codigo necesario entre al bundle, en este caso webpack test: /[\\/]node_modules[\\/]/, // el nombre name: 'common', // que todo se guarde en el archivo de common chunks: 'all' } } } } ``` # add webpack dev server `npm install --save-dev webpack-dev-server` ```javascript // web dev server devServer: { // esto son parametros exclusivos de web dev server // El primero es la carpeta donde se van a cargar la carpeta dist contentBase: path.join(__dirname, 'dist'), compress: true, // the port port: 9000 }, ``` # First project with webpack ![firstWebpack](https://github.com/g4brieljs/React-course/blob/master/02-Webpack/firstproject.png) # Install plugin This plugin va a generar los archivos html y se complementa con el webpack dev server `npm install --save-dev html-webpack-plugin` ```javascript const HtmlWebpackPlugin = require("html-webpack-plugin"); plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.html' }) ] ``` # React Essentials **Install React-app** you need: -Nodejs -NPM Acces a carpet in with cmd or terminal write -`$ npm install -g create-react-app` -`$ create-react-app myapp` If you have a error, you can use -`npm install` ## React without JSX ```javascript import React from 'react'; function App() { return ( React.createElement( 'h1', {id: 'heading', className: 'heading'}, 'Hola mundo' ) ); } export default App; ``` ## React with JSX ```javascript import React, {Fragment} from 'react'; function App() { //ADD CODE JAVASCRIPT const client ={ name: 'Gabriel Jimenez', work: 'Web developer' } return ( <Fragment> <h1>{client.name}</h1> <p>{client.work}</p> </Fragment> ); } export default App; ``` ## What is Component in REACT? **Component** te van a permitir serpar tu código y los elementos de tu interfaz en pequeñas piezas re-utilizables que estarán asoladas una de otras. - Los componentes son como funciones en Javascript - Puedes pasarle datos a un componente por medio de algo llamado Props. - **Importante** es que en React los datos fluyen del componente padre al hijo. ## Two components / Hooks ### Class component ```javascript class App extends Component{ render(){ return( <p>Hellow World</p> ) } } ``` ### Functional component ``` const App = props => ( <p>Hellow World</p> ); ``` **Ventajas** - Fácil de crear, leer - Menos código - Fácil de probar - "Mejor performance" **Desventajas** - No se puede usar los ciclos de vidas (ComponentDidMount, ComponentDidUpdate) - No tienen state - No puedes usar refs - Si necesitan caulquiera de estas 3, crear un class Component ### Hooks Te permite usar State con function ## First Class Component **render** es obligatorio en los class Component **{ Component }** esto permite no utilizar esto: `extends React.Component` ```javascript import React, { Component } from 'react'; class FirstComponent extends Component { state = { } render(){ return ( <div> <h1>First Component</h1> </div> ); } } export default FirstComponent; ``` ## Converting Class Component in a Stateless Functional Component ```javascript // Use this form for create components Parents function SecondComponent(){ return ( <h1>First Component</h1> ); } // For create Methods const SonSecond = () => ( <h1>Son</h1> ); ``` ## Props in you component **Props** nos permiten pasar datos entre componentes. - Un prop se pasan del padre al hijo, nuca del hijo al padre. **Pasar String** `name = "Juan"` **Pasar a var** `date = {var}` ## State in you Component Un **estado** es parecido a los props, pero son privados y se controla totalmente por el componente. **Importante** los State siempre debe ser un objeto cuando se utilizan los class component. ```javascript state = { products : [ { id: 1, name: 'Camisa ReactJS', precio: 30 }, { id: 2, name: 'Camisa VueJS', precio: 30 }, { id: 3, name: 'Camisa AngularJS', precio: 30 }, ] } ``` **Other form** ```js constructor(){ super(){ this.state = { products : [ { id: 1, name: 'Camisa ReactJS', precio: 30 }, { id: 2, name: 'Camisa VueJS', precio: 30 }, { id: 3, name: 'Camisa AngularJS', precio: 30 }, ] } } ``` ## Lifecycle Methods to a Class component Son methods or functions que se ejecutan automaticamente en el componente. **Mala práctica** Es mala práctica llamarlos. - Se actualizan automaticamente - Solo existen en el Class component - Son eventos que ocurren desde que le componente es creado hasta que es destruido. ### ComponentDidMount Cuando se termina de cargar el componente. ```js class App extends Component { componentDidMount(){ console.log('El documento esta listo'); } render(){ return( <p>Hola mundo</p> ) } } ``` **APIS** las APIS se llamán desde el componentDidMount. ### ComponentWillMount El componente se cargará, pero aún no esta listo, este se usa para cargar algo antes de que se monte le Componente. ```js class App extends Component { componentWillMount(){ console.log('El documento aun no esta listo'); } render(){ return( <p>Hola mundo</p> ) } } ``` ### ComponentDidUpdate Cuando algo cambia en el componente lo actualiamos con este método de ciclo de vida. ```js class App extends Component { componentDidUpdate(){ console.log('Algo cambio en el componente'); } render(){ return( <p>Hola mundo</p> ) } } ``` **Car shop** por ejemplo añadimos un producto al carrito de compras, necesitamos actualizar. ### ComponentWillUnmount Te permite hacer algo antes de que se reemplaze un componente viejo por uno nuevo. ```js class App extends Component { componentWillUnmount(){ console.log('Un nuevo componente ha sido cargado y este será reemplazado, pero puedes ejecutar algo antes de que eso pase'); } render(){ return( <p>Hola mundo</p> ) } } ``` **Importante** Los componentes del ciclo de vida tienen este orden: **Primero** ```js - componenteWillMount(){} ``` **Segundo** ```js - render() ``` **Tercero** ```js - componentDidMount(){} ``` **Actualizas el componente** ```js - componentDidUpdate(){} ``` Y luego el render() para visualizar los cambios. **Importante** Un state son inmutables, se cambian con el `this.setState({})` en los class Component. # First project with Reactjs ![firstreact](https://github.com/g4brieljs/React-course/blob/master/04-first-project/quotes-lending/quote.png) ## Development of project: **Importante** en React para leer datos de los formularios debemos utilizar los métodos que trae React como: - onChange - onClick etc **Importante** también hay otra manera que son los res. More (https://es.reactjs.org/docs/forms.html) **Cambiar los estados** tenemeos dos formas, la no recomendada y la recomendada: - No se recomienda de esta manera ```js this.state.cantidad = e.target.value; ``` Recomendada ```js this.setState({ [name] : value }) ``` Algo importante, es que si agregamos {} (llaves) en nuestro componente, sea class o function, será código Javascript, me recuerda mucho a php, que si agregas `<?php echo="Hola, mundo" ?>` adentro del HTML podrás hacer más dinamico tu sitio web. Algo para tomar en cuenta De esta manera esperamos que se carguen los datos, hasta que el user le de Submit, envia los datos. ```js <form onSubmit={this.metodo}> ``` Y de esta manera se ejecuta de manera inmediata. ```js <input disabled={this.metodo()}> ``` El state es lo que nos permite crear una app interactiva. Un evento en el form `onSubmit` **¿Cómo enviar datos de un componente a otro?** Tenmos varias opciones: - Props - Contex - Redux: Es bueno, pero si tienes muchas fuentes de datos, props es la más cómodas. ## Props Siempre envías Props desde el componente Padre hacia el componente más pequeño. Un prop consiste en dos partes: - Primero su identificador - El nombre la funcion, o los datos que pasaras, variables, datos del state, etc. ```js // primero pass el metodo del padre method = () =>{ console.log('hello, this is parent component'); } ``` ```js // Luego pasamos el este metodo al componente hijo <Component method = {this.method} /> ``` ```js // Luego en nuestro componente pasamos esa prop al metodo del componente que querramos renderizar en el HTML this.props.method(); ``` ## Helper function Se usan para no crear componentes muy grandes, se recomienda siempre hacerlos pequños. Su fin también es que sean re-utilizados. Creas un helper, puede ser una function que haga alguna operación, y la exportas a tu app, luego con destruturing pasas esa funcion a tu componente principal, donde esta tu prop, que en mi caso es donde lo necesito. ## Object literal Enhacement para agregar al State **Importante** React ```js datosPrestamos = (cantidad, plazo) => { const total = calcularTotal(cantidad, plazo); // Agregar al state, el total, con sus argumentos this.setState({ // La nueva vs de js, el object literal Enhacement total, cantidad, plazo }); } ``` ## Stateless functional component Diferencias entre Class y Stateless funtional Class component heredan Component, el Stateless functional no. En los Stateless funcitional no se usa this.props, se usa props directamente. Los Stateless functional Component no usan State, esto es lo más obvio. Y támpoco tienen el ciclo de vida. ¿Cuáles son las ventajas? Son más faciles de mantener. **Cómo pasar props** `const Component = (props) => {console.log(props);}` ## Cargar componentes condicionalmente Ejemplo: Una navegacion para un user autenticado y uno para el que no lo este. Autenticado = Accede al dashboard. NoAutenticado = Login / Register ```js // creas una variable que guardara los componentes let component; // Creamos la condicion if(user === 'Autenticado'){ componente = <Dashboard />; }else if{ component = <LoginRegister />; } // Imprimimos nuestra variable en nuestro render(); render( <div> <h1>Pagina web</h1> {component} </div> ) ``` # Finish from First project with Reactjs ---------------------------------------------- # Second project with Reactjs - Reading forms with react ![firstreact](https://github.com/g4brieljs/React-course/blob/master/05-second-project/citas.png) Tenemos varias opciones, la más fácil podría ser la siguiente, pero cada persona tiene su manera de programar. React cuenta con los siguientes eventos, los cueales comienzan con `on`, los utilizados en este proyecto son los siguientes: - onChange - onSubmit With a arrow function we can to wait what be activated ```js onClick={() => evento(parametros)} ``` Los spread operators, nos permiten duplicar los arreglos, en estos casos en los states ```js ...state ``` **Importante** Nunca se le debe hacer cambios directamente al state, siempre que se modifique es bueno hacerle una copia. **Importante** Si quieres pasar algo que tienen los props, de un componente a otro, tienes que pasar por cada uno de ellos, esto se soluciona con algo que se conoce como **context**. ## Methods of cycle of life in Reactjs **componentDidMount** Una vez el componente es completado se ejecutará el evento que tengamos. **componentDidUpdate** Si hay algún cambio este se ejecutará. ## Arrays Methods **Filter** Este Array Methods nos permite seleccionar un objeto del arreglo y devolvernos el mismo o todos los que sean iguales, y si comparas con un negativo te devolverá todos los que sea difeferentes al selccionado. ## LocalStorage and JSON.stringify / JSON.parse **JSON.stringify** esta propiedad de javascript los que nos permite es transformar un arreglo o objeto a un String, es decir a una cadena de texto. **JSON.parse** este lo que nos permite es transformar una cadena de texto (string) y los covierte en un array o un objeto JSON. ## App Documentation with PropTypes in reactjs PropTypes nos permite definir que tipo de datos esperan los componentes o props, y si son requeridos o no. ```js Component.propTypes = { props : PropTypes.string.isRequired } ``` # Finish from Second project with Reactjs ---------------------------------------------- # Third project with Reactjs - Apis and Search | NewsApi.org ![Thirdreact](https://github.com/g4brieljs/React-course/blob/master/06-third-project/search.png) ## Project with APi NewsApi Al consumir una API se utiliza el Ciclo de vide `componentDidMount(){}` Para extraer los datos podemos utilizar: - Axios - Fetch - Async Await Example with Async Await ```js async componentDidMount(){ const url = `https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=ApiKey`; const res = await fetch(url); const data = await res.json(); console.log(data); } ``` You can create a method para utilizarlo en el componentDidMount
PHP
UTF-8
3,112
2.890625
3
[]
no_license
<?php namespace Services; class SessionHandler{ public function __construct() { $this->buildSession(); } public function __get($key){ if(property_exists($this,$key)){ $return = $this->$key; return $return['value']; } else{ return null; } } public function __set($key,$value){ $this->{$key} = $value; return $this; } public function setSession($key,$value,$time = 900){ if(isset($this) && is_object($this)) { $this->{$key} = ['time'=>$time,'value'=>$value]; return $this->save(); } return self::init()->setSession($key,$value,$time); } public function getSession($key) { return self::init()->__get($key); } public function deleteSession($key) { if(isset($this) && is_object($this)) { if (isset($_COOKIE[$key])) { setcookie($key,null,time() - 3600, '/'); unset($_COOKIE[$key]); } if (property_exists($this, $key)) { unset($this->{$key}); } return $this->save(); } return self::init()->deleteSession($key); } public function buildSession() { if(isset($this) && is_object($this)) { foreach ($_COOKIE as $key => $c) { if ($this->is_serialized($c)) { $this->{$key} = unserialize($c); } else { $this->{$key} = $c; } } return $this; } return self::init()->buildSession(); } public function save() { if(isset($this) && is_object($this)) { foreach (get_object_vars($this) as $key => $i) { if (is_array($i) || is_object($i)) { setcookie($key, serialize($i), time()+$i['time'], '/'); } else { setcookie($key, $i, time()+$i['time'], '/'); } } return $this; } else{ Self::init()->save(); } } public function has($key) { if(isset($_COOKIE[$key])) { return self::getSession($key); } else{ return false; } } public function getAndDelete($key) { $session = self::getSession($key); self::deleteSession($key); return $session; } private function is_serialized($data){ return (is_string($data) && preg_match("#^((N;)|((a|O|s):[0-9]+:.*[;}])|((b|i|d):[0-9.E-]+;))$#um", $data)); } private function init($params = array()){ if(isset($this) && is_object($this)){ return $this; } $class = get_called_class(); return new $class($params); } public function resetSession(){ foreach($_COOKIE as $key=>$c){ if($key != 'user'){ self::deleteSession($key); } } } public function executeSessions(){ } }
JavaScript
UTF-8
921
3.203125
3
[]
no_license
let texTarea = document.getElementById("text"); let button = document.getElementById("button"); let ul = document.getElementById("ul"); let API = "http://localhost:3000/tweets" // console.log(ul) button.addEventListener('click', () => { let obj = { body: texTarea.value } fetch(API, { method: 'post', body: JSON.stringify(obj), headers: { 'Content-Type': 'application/json; charset=utf-8' } }) .then(res => res.json()) .then(data => { console.log(data); ul.innerHTML += ` <li>${data.body}</li> `; texTarea.value = "" }); }) fetch(API) .then(res => res.json()) .then(data => { data.forEach(tweets => { let li = ` <li>${tweets.body}</li> ` ul.innerHTML += li; }); })
Python
UTF-8
1,673
3.421875
3
[]
no_license
# produkt = input("Podaj jaki produkt chcesz kupić: ") # # produkt = print ("produkt") # # waga = input("Podaj wagę produktu") # # waga = print("waga") # # Cena = 1,99 # kg = 0 # cena_za_kg = dict(cena ) produkty = {"Ziemniaki": 2, "Bataty": 4, "Pomidory": 6} magazyn = {"Ziemniaki": 10, "Bataty": 10, "Pomidory": 10} do_zapłaty = 0 while True: print("-"*40) print("Nasz sklep oferuje: ") for produkt in produkty: print(f' - {produkt} - {produkty[produkt]} PLN') komenda = input("Co chcesz zrobić: [d]odać, [k]upić, [koniec] by by przerwać zakupy") if komenda == 'koniec': break produkt_wybrany = input("Co chcesz kupić? ") if produkt_wybrany not in produkty: print("Nie mamy takiego produktu!") continue waga = float(input("Ile chcesz kupić wybranego produktu[{produkt_wybrany}]")) if magazyn[produkt_wybrany] < waga: print(f"Mamy za mało [{produkt_wybrany}") continue magazyn[produkt_wybrany] = magazyn[produkt_wybrany] - waga cena = produkty[produkt_wybrany] koszt = waga * cena do_zapłaty += koszt elif komenda == 'd': produkt_do_dodania = input(("Jaki produkt chcesz dodać?")) if produkt_do_dodania not in magazyn: magazyn ile_produktu_dodajemy = float(input("Ile tego dodać? ")) magazyn[produkt_do_dodania] += ile_produktu_dodajemy else print("Niepoprawna komenda!!") print("="*40) print(f"Za zakupy zapłacisz: {do_zapłaty} PLN") for produkt in koszyk: print(f" - {produkt} - {koszyk[produkt]} PLN") suma += koszyk[produkt] print("-"*40) print(f"Suma: {suma} PLN")
Java
UTF-8
254
2.484375
2
[]
no_license
public class mainProgram2 { public static void main(String[] args) { Car c = new Car("Audi", "A4", 25000.0f, 200, 4, 4); Car clone = c.clone(); c.setPrice(30000.0f); c.vehicleInfo(); clone.vehicleInfo(); } }
SQL
UTF-8
1,925
2.984375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.5.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jan 17, 2018 at 04:00 PM -- Server version: 10.1.16-MariaDB -- PHP Version: 5.5.38 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `banked` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `role` int(11) NOT NULL, `createdAt` datetime NOT NULL, `updatedAt` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `password`, `role`, `createdAt`, `updatedAt`) VALUES (2, 'brian', '$2a$10$ZLkwzAEU3sxgqohBV/NakOMKOoaj5S8RCrJ3B.lpzoMfG.52ii27m', 4, '2018-01-03 06:54:05', '2018-01-03 06:54:05'), (3, 'sipho', '$2a$10$5lSy5S/8IOTkRd0FoQUqpu3nSrThZKrl2mo4xCEUgJ4MHt441F8gO', 4, '2018-01-08 03:12:07', '2018-01-08 03:12:07'), (4, 'james', '$2a$10$PtOXCRLLGc7MTV878odmMO1V9gzMcc042F1WhLSuRjK1ante9R7Wq', 2, '2018-01-11 15:01:34', '2018-01-11 15:01:34'); -- -- Indexes for dumped tables -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `username` (`username`), ADD UNIQUE KEY `users_username_unique` (`username`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C++
ISO-8859-1
4,037
3.765625
4
[]
no_license
#include <iostream> using namespace std; //PARTE 1: Verificar se o nmero primo bool ehPrimo(int n){ int cont = 0, i; for(i = 2; i <= n; i++){ if(n%i == 0){ cont++; } } if(cont == 1) return true; else return false; } //PARTE 2: Posio do nmero int pos_primo(int num){ int cont_pos = 0, i; for(i = 0; i <= num; i++){ if(ehPrimo(i)) cont_pos++; } return cont_pos;//Posio do nmero no ranking } //PARTE 3: Inverter nmero int invert_num(int num){ int cont = 0, aux, i, num_invert = 0;; aux = num; while(num > 0){//Conta quantos dgitos o nmero tem cont++; num /= 10; } for(i = 0; i < cont; i++){ num_invert = num_invert * 10 + aux % 10;//Ao somar dez quando somamos cada termo da var auxiliar, damos um espao de uma unidade no nmero para alocar o prximo dgito aux /= 10; } return num_invert; } //PARTE 4: Produto dos dgitos int prod_dig(int num){ int prod = 1, cont_dig = 0, aux, i; aux = num;//Armazena o valor inicial de num while(num > 0){//Conta quantos dgitos o nmero tem cont_dig++; num /= 10; } for(i = 0; i < cont_dig; i++){ prod *= aux % 10; aux /= 10; } return prod; } //PARTE 5: Converter o nmero primo em binrio int primo_bin(int num_primo1){ int num = 0, cont = 0, num_invert1 = 0, i = 0; while(num_primo1 > 0){ cont++; num = num * 10 + num_primo1 % 2;//Armazena os termos de forma que fiquem invertidas, mas em binrio, e o 10 d um espao de 1 unidade entre cada nmero num_primo1/=2;//Atualiza o nmero para sair do lao } for(i = 0; i < cont; i++){//Sai do lao, mas usa para isso a quantidade de dgitos o nmero em binrio, capturada anteriormente num_invert1 = num_invert1 * 10 + num % 2; num = (num - num % 2) / 10;//Adiciona os nmeros na ordem inversa, operando da unidade at a centena usando o 10 como fator de correo } return num_invert1; } //Funo principal int main () { setlocale(LC_ALL,"portuguese"); unsigned int num;//Nmero positivo somente int numinv, contSheldon = 0, pos, posInv, prod, bin_num; cin >> num; //Verifica se o nmero primo e inverte ele(PARTE 1) if(ehPrimo(num)){ cout << " primo" << endl; contSheldon++; } else{ cout << "No primo" << endl; } pos = pos_primo(num); //Posio do nmero primo(PARTE 2) cout<< "Posio: " << pos << endl; numinv = invert_num(num); //Captura o nmero invertido(PARTE 3) //Imprime o nmero invertido sendo primo ou no cout << "Nmero invertido: " << numinv << endl; //Verifica se o nmero invertido primo(PARTES 1 E 3) if(ehPrimo(numinv)){ cout << "Nmero invertido primo" << endl; contSheldon++; } else{ cout << "Nmero invertido no primo"<< endl; } //Armazena a posio do nmero invertido(PARTE 2) posInv = pos_primo(numinv); //Posio do nmero invertido cout << "Posio nmero invertido: " << posInv << endl; //Compara se as posies do num e do numInv coincidem(PARTES 2 E 3) if(pos == invert_num(posInv)){ cout << "Posies coincidem" << endl; contSheldon++; } else{ cout << "As posies no coincidem" << endl; } //Produto dos dgitos(PARTE 4) prod = prod_dig(num); //Imprime o produto dos dgitos cout << "Produto dos dgitos: " << prod << endl; //Compara se o produto e a posio coincidem(PARTES 2 E 4) if(prod == pos){ cout << "Produto e posio coincidem" << endl; contSheldon++; } else{ cout << "Produto e posio no coincidem" << endl; } //Converte o nmero inicial em binrio(PARTE 5) bin_num = primo_bin(num); cout << "Nmero em binrio: " << bin_num << endl; //Verifica se o binrio palndromo(PARTES 3 E 5) if(bin_num == invert_num(bin_num)){ cout << "Binrio palndromo" << endl; contSheldon++; } else{ cout << "Binrio no palndromo" << endl; } //Verifica se Sheldon if(contSheldon == 5) cout << " Sheldon"; else cout << "No Sheldon"; return 0; }
PHP
UTF-8
5,906
2.5625
3
[]
no_license
<?php class SiteController extends Controller { /** * Declares class-based actions. */ public function actions() { return array( // captcha action renders the CAPTCHA image displayed on the contact page 'captcha'=>array( 'class'=>'CCaptchaAction', 'backColor'=>0xFFFFFF, ), // page action renders "static" pages stored under 'protected/views/site/pages' // They can be accessed via: index.php?r=site/page&view=FileName 'page'=>array( 'class'=>'CViewAction', ), ); } /** * This is the default 'index' action that is invoked * when an action is not explicitly requested by users. */ public function actionIndex() { // renders the view file 'protected/views/site/index.php' // using the default layout 'protected/views/layouts/main.php' //进入首页时,取1.最新10条用户动态,即最新的面试准备信息;2.最新的10条自我介绍 3.最新10条求人品 /* */ $management = new PrepareManagement(); $prepareForms = $management->getLatestPrepare(); $userManagement = new UserManagement(); $selfIntroductions = $userManagement->getLatestIntroduction(); $preparedata= new CArrayDataProvider($prepareForms); $introductiondata = new CArrayDataProvider($selfIntroductions); $loginForm = new LoginForm(); $renpindata=new CActiveDataProvider('Renpin'); $renpin = $renpindata->getData(); //获取10条最新的面试总结 $summaryManagement=new SummaryManagement(); $summaryForms = $summaryManagement->getLatestSummary(); $summaryData =new CArrayDataProvider($summaryForms); // $renpindata=new CActiveDataProvider('renpin');// array( // 'criteria'=>array( //// 'condition'=>'user_name='."'".$user_name."'", // 'order'=>'time DESC', // ), // 'pagination'=>array( // 'pageSize'=>1, // ), // )); //$prepareForm = new PrepareForm(); $this->render('index',array('preparedata'=>$preparedata,'introductiondata'=>$introductiondata,'loginForm'=>$loginForm,'renpin'=>$renpin,'summaryData'=>$summaryData)); } /** * This is the action to handle external exceptions. */ public function actionError() { if($error=Yii::app()->errorHandler->error) { if(Yii::app()->request->isAjaxRequest) echo $error['message']; else $this->render('error', $error); } } /** * Displays the contact page */ public function actionContact() { $model=new ContactForm; if(isset($_POST['ContactForm'])) { $model->attributes=$_POST['ContactForm']; if($model->validate()) { $name='=?UTF-8?B?'.base64_encode($model->name).'?='; $subject='=?UTF-8?B?'.base64_encode($model->subject).'?='; $headers="From: $name <{$model->email}>\r\n". "Reply-To: {$model->email}\r\n". "MIME-Version: 1.0\r\n". "Content-type: text/plain; charset=UTF-8"; mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers); Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.'); $this->refresh(); } } $this->render('contact',array('model'=>$model)); } /** * Displays the login page */ public function actionLogin() { $model=new LoginForm; // if it is ajax validation request if(isset($_POST['ajax']) && $_POST['ajax']==='login-form') { echo CActiveForm::validate($model); Yii::app()->end(); } // collect user input data if(isset($_POST['LoginForm'])) { $model->attributes=$_POST['LoginForm']; // validate user input and redirect to the previous page if valid if($model->validate() && $model->login()) $this->redirect(Yii::app()->user->returnUrl); // $this->redirect('index.php'); } // display the login form $this->render('login',array('model'=>$model)); } /** * Logs out the current user and redirect to homepage. */ public function actionLogout() { Yii::app()->user->logout(); $this->redirect(Yii::app()->homeUrl); } /** * Displays the register page */ public function actionRegister() { $model=new RegisterForm(); // if it is ajax validation request if(isset($_POST['ajax']) && $_POST['ajax']==='register-form') { echo CActiveForm::validate($model); Yii::app()->end(); } // collect user input data if(isset($_POST['RegisterForm'])) { $model->attributes=$_POST['RegisterForm']; // validate user input and redirect to the previous page if valid /*if($model->validate() && $model->login()) $this->redirect(Yii::app()->user->returnUrl); */ $model->register(); $modelLogin=new LoginForm; $modelLogin->username = $model->username; $modelLogin->password = $model->password; $modelLogin->login(); $this->redirect('index.php'); //注册成功后跳到首页 } // display the login form //$this->render('login',array('model'=>$model)); /**/ $tmp = ""; $this->render('register',array('model'=>$model)); } }
Markdown
UTF-8
8,864
2.859375
3
[]
no_license
``` 概論 學習方式 監督式 小學 非監督式 自已找規則 半監督式 電腦找規則 強化式 錯誤中找路徑 監督式 連續反應(回歸) 離散反應(分類) 數據 非監督式 分群(或聚類)(連續數據) 降維(向量)欄(column) 資訊(row) 非負矩陣因式分解 分類 回歸 人以類聚 物以群分 半監督式 將少量的標記數據與大量的未標記數據結合 強化式 嘗試錯誤 硬分群:其中每個數據點只屬於一個集群 軟分群:其中每個數據點可以屬於多個集群 訓練 取資料 提特徵 訓練模型 優化參數 模型 1.取資料 數據集 訓練 驗證 測試 用於評估 2.提特徵 可以遵循蠻力計算法 也可以從特定分類任務的 3.訓練模型 4.優化參數 要提高模型性能,除了嘗試其他更復雜演算法 真陽 偽陰(漏報) 偽陽(誤報) 真陰 5.模型 準確度 = 分類正確的樣本個數 / 總樣本個數 1 8 1 90 準確度 = 真陽+真陰 / 真陽+真陰+偽陽+偽陰 = 1+90 / 1+90+1+8 = 0.91 閥值 ROC Curve ``` ``` 監督式學習|分類 使用分類學習器 (Classification Learner) “Command Window”: fishertable = readtable('fisheriris.csv'); 輸入 “classificationLearner” New Session FILE -> From Workspace -> All -> Train 用24種訓練 顯示所有結果,並會標示出前一名 Confusion Matrix 顯示 偽陰偽陽 ROC Curve Misclassification Costs OPTIONS ``` ``` 建模 模型 ❓ 輸入 輸出 已知 已知 從經驗中學習 學習⽅式 監督式學習(Supervised Learning) 從成對的問題/答案找規則 例如:讓電腦各看1,000張貓和狗的圖片,再問電腦⼀張新的圖片上是貓或狗? 1. 分類 classification 離散反應 2. 回歸 regression 連續變量 所有資料都被「標註」(label),告訴機器相對應的值 監督式學習|建立⼀個基於不確定性證據進⾏預測的模型 透過已知標準答案資料進⾏模型訓練 ❖ 訓練已知輸入和輸出數據的模型,預測未來的輸出 非監督式學習(Unsupervised Learning) 只有從問題找規則 例如:讓電腦各看10萬張照片,然後⾃⾏歸納後告訴你某些照片跟其他照片不太⼀樣。 1. 分群(或聚類) Clustering 2. 降維 Dimensionality Reduction 非監督式學習|在數據中尋找隱藏的模式或內部結構 未知標準答案(不需⼈⼯來標籤分類) ❖ 在輸入數據中查找隱藏的模式 半監督式學習(Semi-supervised Learning) ⼤部分只有問題找規則 例如:讓電腦各看1,000張貓和狗的圖片,另外還有10萬張照片,讓電腦找規則。 半監督式學習|訓練期間將少量的標記數據與⼤量的未標記數據結合 強化式學習(Reinforcement Learning) 在嘗試錯誤中找到成功路徑 例如:讓電腦學玩瑪莉歐、AlphaZero⾃學圍棋、Google控制資料中⼼伺服器的⽤電模式。 不需要正確答案 ❖ 透過獎勵與懲罰來引導答案 強化式學習|系統(或代理⼈),藉由與環境的互動來改進⾃⾝的效能 監督式 分類 線性分類器 (linear classifier) 監督式 回歸 非監督式 分群 硬分群 ❖ 其中每個數據點只屬於⼀個集群 軟分群 ❖ 其中每個數據點可以屬於多個集群 非監督式 降維 降維:⽤降維的⽅法改進模型|EEG 數據減縮 演算法 分類 ⾙葉斯 回歸 線性回歸 SVR, GPR 決策樹 分群 K均值 ⾼斯混合 降維 強化式學習 蒙特卡洛樹搜索 湯普森採樣 overfit (過度擬合) 選擇正確的演算法需要 tradeoff (權衡)⼀個好處和另⼀個好處 訓練|迭代進⾏,直到取得令⼈滿意的性能 預測|將訓練好的模型集成到應⽤程序中 準備數據|訓練(Training),驗證(Validation)和測試集(Testing) 訓練數據 (Training Data) ❖ 訓練集 (training set) ❖ 訓練模型 ❖ 像是課本、講義 ❖ 驗證集 (validation set) ❖ 選擇和修改模型 ❖ 像是模擬考 ❖ 測試數據 (Testing Data) ❖ 不會修改模型或更新參數 ❖ 評估此模型的效能,模型如何在實際情況 下進⾏預測 ❖ 像是學測或指考 準備數據|泛化(Generalization) 準備數據|過度擬合(Overfitting)、擬合不⾜(Underfitting) 探索數據 (Exploring the Data) 預處理數據 (Preprocessing) 刪除異常值和趨勢 填補缺失數據 對數據進⾏正規化(Normalizing) 特徵擷取 (Extracting Features) 選擇特徵(Selecting Feature)|避免使⽤過多特徵 特徵(Feature)|特徵表格(Feature Table) 類別型特徵(Categorical Feature)|通常是「字串形式」 類別型特徵(Categorical Feature)|1. 序號編碼(Ordinal Encoding 2. 獨熱編碼(One-hot Encoding) 3. ⼆進位編碼(Binary Encoding) 組合特徵(Combined Features)|提⾼複雜關係的擬合能⼒ ⽂字表⽰模型(Text Representation Model)|詞袋模型(Bag of Words) 開發預測模型是⼀個迭代過程 1. 選擇訓練和驗證數據 2. 選擇分類演算法 3. 反複訓練和評估分類模型 改善模型性能|特徵選擇|常⽤特徵選擇技術 近鄰元分析 (NCA) 改善模型性能|特徵變換|降維的形式,三個最常⽤的降維技術 主成分分析 (PCA) 調整模型參數 ROC 曲線 operating point (⼯作點)或cutoff 最⼤限度地減⼩由 cost function (代價函數)定義的總體“ cost (代價)” 變換或提取特徵|使⽤特徵選擇來糾正誤分類和過度擬合 針對我們的⼼⾳分類器,我們運⽤鄰域分量分析 (NCA) 鄰域分量分析(NCA, Neighborhood component analysis) 可以運⽤代價矩陣(cost matrix) 進⾏特定任務的權衡|引入偏差(bias) 混淆矩陣(confusion matrix) 評估指標|準確度(Accuracy) 分類正確的樣本占總樣本個數的 比例 ❖ 也可以⽤陽性陰性來計算 準確度 = 分類正確的樣本個數 / 總樣本個數 準確度 = 真陽+真陰 / 真陽(1)+真陰(90)+偽陽(1)+偽陰(8) = TP+TN / TP+TN+FP+FN = (1 + 90) / (1 + 90 + 1 + 8) = 0.91 精確度 = 真陽 / 真陽+偽陽 = TP / TP+FP = 1 / 1+1 = 0.5 召回率 = 真陽 / 真陽+偽陰 = TP / TP+FN = 1 / 1+8 = 0.11 classification threshold (分類閾值) 精確度 量測正確分類為標記為垃圾郵件的電⼦郵件的百分比 TP / TP+FP = 8 / 8+2 = 0.8 ❖ 召回率 量測正確分類的實際垃圾郵件的百分比 TP / TP+FN = 8 / 8+3 = 0.73 偽陽 False Positives ⇩ 偽陰 False Negatives ⇧ ❖ 精確度(Precision) ⇧ 召回率 (Recall) ⇩ 精確度 = TP / TP+FP = 7 / 7+1 = 0.88 召回率 = TP / TP+FN = 7 / 7+4 = 0.64 評估指標|P-R 曲線 評估指標|ROC Curve(Receiver Operating Characteristic curve)「接受者操作特性曲線」 橫座標為偽陽率(False Positive Rate, FPR) FPR = FP / N = FP / FP+TN 縱座標為真陽率(True Positive Rate, TPR) TPR = TP / P = TP / TP + FN 10 位疑似癌症患者 ❖ 3 位罹患癌症 (P = 3) ❖ 7 位沒罹患癌症 (N = 7) ❖ 醫院對這 10 位疑似患者做了診斷 ❖ 檢出 3 位癌症患者 ❖ 其中有 2 位確實是真正的患者 (TP = 2) 真陽率 = TP / P = 2 / 3 對於 7 位沒罹患癌症來說 ❖ 有⼀位很不幸被誤診為癌症患者 (FP=1) 偽陽率 = FP / N = 1 / 7 這組分類結果就對應 ROC 曲線上的⼀個點 (1/7, 2/3) 評估指標| AUC (Area under ROC Curve) :ROC 曲線下的⾯積⼤⼩ 誤報風險 (false positives) 漏報的風險 (false negatives) 敏感度(Sensitivity)和特異度(Specificity) 評估指標|平⽅根誤差(Root Mean Square Error · RMSE) 陳時中開課:全國PCR普篩找出無症狀感染者,需花690億元,不符效益! 使⽤分類學習器 (Classification Learner) App : classificationLearner” 分類 鳶尾花 (Iris) fishertable = readtable('fisheriris.csv'); 信⽤評級 (Credit Rating) creditrating = readtable('CreditRating_Historical.dat'); 汽⾞ (Cars) load carsmall >> cartable = table(Acceleration, Cylinders, Displacement,... Horsepower, Model_Year, MPG, Weight, Origin); ⼼律失常(Arrhythmia) load arrhythmia >> Arrhythmia = array2table(X); >> Arrhythmia.Class = categorical(Y); 卵巢癌(Ovarian Cancer) >> load ovariancancer >> ovariancancer = array2table(obs); >> ovariancancer.Group = categorical(grp); 電離層 (Ionosphere) >> load ionosphere >> ionosphere = array2table(X); ionosphere.Group = Y; >> ionosphere.Group = Y; 監督式學習|分類學習器(Classification Learner) 監督式學習|回歸 使⽤回歸學習器 (Regression Learner) App : regressionLearner 非監督式學習|分群(或聚類) 使⽤類神經網路分群器 (Neural Net Clustering) App : nnstart AI 實戰吧 https://tbrain.trendmicro.com.tw/ ```
Shell
UTF-8
3,674
4.34375
4
[]
no_license
#!/bin/sh INPUT_FILE="stats_input$$" TMP_FILE="stats_tmp$$" function stats () { } function row_separator () { } function column_separator () { } function average_calculator () { } function median_calculator () { } function average_printer () { } function median_printer () { } function rows () { printf "Average\tMedian\n" while read line do # write row, newline separated, to temporary file printf "%s\n" $line > $TMP_FILE # sort temporary file sort $TMP_FILE -n -o $TMP_FILE # print average and median for row printf '%s\t%s\n' $(calculate_average) $(calculate_median) done < $INPUT_FILE } function row_to_column () { # arg: col number COL=$1 while read LINE do # write column COL to temporary file echo $LINE | cut -d" " -f $COL >> $TMP_FILE done < $INPUT_FILE } function columns () { local AVERAGES=() # array for storing each column's average local MEDIANS=() # array for storing each column's medians local ROWS=$(wc -l < $INPUT_FILE) # number of rows in file local WORDS=$(wc -w < $INPUT_FILE) # number of numbers in file # if file is empty, avoid division by zero error if [ $ROWS -eq "0" ] then ROWS=1 fi local COLS=$(( $WORDS / $ROWS )) # calculate number of columns in file for COL in $(seq 1 $COLS) do $(> $TMP_FILE) # empty $TMP_FILE #while read LINE #do # write column COL to temporary file # echo $LINE | cut -d" " -f $COL >> $TMP_FILE #done < $INPUT_FILE row_to_column $COL # sort temporary file from least to greatest sort $TMP_FILE -n -o $TMP_FILE # calculate average for column and add to AVERAGES array AVERAGES+=($(calculate_average)) # calculate median for column and add to MEDIAN array MEDIANS+=($(calculate_median)) done # print results to standard output echo Averages: if [ ${#AVERAGES[@]} -ne 0 ] then printf "%s\t" "${AVERAGES[@]}" fi printf "\n" echo Medians: if [ ${#MEDIANS[@]} -ne 0 ] then printf "%s\t" "${MEDIANS[@]}" fi printf "\n" } function calculate_average() { local SUM=0 local COUNT=0 local AVERAGE=0 while read -r num do (( SUM += num )) (( COUNT += 1 )) done < $TMP_FILE # add 0.5 to AVERAGE in order to round properly AVERAGE=$( echo $SUM / $COUNT + 0.5 | bc -l ) # rounded AVERAGE echo ${AVERAGE%.*} } function calculate_median() { # find number of lines in $TMP_FILE local NUMS=$(wc -l < $TMP_FILE) # calculate line of $TMP_FILE with median number local MEDIAN_INDEX=$(( ($NUMS / 2) +1 )) # get median line of $TMPFILE echo $( head -$MEDIAN_INDEX $TMP_FILE | tail -1 ) } function clean_up() { # remove temp files rm -f $TMP_FILE rm -rf "stats_input$$" } function usage() { >&2 echo "Usage: stats {-rows|-cols} [file]" clean_up exit 1 } trap clean_up EXIT # run clean_up no matter what if [ "$#" = "1" ] then # read from standard input cat > $INPUT_FILE elif [ "$#" = "2" ] then INPUT_FILE=$2 else # bad arguments usage fi if [ ! -r $INPUT_FILE ] then >&2 echo "${0}: Cannot read ${INPUT_FILE}" clean_up exit 1 fi if [[ $1 == -r* ]]; then # calculate stats for rows rows elif [[ $1 == -c* ]]; then # calculate stats for columns columns else # bad arguments usage fi # clean up files clean_up # HANDLE ERRORS # NEED COMMENTS # PIPE ERROR OUTPUT CORRECTLY # CORRECT EXIT STATEMENTS exit 0
JavaScript
UTF-8
861
3.03125
3
[]
no_license
function myTask() { var num = document.getElementById("myNumberToCath").value; // document.getElementById("myNumberToShow").innerText = num; if (num > 300) { document.getElementById("myNumberToShow").innerText = 300; alert("not more than 300"); } else if (num < 1) { document.getElementById("myNumberToShow").innerText = 1; alert("not less than 1"); } else { document.getElementById("myNumberToShow").innerText = parseFloat(document.getElementById("myNumberToCath").value).toFixed(2); } localStorage.setItem('myTastNumber', num); sessionStorage.setItem('stam', 'noam'); } function init() { document.getElementById("myNumberToCath").value = localStorage.getItem("myTastNumber"); } function nonono() { localStorage.removeItem('myTastNumber') }
C
UTF-8
7,420
3.671875
4
[]
no_license
#include"slinklist.h" /* 在静态单链线性表L中查找第一个值为e的元素 若找到,则返回它在L中的位序,否则返回0 */ int LocateElem_SL(SLinkList L,ElemType e){ int i; i = L[0].cur; while (i && L[i].data != e) i = L[i].cur; return i; } /* 将一维数组space中各分量链成一个备用链表,sapce[0].cur为头指针 “0”表示空指针 */ void InitSpace_SL(SLinkList space){ int i; for (i = 0; i < MAXSIZE - 1;i++){ space[i].cur = i+1; } space[MAXSIZE-1].cur = 0; } /* 若备用空间链表非空,则返回分配的结点下标 */ int Malloc_SL(SLinkList space){ int i; i = space[0].cur; if(space[0].cur) space[0].cur = space[i].cur; return i; } /* 将下标为k的空闲结点回收到备用链表 */ void Free_SL(SLinkList space,int k){ space[k].cur = space[0].cur; space[0].cur = k; } /* 依次输入集合A和B的元素,在一维数组sapce中建立表示集合(A-B)并(B-A)的静态链表,S为其头指针。 假设备用空间足够大,space[0].cur为其头指针。 */ void difference(SLinkList space,int *S){ int r,j,i,m,n; InitSpace_SL(space); (*S) = Malloc_SL(space); //S头结点指针(游标) r = (*S); //r指向最后结点 scanf("%d,%d",&m,&n); for (j = 0; j < m; j++){ i = Malloc_SL(space); scanf("%d",&(space[i].data)); space[r].data = i; r = i; } space[r].cur = 0; int b,p,k; for (i = 0; i < n; i++){ scanf("%d",&b); p = (*S); k = space[*S].cur; while ( k != space[r].cur && space[k].data != b){ p = k; k = space[k].cur; } if (k == space[r].cur){ i = Malloc_SL(space); space[i].data = b; space[i].cur = space[r].cur; space[r].cur = i; } else { space[p].cur = space[k].cur; Free_SL(space,k); if (r == k)r=p; } } } //静态链表操作 /* 初始化 先初始化备用空间,而后从备用空间中申请头结点的空间,进而完成链表的初始化 初始化成功则使用S存储头结点索引,且返回OK,否则返回ERROR */ Status InistList_SL(SLinkList space,int *S){ int index; InitSpace_SL(space); index = Malloc_SL(space); if (!index)return ERROR; space[index].cur = 0; *S = index; return OK; } /* 销毁(结构) 释放静态链表所占内存,即将静态链表所有结点空间移入备用空间列表中。 */ Status DestoryList_SL(SLinkList space,int *S){ int cur; if (S == NULL || *S == 0)return ERROR; while (*S){ cur = space[*S].cur; Free_SL(space,*S); *S = cur; } return OK; } /* 置空(内容) 这里需要释放静态链表中非头结点处的空间 */ Status ClearList_SL(SLinkList space,int S){ int P; int cur; if (!S)return ERROR; P = space[S].cur; while (P){ cur = space[P].cur; Free_SL(space,P); P = cur; } space[S].cur = 0; return OK; } /* 判空 判断静态链表中是否包含有效数据 返回值 TRUE: 静态链表为空 FALSE: 静态链表不为空 */ Status ListEmpty_SL(SLinkList space,int S){ if (S != 0 && space[S].cur == 0)return TRUE; else return FALSE; } /* 计数 返回静态链表包含的有效元素的数量 */ int ListLength_SL(SLinkList space,int S){ int count; if (S == 0 || space[S].cur == 0)return 0; S = space[S].cur; count = 0; while (S){ count++; S = space[S].cur; } return count; } /* 取值 获取静态链表中第i个元素,将其存储到e中 如果可以找到,返回OK,否则,返回ERROR */ Status GetElem_SL(SLinkList space, int S,int i, ElemType * e){ int count; if (S == 0 || space[S].cur == 0)return ERROR; S = space[S].cur; count = 0; while (S && count < i-1){ S = space[S].cur; count++; } if (!S || count > i-1)return ERROR; *e = space[S].data; return OK; } /* 查找 返回静态链表中首个与e满足Compare关系的元素位序 如果不存在这样的元素,则返回0. */ int LocateElem(SLinkList space,int S,ElemType e,Status(Compare)(ElemType,ElemType)){ int i,p; if (S == 0 || space[S].cur == 0)return ERROR; i = 1; p = space[S].cur; while (p && !Compare(space[p].data,e)){ i++; p = space[p].cur; } if(p)return i; else return 0; } /* 前驱 获取元素cur_e的前驱 如果存在,将其存储到pre_e中,返回OK 如果不存在,则返回ERROR */ Status PriorElem_SL(SLinkList space, int S,ElemType cur_e,ElemType *pre_e){ int pre,next; if (S == 0 || space[S].cur == 0)return ERROR; pre = space[S].cur; if (space[pre].data == cur_e)return ERROR; next = space[pre].cur; while (next && space[next].data != cur_e){ pre = next; next = space[next].cur; } if (next){ *pre_e = space[pre].data; return OK; } return ERROR; } /* 后继 获取元素cur_e的后继 如果存在,将其存储到next_e中,返回OK 如果不存在,则返回ERROR */ Status NextElem_SL(SLinkList space,int S, ElemType cur_e,ElemType *next_e){ int pre; if (S == 0 || space[S].cur == 0)return ERROR; pre = space[S].cur; while (space[pre].cur && space[pre].data != cur_e){ pre = space[pre].cur; } if (space[pre].cur){ *next_e = space[space[pre].cur].data; return OK; } return ERROR; } /* 插入 向静态链表第i个位置上插入e,插入成功则返回OK,否则返回ERROR */ Status ListInsert_SL(SLinkList space, int S,int i,ElemType e){ int p,s; int j; if (!S)return ERROR; p = S; j = 0; while (p && j < i-1){ p = space[p].cur; j++; } if (!p || j > i-1)return ERROR; s = Malloc_SL(space); space[s].data = e; space[s].cur = space[p].cur; space[p].cur = s; return OK; } /* 删除 删除静态链表第i个位置上的元素,并将被删元素存储到e中 删除成功则返回OK,否则返回ERROR */ Status ListDelete_SL(SLinkList space, int S,int i,ElemType *e){ int p,q; int j; if (!S)return ERROR; p = S; j = 0; while (space[p].cur && j < i-1){ p = space[p].cur; j++; } if (space[p].cur == 0 || j > i - 1){ return ERROR; } q = space[p].cur; space[p].cur = space[q].cur; *e = space[q].data; Free_SL(space,q); return OK; } static void Visit(ElemType e){ printf("%d\n",e); } /* 遍历 用visit函数访问静态链表 */ void ListTraverse_SL(SLinkList space,int S,void(Visit)(ElemType)){ int p; if (S == 0 || space[S].cur == 0)return ; p = space[S].cur; while (p){ Visit(space[p].data); p = space[p].cur; } printf("\n"); } // 以图形化形式输出结构 void PrintList_SL(SLinkList space,int S){ int i = 0; printf("==== 备用空间 ====\n"); while(i < 20) { printf("%2d | %2d | %2d |\n", i, space[i].data, space[i].cur); i = space[i].cur; } printf("==== 静态链表 ====\n"); i = S; while(i>0 && i < 20) { printf("%2d | %2d | %2d |\n", i, space[i].data, space[i].cur); i = space[i].cur; } }
Java
UTF-8
877
2.671875
3
[ "Apache-2.0" ]
permissive
package sh.isaac.solor.direct.rxnorm; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.HashSet; public class ChildTagSet { HashSet<String> childTags = new HashSet<>(); private final String setName; public ChildTagSet(String setName) { this.setName = setName; } public void processElement(Element element) { NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node currentNode = childNodes.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element childElement = (Element) currentNode; childTags.add(childElement.getTagName()); } } } @Override public String toString() { return setName + " children: " + childTags; } }
Java
UTF-8
1,667
3.234375
3
[]
no_license
package think.seventeen; import java.util.*; /** * @author z **/ public class Synchronization { public static void main(String[] args) { Synchronization synchronization = new Synchronization(); synchronization.failFast(); } public void dump() { Collection<String> collection = Collections.synchronizedCollection(new ArrayList<>()); List<String> list = Collections.synchronizedList(new ArrayList<>()); Set<String> s = Collections.synchronizedSet(new HashSet<>()); Set<String> ss = Collections.synchronizedSortedSet(new TreeSet<>()); Map<String, String> m = Collections.synchronizedMap(new HashMap<>()); Map<String, String> sm = Collections.synchronizedSortedMap(new TreeMap<>()); } public void failFast() { Collection<String> c = new ArrayList<>(); c.add("hello"); c.add("world"); for (String s : c) { if ("hello".equals(s)) { c.add(s); } } System.out.println(c); Iterator<String> iterator = c.iterator(); c.add("An object"); try { String s = iterator.next(); } catch (ConcurrentModificationException e) { System.out.println("concurrent modification exception"); } Map<String, Integer> sMap = Map.of("a", 1, "b", 2, "c", 3, "d", 4); Map<String, Integer> stringIntegerMap = new HashMap<>(); sMap.forEach(stringIntegerMap::put); for (Map.Entry<String, Integer> entry : stringIntegerMap.entrySet()) { entry.setValue(1); } System.out.println(stringIntegerMap); } }
Java
UTF-8
739
3.765625
4
[]
no_license
import java.util.Scanner; public class Divide { public static void main(String arg[]) { try { int a, b, c; Scanner KB = new Scanner(System.in); System.out.println("Enter the 2 numbers "); a = KB.nextInt(); b = KB.nextInt(); c = a / b; System.out.println("The quotient of " + a + "/" + b + "=" + c); } catch (ArithmeticException e) { System.out.println("DivideByZeroException caught "); } finally { System.out.println("Inside finally block"); } } }
Java
UTF-8
1,213
2.09375
2
[]
no_license
package org.iana.rzm.init.ant; import org.apache.tools.ant.*; import org.hibernate.*; /** * @author Jakub Laszkiewicz */ public abstract class HibernateTask extends Task { private String configurationFile = null; private String annotationConfiguration = null; public void setConfigurationFile(String configurationFile) { this.configurationFile = configurationFile; } public void setAnnotationConfiguration(String annotationConfiguration) { this.annotationConfiguration = annotationConfiguration; } public final void execute() throws BuildException { SessionFactory sf = (SessionFactory) SpringInitContext.getContext().getBean("sessionFactory"); Session session = sf.openSession(); try { Transaction transaction = session.beginTransaction(); try { doExecute(session); transaction.commit(); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } } finally { session.close(); } } public abstract void doExecute(Session session) throws Exception; }
Java
UTF-8
2,957
2.40625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2015 LingoChamp Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liulishuo.filedownloader; import android.os.SystemClock; /** * The downloading speed monitor. */ public class DownloadSpeedMonitor implements IDownloadSpeed.Monitor, IDownloadSpeed.Lookup { private long mLastRefreshTime; private long mLastRefreshSofarBytes; private long mStartSofarBytes; private long mStartTime; // KB/s private int mSpeed; private long mSoFarBytes; private long mTotalBytes; // The min interval millisecond for updating the download mSpeed. private int mMinIntervalUpdateSpeed = 5; @Override public void start() { this.mStartTime = SystemClock.uptimeMillis(); this.mStartSofarBytes = this.mSoFarBytes; } @Override public void end(long sofarBytes) { if (mStartTime <= 0 || mStartSofarBytes <= 0) { return; } long downloadSize = sofarBytes - mStartSofarBytes; this.mLastRefreshTime = 0; long interval = SystemClock.uptimeMillis() - mStartTime; if (interval < 0) { mSpeed = (int) downloadSize; } else { mSpeed = (int) (downloadSize / interval); } } @Override public void update(long sofarBytes) { if (mMinIntervalUpdateSpeed <= 0) { return; } boolean isUpdateData = false; do { if (mLastRefreshTime == 0) { isUpdateData = true; break; } long interval = SystemClock.uptimeMillis() - mLastRefreshTime; if (interval >= mMinIntervalUpdateSpeed || (mSpeed == 0 && interval > 0)) { mSpeed = (int) ((sofarBytes - mLastRefreshSofarBytes) / interval); mSpeed = Math.max(0, mSpeed); isUpdateData = true; break; } } while (false); if (isUpdateData) { mLastRefreshSofarBytes = sofarBytes; mLastRefreshTime = SystemClock.uptimeMillis(); } } @Override public void reset() { this.mSpeed = 0; this.mLastRefreshTime = 0; } @Override public int getSpeed() { return this.mSpeed; } @Override public void setMinIntervalUpdateSpeed(int minIntervalUpdateSpeed) { this.mMinIntervalUpdateSpeed = minIntervalUpdateSpeed; } }
Python
UTF-8
363
4.8125
5
[]
no_license
#2-2 Simple Messages: Store a message in a variable, and print that message. #Then change the value of your variable to a new message, and print the new message. #This time we use the variable message twice, first with "Hello World!" and then we change it to "Python is great!" message = "Hello world!" print(message) message = "Python is great!" print(message)
Java
UTF-8
5,550
2.28125
2
[]
no_license
/******************************************************************************* * Copyright (c) 2009 - 2012 hCentive Inc. All rights reserved. ******************************************************************************/ /** * Copyright (c) 2009 - 2012 hCentive Inc. All rights reserved. */ /** * Copyright (c) 2009 - 2011 hCentive Inc. All rights reserved. */ package com.demo.dao; import java.io.Serializable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.dao.InvalidDataAccessApiUsageException; public class GenericDAOImpl<T extends Serializable> implements GenericDAO<T> { @PersistenceContext private EntityManager entityManager; @Override public void delete(T t) { entityManager.remove(t); } @Override public void delete(Class<T> clas, Serializable id) { entityManager.remove(entityManager.getReference(clas, id)); } @Override public T create(T t) { entityManager.persist(t); return t; } @Override public T get(Class<T> clas, Serializable id) { return entityManager.find(clas, id); } @Override public T update(T t) { return entityManager.merge(t); } @Override public int executeUpdateNamedQuery(final String queryName, final Map<String, Object> params) { Query queryObject = entityManager.createNamedQuery(queryName); if (params != null) { for (String key : params.keySet()) { queryObject.setParameter(key, params.get(key)); } } return queryObject.executeUpdate(); } @Override @SuppressWarnings("unchecked") public List<T> findByNamedQuery(final String queryName) { return entityManager.createNamedQuery(queryName).getResultList(); } @Override @SuppressWarnings("unchecked") public List<T> findByNamedQuery(final String queryName, final String[] paramNames, final Object... paramValues) { Query queryObject = entityManager.createNamedQuery(queryName); for (int i = 0; i < paramNames.length; i++) { queryObject.setParameter(paramNames[i], paramValues[i]); } return queryObject.getResultList(); } @Override @SuppressWarnings("unchecked") public List<T> findPaginatedByNamedQuery(final String queryName, int startPosition, int maxResult, final String[] paramNames, final Object... paramValues) { Query queryObject = entityManager.createNamedQuery(queryName); for (int i = 0; i < paramNames.length; i++) { queryObject.setParameter(paramNames[i], paramValues[i]); } queryObject.setFirstResult(startPosition); queryObject.setMaxResults(maxResult); return queryObject.getResultList(); } @Override public Object findObjectByNamedQuery(String queryName, String[] paramNames, Object... paramValues) { List<T> results = findByNamedQuery(queryName, paramNames, paramValues); if (results == null || results.size() == 0) { return null; } if (results.size() > 1) { throw new InvalidDataAccessApiUsageException("Multiple records found in query result where single record is expected"); } return results.get(0); } @Override public Object findObjectByNamedQuery(String queryName, Map<String, Object> params) { List<T> results = findByNamedQuery(queryName, params); if (results == null || results.size() == 0) { return null; } if (results.size() > 1) { throw new InvalidDataAccessApiUsageException("Multiple records found in query result where single record is expected"); } return results.get(0); } @Override @SuppressWarnings("unchecked") public List<T> findByNativeQuery(final String query, final Object... params) { Query queryObject = entityManager.createNativeQuery(query); if (params != null) { for (int i = 0; i < params.length; i++) { queryObject.setParameter(i, params[i]); } } return queryObject.getResultList(); } @Override @SuppressWarnings("unchecked") public List<T> findByNamedQuery(String queryName, Map<String, Object> params, int startPosition, int maxResult) { Query queryObject = entityManager.createNamedQuery(queryName); if (params != null) { for (String key : params.keySet()) { queryObject.setParameter(key, params.get(key)); } } queryObject.setFirstResult(startPosition); queryObject.setMaxResults(maxResult); return queryObject.getResultList(); } @Override @SuppressWarnings("unchecked") public List<T> findByNamedQuery(String queryName, Map<String, Object> params) { Query queryObject = entityManager.createNamedQuery(queryName); if (params != null) { for (String key : params.keySet()) { queryObject.setParameter(key, params.get(key)); } } return queryObject.getResultList(); } @Override public Integer deleteByNamedQuery(String queryName, String[] paramNames, Object... paramValues) { Query queryObject = entityManager.createNamedQuery(queryName); for (int i = 0; i < paramNames.length; i++) { queryObject.setParameter(paramNames[i], paramValues[i]); } return queryObject.executeUpdate(); } @Override public EntityManager getEntityManager() { return entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } public void setQueryParams(Query queryObj, Map<String, Object> params) { Iterator<Entry<String, Object>> iterator = params.entrySet().iterator(); while(iterator.hasNext()) { Entry<String, Object> entries = iterator.next(); queryObj.setParameter(entries.getKey(), entries.getValue()); } } }
Java
UTF-8
2,438
2.265625
2
[]
no_license
package com.dlwx.wisdomschool.bean; import java.util.List; /** * Created by Administrator on 2018/1/19/019. */ public class GroupList { /** * code : 200 * result : 获取成功 * body : [{"groupid":"1","group_name":"我的群名称","imgid":"6","imgurl":"http://192.168.0.199/school//Uploads/20161223/585c9226aae09x1000.jpg"},{"groupid":"2","group_name":"我的群名称1","imgid":"6","imgurl":"http://192.168.0.199/school//Uploads/20161223/585c9226aae09x1000.jpg"}] */ private int code; private String result; private List<BodyBean> body; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public List<BodyBean> getBody() { return body; } public void setBody(List<BodyBean> body) { this.body = body; } public static class BodyBean { /** * groupid : 1 * group_name : 我的群名称 * imgid : 6 * imgurl : http://192.168.0.199/school//Uploads/20161223/585c9226aae09x1000.jpg */ private String groupid; private String group_name; private String imgid; private String imgurl; private String num; private String classid; public String getClassid() { return classid; } public void setClassid(String classid) { this.classid = classid; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getGroupid() { return groupid; } public void setGroupid(String groupid) { this.groupid = groupid; } public String getGroup_name() { return group_name; } public void setGroup_name(String group_name) { this.group_name = group_name; } public String getImgid() { return imgid; } public void setImgid(String imgid) { this.imgid = imgid; } public String getImgurl() { return imgurl; } public void setImgurl(String imgurl) { this.imgurl = imgurl; } } }
PHP
UTF-8
1,589
2.734375
3
[]
no_license
<?php namespace kbwp\Integration; use kbwp\kbwp as kbwp; class FaceIt { private static $_instances = []; private $_api_key; private $_id; private $_debug; private $_api_url; private function __construct(string $id, string $api_key, bool $debug_mode_enabled = false) { $this->_api_key = $api_key; $this->_id = $id; $this->_debug = $debug_mode_enabled; $this->_api_url = 'https://open.faceit.com/data/v4'; self::$_instances[$id] = $this; } public static function init(string $id, string $api_key, bool $debug_mode_enabled = false) { if (array_key_exists($id, self::$_instances)) { return self::$_instances[$id]; } return new self($id, $api_key, $debug_mode_enabled); } public function get(string $endpoint, bool $json_decode = true) { $url = $this->_api_url . $endpoint; $headers = [ 'accept' => 'application/json', 'Authorization' => 'Bearer ' . $this->_api_key ]; $response = wp_remote_get( $url, [ 'headers' => $headers ] ); if (is_a($response, 'WP_Error')) return false; if (200 === $response['response']['code']) { return $json_decode ? json_decode($response['body'], false) : $response['body']; } if ($this->_debug) { kbwp::log($response); } return false; } }
Java
UTF-8
750
2.734375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.edu.ifes.composite.menu; /** * * @author pchan */ public class ItemMenu extends Item { public ItemMenu(String descricao) { super(descricao); } @Override public void addItem(Item item) { setDescricao(item.getDescription()); } @Override public void removeItem(Item item) { setDescricao("Item vazio"); } @Override public Item[] getItens() { throw new UnsupportedOperationException("Não suportado"); } }
C#
UTF-8
464
2.640625
3
[]
no_license
using System; namespace CrudRapido.Models { public class Pessoa { public int Id{get; set;} public string Nome{get; set;} public int Idade{get; set;} public DateTime Data{get; set;} public Pessoa(){} public Pessoa(int id, string nome, int idade, DateTime data) { this.Id = id; this.Nome = nome; this.Idade = idade; this.Data = data; } } }
Markdown
UTF-8
2,719
3.59375
4
[]
no_license
#### Sumatoria La suma o la reducción por la suma es definido en: Dado una lista de `MonetaryAmount` este retornará un elemento con la sumatoria de esos valores. ```java public class ReduceSumMonetaryAmount { public static void main(String[] args) { CurrencyUnit dollar = Monetary.getCurrency("USD"); MonetaryAmount money = Money.of(10, dollar); MonetaryAmount money2 = Money.of(10, dollar); MonetaryAmount money3 = Money.of(10, dollar); MonetaryAmount money4 = Money.of(9, dollar); MonetaryAmount money5 = Money.of(8, dollar); Optional<MonetaryAmount> result = Stream.of(money, money2, money3, money4, money5).reduce(MonetaryFunctions.sum()); result.ifPresent(System.out::println);//USD 47 } } ``` Resaltando algo, en caso tenga una moneda diferente en la sumatoria este retornará una excepción. ```java public class ReduceSumMonetaryAmountError { public static void main(String[] args) { CurrencyUnit dollar = Monetary.getCurrency("USD"); CurrencyUnit real = Monetary.getCurrency("BRL"); MonetaryAmount money = Money.of(10, dollar); MonetaryAmount money2 = Money.of(10, dollar); MonetaryAmount money3 = Money.of(10, real); MonetaryAmount money4 = Money.of(9, dollar); MonetaryAmount money5 = Money.of(8, dollar); Optional<MonetaryAmount> result = Stream.of(money, money2, money3, money4, money5).reduce( MonetaryFunctions.sum());//javax.money.MonetaryException: Currency mismatch: BRL/USD } } ``` En caso sea necesario sumar y convertir para una específica moneda, Moneta da soporte para eso, basta proporcionar una implementación de `ExchangeRateProvider` y también la moneda en la que todos los valores serán convertidos. ```java public class ReduceSumMonetaryAmountExchange { public static void main(String[] args) { CurrencyUnit dollar = Monetary.getCurrency("USD"); CurrencyUnit real = Monetary.getCurrency("BRL"); ExchangeRateProvider provider = MonetaryConversions.getExchangeRateProvider(ExchangeRateType.IMF); MonetaryAmount money = Money.of(10, dollar); MonetaryAmount money2 = Money.of(10, dollar); MonetaryAmount money3 = Money.of(10, real); MonetaryAmount money4 = Money.of(9, dollar); MonetaryAmount money5 = Money.of(8, dollar); Optional<MonetaryAmount> result = Stream.of(money, money2, money3, money4, money5).reduce( MonetaryFunctions.sum(provider, dollar));//javax.money.MonetaryException: Currency mismatch: BRL/USD result.ifPresent(System.out::println);//money converted in dollar } } ```
JavaScript
UTF-8
417
2.640625
3
[]
no_license
// anonymous, self-invoking function to limit scope (function() { const NewsfeedView = {} /* Renders the newsfeed into the given newsfeedElement element. */ NewsfeedView.render = newsfeedElement => { // TODO } /* Given post information, renders a post element into newsfeedElement. */ NewsfeedView.renderPost = (newsfeedElement, post) => { // TODO } window.NewsfeedView = NewsfeedView })()
PHP
UTF-8
7,572
2.875
3
[]
no_license
<?php namespace Models; class Truck extends DBmanager { public $currentUser; public function __construct($currentUser, $conn) { $this->currentUser = $currentUser; parent::__construct($conn); } public function addOrder($carname, $color, $engine, $disk) { //getting user and car id for correct insert $user = new User($this->conn, $this->currentUser); $car = new Car($this->conn, $carname); $user_id = $user->getUserColumn('ID'); $car_id = $car->getCarColumn('ID'); $getOptionRequest = "SELECT COUNT(*) AS c, ID FROM options WHERE CarID = ".$car_id." AND Color = '{$color}' AND Engine = '{$engine}' AND Disk='{$disk}'"; //getting all options for this car $optionsInfo = $this->conn->query($getOptionRequest)->fetch_array(); $optionsCount = $optionsInfo['c']; $optionsID = $optionsInfo['ID']; if($optionsCount != 0) //it there is options with needed parameters { //is there already this order $getOrderCountRequest = "SELECT COUNT(*) AS c, ID FROM `order` WHERE OptionID = {$optionsID} AND UserID = {$user_id}"; echo $getOrderCountRequest; $ordersInfo = $this->conn->query($getOrderCountRequest)->fetch_array(); $countOrders = $ordersInfo['c']; $orderID = $ordersInfo['ID']; $request = ""; if($countOrders == 0) //creating new order { $this->conn->query("INSERT INTO `order`(OptionID, UserID, Count) VALUES({$optionsID}, $user_id, 1);"); } else //increasing existing { $this->redactOrder($orderID, '+', 1); } $this->conn->query($request); return true; } else { return false; } } public function changeOrder($idOrder, $sign) { //getting info what should we do $getOrderInfo = "SELECT `order`.Count AS orderCount, options.Quantity AS optionsQuantity FROM `order` JOIN options ON options.ID = `order`.OptionID WHERE `order`.id={$idOrder}"; $ordersInfo = $this->conn->query($getOrderInfo)->fetch_array(); //getting count info we need $orderCount = $ordersInfo['orderCount']; $optionsCount = $ordersInfo['optionsQuantity']; //what we should do with order if($sign == '-' && $orderCount == 1) //if we want to delete order from truck (1-1 = 0, we can`t have 0 cars in truck, so we delete order) { $this->deleteOrder($idOrder); } else //increase or decrease quantity { if($optionsCount > $orderCount || $sign == '-') //checking if we have enough quantity of this option { $this->redactOrder($idOrder, $sign, 1); } else { alert('Вибачте, це все, що у нас є'); } } } private function redactOrder($idOrder, $sign, $value) { $request = "UPDATE `order` SET Count = COUNT {$sign} {$value} WHERE id={$idOrder}"; $this->conn->query($request); } private function deleteOrder($idOrder) { $request = "DELETE FROM `order` WHERE id={$idOrder}"; $this->conn->query($request); } public function getOrders() { $orders = []; $request = "SELECT car.name AS carName, car.year, manufacturer.name AS manufacturerName, car.img, `options`.HP, `options`.disk, `options`.Color, `options`.price, `order`.Count, `order`.ID AS orderID FROM `order` JOIN `options` ON `options`.ID = OptionID JOIN car ON car.ID = `options`.CarID JOIN `user` ON `user`.ID = UserID JOIN manufacturer ON manufacturer.ID = car.ManufacturerID WHERE `user`.login = '{$this->currentUser}'"; $result = $this->conn->query($request); while($row = $result->fetch_array()) { $orders[count($orders)] = $row; //adding orders to array } return $orders; } public function purchaseOrders($email) { if($email != "") { $totalCount = 0; $totalPrice = 0; //making request $request = "SELECT `order`.ID AS orderID, options.ID AS optionsID, `order`.Count AS orderCount, options.price AS optionsPrice, car.name AS carName, options.Color AS carColor FROM `order` JOIN options on `order`.OptionID = options.ID JOIN car ON options.CarID = car.id"; $result = $this->conn->query($request); $orders = []; //how much user bought while($row = $result->fetch_array()) { //filling array with main info $orders[count($orders)] = [ "optionsID" => $row["optionsID"], "orderCount" => $row["orderCount"], "orderID" => $row["orderID"], "carName" => $row["carName"], "carColor" => $row["carColor"], "totalPrice" => $row["orderCount"] * $row['optionsPrice'] ]; //total price and count for statistics $totalCount += $row["orderCount"]; $totalPrice += $row["orderCount"] * $row['optionsPrice']; } $user = new User($this->conn, $this->currentUser); //for stats //cars message for email $cars = ""; //changing database for($i = 0; $i < count($orders); $i++) { //adding to user stats $user->increaseUserOrders($orders[$i]["orderCount"]); $user->increaseUserWasted($totalPrice); //reducing optins quantity $this->conn->query("UPDATE options SET Quantity = Quantity - {$orders[$i]["orderCount"]} WHERE ID = {$orders[$i]["optionsID"]}"); $cars .= "<br>{$orders[$i]['carName']} ({$orders[$i]['carColor']}) - {$orders[$i]['orderCount']}шт - {$orders[$i]['totalPrice']}$"; //deleting order $this->deleteOrder($orders[$i]["orderID"]); } return [ "success" => true, "totalCount" => $totalCount, "totalPrice" => $totalPrice, "cars" => $cars ]; } return false; } } ?>
C
UTF-8
3,525
3.953125
4
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <limits.h> #include "single_linked_list.h" int addElementSingleLinkedList(struct singleLinkedList *list, int value) { struct singleLinkedListElement *newElement = (struct singleLinkedListElement *)malloc(sizeof(struct singleLinkedListElement)); struct singleLinkedListElement *temp; if (list->first == NULL) { list->first = newElement; newElement->data = value; newElement->next = NULL; return value; } else { temp = list->first; while (temp->next != NULL) { temp = temp->next; } temp->next = newElement; newElement->data = value; newElement->next = NULL; bubbleSort(list); return value; } return INT_MIN; } void initSingleLinkedList(struct singleLinkedList *list) { list->first = NULL; } int removeFirstElementSingleLinkedList(struct singleLinkedList *list) { struct singleLinkedListElement *removeFirst = list->first; struct singleLinkedListElement *removeMalocFirst = list->first; int returnValue; // När det inte finns något att ta bort if (list->first == NULL) { return INT_MIN; } // När det bara finns ett element att ta bort if (removeFirst->next == NULL) { returnValue = list->first->data; free(list->first); list->first = NULL; return returnValue; } // När det finns mer än ett element i listan. if (removeFirst->next != NULL) { list->first = list->first->next; free(removeMalocFirst); return list->first->data; } return INT_MIN; } int removeLastElementSingleLinkedList(struct singleLinkedList *list) { struct singleLinkedListElement *removeLast = list->first; struct singleLinkedListElement *secondLastNode = list->first; int returnValue; // När listan är tom från början. if (list->first == NULL) { return INT_MIN; } // När listan bara har ett element kvar. if (removeLast->next == NULL) { returnValue = list->first->data; free(list->first); list->first = NULL; return returnValue; } // När det finns flera elment i listan. else { while (removeLast->next != NULL) { secondLastNode = removeLast; removeLast = removeLast->next; } secondLastNode->next = NULL; free(removeLast); return list->first->data; } } void printSingelLinkedList(struct singleLinkedList *list) { struct singleLinkedListElement *print = list->first; while (print != NULL) { printf("%d \n", print->data); print = print->next; } } void bubbleSort(struct singleLinkedList *list) { int swapped; struct singleLinkedListElement *ptr1; struct singleLinkedListElement *lptr = NULL; /* Bubbelsort inspirerd from geeksforgeeks */ if (list == NULL) return; do { swapped = 0; ptr1 = list->first; while (ptr1->next != lptr) { if (ptr1->data > ptr1->next->data) { swap(ptr1, ptr1->next); swapped = 1; } ptr1 = ptr1->next; } lptr = ptr1; } while (swapped); } void swap(struct singleLinkedListElement *valueA, struct singleLinkedListElement *valueB) { int temp = valueA->data; valueA->data = valueB->data; valueB->data = temp; } void resetSingelLinkedList(struct singleLinkedList *list) { struct singleLinkedListElement *remove = list->first; struct singleLinkedListElement *ptr = list->first; while (remove != NULL) { ptr = ptr->next; free(remove); remove = NULL; remove = ptr; } list->first = NULL; }
C#
UTF-8
449
2.53125
3
[]
no_license
using UnityEngine; public class GameScreen { public Bounds Bounds { get; private set; } public GameScreen(Camera gameCamera) { Vector3 center = gameCamera.transform.position; Vector2 size = new Vector2(); size.y = gameCamera.orthographicSize * 2f; float screenAspect = ((float)Screen.width / Screen.height); size.x = screenAspect * size.y; Bounds = new Bounds(center, size); } }
PHP
UTF-8
12,999
3
3
[ "Apache-2.0" ]
permissive
<?php /** * @package JAMA * * For an m-by-n matrix A with m >= n, the singular value decomposition is * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and * an n-by-n orthogonal matrix V so that A = U*S*V'. * * The singular values, sigma[$k] = S[$k][$k], are ordered so that * sigma[0] >= sigma[1] >= ... >= sigma[n-1]. * * The singular value decompostion always exists, so the constructor will * never fail. The matrix condition number and the effective numerical * rank can be computed from this decomposition. * * @author Paul Meagher * @license PHP v3.0 * @version 1.1 */ class SingularValueDecomposition { /** * Internal storage of U. * @var array */ private $U = array(); /** * Internal storage of V. * @var array */ private $V = array(); /** * Internal storage of singular values. * @var array */ private $s = array(); /** * Row dimension. * @var int */ private $m; /** * Column dimension. * @var int */ private $n; /** * Construct the singular value decomposition * * Derived from LINPACK code. * * @param $A Rectangular matrix * @return Structure to access U, S and V. */ public function __construct($Arg) { // Initialize. $A = $Arg->getArrayCopy(); $this->m = $Arg->getRowDimension(); $this->n = $Arg->getColumnDimension(); $nu = min($this->m, $this->n); $e = array(); $work = array(); $wantu = true; $wantv = true; $nct = min($this->m - 1, $this->n); $nrt = max(0, min($this->n - 2, $this->m)); // Reduce A to bidiagonal form, storing the diagonal elements // in s and the super-diagonal elements in e. for ($k = 0; $k < max($nct,$nrt); ++$k) { if ($k < $nct) { // Compute the transformation for the k-th column and // place the k-th diagonal in s[$k]. // Compute 2-norm of k-th column without under/overflow. $this->s[$k] = 0; for ($i = $k; $i < $this->m; ++$i) { $this->s[$k] = hypo($this->s[$k], $A[$i][$k]); } if ($this->s[$k] != 0.0) { if ($A[$k][$k] < 0.0) { $this->s[$k] = -$this->s[$k]; } for ($i = $k; $i < $this->m; ++$i) { $A[$i][$k] /= $this->s[$k]; } $A[$k][$k] += 1.0; } $this->s[$k] = -$this->s[$k]; } for ($j = $k + 1; $j < $this->n; ++$j) { if (($k < $nct) & ($this->s[$k] != 0.0)) { // Apply the transformation. $t = 0; for ($i = $k; $i < $this->m; ++$i) { $t += $A[$i][$k] * $A[$i][$j]; } $t = -$t / $A[$k][$k]; for ($i = $k; $i < $this->m; ++$i) { $A[$i][$j] += $t * $A[$i][$k]; } // Place the k-th row of A into e for the // subsequent calculation of the row transformation. $e[$j] = $A[$k][$j]; } } if ($wantu AND ($k < $nct)) { // Place the transformation in U for subsequent back // multiplication. for ($i = $k; $i < $this->m; ++$i) { $this->U[$i][$k] = $A[$i][$k]; } } if ($k < $nrt) { // Compute the k-th row transformation and place the // k-th super-diagonal in e[$k]. // Compute 2-norm without under/overflow. $e[$k] = 0; for ($i = $k + 1; $i < $this->n; ++$i) { $e[$k] = hypo($e[$k], $e[$i]); } if ($e[$k] != 0.0) { if ($e[$k+1] < 0.0) { $e[$k] = -$e[$k]; } for ($i = $k + 1; $i < $this->n; ++$i) { $e[$i] /= $e[$k]; } $e[$k+1] += 1.0; } $e[$k] = -$e[$k]; if (($k+1 < $this->m) AND ($e[$k] != 0.0)) { // Apply the transformation. for ($i = $k+1; $i < $this->m; ++$i) { $work[$i] = 0.0; } for ($j = $k+1; $j < $this->n; ++$j) { for ($i = $k+1; $i < $this->m; ++$i) { $work[$i] += $e[$j] * $A[$i][$j]; } } for ($j = $k + 1; $j < $this->n; ++$j) { $t = -$e[$j] / $e[$k+1]; for ($i = $k + 1; $i < $this->m; ++$i) { $A[$i][$j] += $t * $work[$i]; } } } if ($wantv) { // Place the transformation in V for subsequent // back multiplication. for ($i = $k + 1; $i < $this->n; ++$i) { $this->V[$i][$k] = $e[$i]; } } } } // Set up the final bidiagonal matrix or order p. $p = min($this->n, $this->m + 1); if ($nct < $this->n) { $this->s[$nct] = $A[$nct][$nct]; } if ($this->m < $p) { $this->s[$p-1] = 0.0; } if ($nrt + 1 < $p) { $e[$nrt] = $A[$nrt][$p-1]; } $e[$p-1] = 0.0; // If required, generate U. if ($wantu) { for ($j = $nct; $j < $nu; ++$j) { for ($i = 0; $i < $this->m; ++$i) { $this->U[$i][$j] = 0.0; } $this->U[$j][$j] = 1.0; } for ($k = $nct - 1; $k >= 0; --$k) { if ($this->s[$k] != 0.0) { for ($j = $k + 1; $j < $nu; ++$j) { $t = 0; for ($i = $k; $i < $this->m; ++$i) { $t += $this->U[$i][$k] * $this->U[$i][$j]; } $t = -$t / $this->U[$k][$k]; for ($i = $k; $i < $this->m; ++$i) { $this->U[$i][$j] += $t * $this->U[$i][$k]; } } for ($i = $k; $i < $this->m; ++$i ) { $this->U[$i][$k] = -$this->U[$i][$k]; } $this->U[$k][$k] = 1.0 + $this->U[$k][$k]; for ($i = 0; $i < $k - 1; ++$i) { $this->U[$i][$k] = 0.0; } } else { for ($i = 0; $i < $this->m; ++$i) { $this->U[$i][$k] = 0.0; } $this->U[$k][$k] = 1.0; } } } // If required, generate V. if ($wantv) { for ($k = $this->n - 1; $k >= 0; --$k) { if (($k < $nrt) AND ($e[$k] != 0.0)) { for ($j = $k + 1; $j < $nu; ++$j) { $t = 0; for ($i = $k + 1; $i < $this->n; ++$i) { $t += $this->V[$i][$k]* $this->V[$i][$j]; } $t = -$t / $this->V[$k+1][$k]; for ($i = $k + 1; $i < $this->n; ++$i) { $this->V[$i][$j] += $t * $this->V[$i][$k]; } } } for ($i = 0; $i < $this->n; ++$i) { $this->V[$i][$k] = 0.0; } $this->V[$k][$k] = 1.0; } } // Main iteration loop for the singular values. $pp = $p - 1; $iter = 0; $eps = pow(2.0, -52.0); while ($p > 0) { // Here is where a test for too many iterations would go. // This section of the program inspects for negligible // elements in the s and e arrays. On completion the // variables kase and k are set as follows: // kase = 1 if s(p) and e[k-1] are negligible and k<p // kase = 2 if s(k) is negligible and k<p // kase = 3 if e[k-1] is negligible, k<p, and // s(k), ..., s(p) are not negligible (qr step). // kase = 4 if e(p-1) is negligible (convergence). for ($k = $p - 2; $k >= -1; --$k) { if ($k == -1) { break; } if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) { $e[$k] = 0.0; break; } } if ($k == $p - 2) { $kase = 4; } else { for ($ks = $p - 1; $ks >= $k; --$ks) { if ($ks == $k) { break; } $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.); if (abs($this->s[$ks]) <= $eps * $t) { $this->s[$ks] = 0.0; break; } } if ($ks == $k) { $kase = 3; } else if ($ks == $p-1) { $kase = 1; } else { $kase = 2; $k = $ks; } } ++$k; // Perform the task indicated by kase. switch ($kase) { // Deflate negligible s(p). case 1: $f = $e[$p-2]; $e[$p-2] = 0.0; for ($j = $p - 2; $j >= $k; --$j) { $t = hypo($this->s[$j],$f); $cs = $this->s[$j] / $t; $sn = $f / $t; $this->s[$j] = $t; if ($j != $k) { $f = -$sn * $e[$j-1]; $e[$j-1] = $cs * $e[$j-1]; } if ($wantv) { for ($i = 0; $i < $this->n; ++$i) { $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1]; $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1]; $this->V[$i][$j] = $t; } } } break; // Split at negligible s(k). case 2: $f = $e[$k-1]; $e[$k-1] = 0.0; for ($j = $k; $j < $p; ++$j) { $t = hypo($this->s[$j], $f); $cs = $this->s[$j] / $t; $sn = $f / $t; $this->s[$j] = $t; $f = -$sn * $e[$j]; $e[$j] = $cs * $e[$j]; if ($wantu) { for ($i = 0; $i < $this->m; ++$i) { $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1]; $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1]; $this->U[$i][$j] = $t; } } } break; // Perform one qr step. case 3: // Calculate the shift. $scale = max(max(max(max( abs($this->s[$p-1]),abs($this->s[$p-2])),abs($e[$p-2])), abs($this->s[$k])), abs($e[$k])); $sp = $this->s[$p-1] / $scale; $spm1 = $this->s[$p-2] / $scale; $epm1 = $e[$p-2] / $scale; $sk = $this->s[$k] / $scale; $ek = $e[$k] / $scale; $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0; $c = ($sp * $epm1) * ($sp * $epm1); $shift = 0.0; if (($b != 0.0) || ($c != 0.0)) { $shift = sqrt($b * $b + $c); if ($b < 0.0) { $shift = -$shift; } $shift = $c / ($b + $shift); } $f = ($sk + $sp) * ($sk - $sp) + $shift; $g = $sk * $ek; // Chase zeros. for ($j = $k; $j < $p-1; ++$j) { $t = hypo($f,$g); $cs = $f/$t; $sn = $g/$t; if ($j != $k) { $e[$j-1] = $t; } $f = $cs * $this->s[$j] + $sn * $e[$j]; $e[$j] = $cs * $e[$j] - $sn * $this->s[$j]; $g = $sn * $this->s[$j+1]; $this->s[$j+1] = $cs * $this->s[$j+1]; if ($wantv) { for ($i = 0; $i < $this->n; ++$i) { $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1]; $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1]; $this->V[$i][$j] = $t; } } $t = hypo($f,$g); $cs = $f/$t; $sn = $g/$t; $this->s[$j] = $t; $f = $cs * $e[$j] + $sn * $this->s[$j+1]; $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1]; $g = $sn * $e[$j+1]; $e[$j+1] = $cs * $e[$j+1]; if ($wantu && ($j < $this->m - 1)) { for ($i = 0; $i < $this->m; ++$i) { $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1]; $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1]; $this->U[$i][$j] = $t; } } } $e[$p-2] = $f; $iter = $iter + 1; break; // Convergence. case 4: // Make the singular values positive. if ($this->s[$k] <= 0.0) { $this->s[$k] = ($this->s[$k] < 0.0 ? -$this->s[$k] : 0.0); if ($wantv) { for ($i = 0; $i <= $pp; ++$i) { $this->V[$i][$k] = -$this->V[$i][$k]; } } } // Order the singular values. while ($k < $pp) { if ($this->s[$k] >= $this->s[$k+1]) { break; } $t = $this->s[$k]; $this->s[$k] = $this->s[$k+1]; $this->s[$k+1] = $t; if ($wantv AND ($k < $this->n - 1)) { for ($i = 0; $i < $this->n; ++$i) { $t = $this->V[$i][$k+1]; $this->V[$i][$k+1] = $this->V[$i][$k]; $this->V[$i][$k] = $t; } } if ($wantu AND ($k < $this->m-1)) { for ($i = 0; $i < $this->m; ++$i) { $t = $this->U[$i][$k+1]; $this->U[$i][$k+1] = $this->U[$i][$k]; $this->U[$i][$k] = $t; } } ++$k; } $iter = 0; --$p; break; } // end switch } // end while } // end constructor /** * Return the left singular vectors * * @access public * @return U */ public function getU() { return new Matrix($this->U, $this->m, min($this->m + 1, $this->n)); } /** * Return the right singular vectors * * @access public * @return V */ public function getV() { return new Matrix($this->V); } /** * Return the one-dimensional array of singular values * * @access public * @return diagonal of S. */ public function getSingularValues() { return $this->s; } /** * Return the diagonal matrix of singular values * * @access public * @return S */ public function getS() { for ($i = 0; $i < $this->n; ++$i) { for ($j = 0; $j < $this->n; ++$j) { $S[$i][$j] = 0.0; } $S[$i][$i] = $this->s[$i]; } return new Matrix($S); } /** * Two norm * * @access public * @return max(S) */ public function norm2() { return $this->s[0]; } /** * Two norm condition number * * @access public * @return max(S)/min(S) */ public function cond() { return $this->s[0] / $this->s[min($this->m, $this->n) - 1]; } /** * Effective numerical matrix rank * * @access public * @return Number of nonnegligible singular values. */ public function rank() { $eps = pow(2.0, -52.0); $tol = max($this->m, $this->n) * $this->s[0] * $eps; $r = 0; for ($i = 0; $i < count($this->s); ++$i) { if ($this->s[$i] > $tol) { ++$r; } } return $r; } } // class SingularValueDecomposition
Java
UTF-8
1,351
2.40625
2
[]
no_license
package com.qa.choonz.persistence.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Entity @Data @NoArgsConstructor @AllArgsConstructor public class Track { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Size(max = 100) @Column(unique = true) private String title; @OneToOne private Artist artist; @OneToOne private Genre genre; @ManyToOne private Album album; @ManyToOne private Playlist playlist; // in seconds private int duration; private String lyrics; public Track(Long id, @NotNull @Size(max = 100) String title) { super(); this.id = id; this.title = title; } public Track(@NotNull @Size(max = 100) String title) { super(); this.title = title; } public Track(@NotNull @Size(max = 100) String title, int duration, String lyrics) { super(); this.title = title; this.duration = duration; this.lyrics = lyrics; } }
Python
UTF-8
4,618
3.796875
4
[ "MIT" ]
permissive
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 渐渐用多了,才发现,整理的这些东西,并非是用来提供直接调用的。 主要是方便对于python各种数据类型的理解,方便用到什么的时候, 可以直接拿来作为参考 ''' # -------------- python3.6 ---------------------- ''' 1-3 主要涉及Hex,Bytes,List之间的相互转换 这里的Hex指的是诸如 str("313233414234") (即相当于是2个字符表示一位十六进制数据) 则可定Hex不能有[^0-9A-Fa-f]数据 4-6 涉及到str 诸如"Hello world哈哈" 则这种情况会涉及到转码问题encoding=utf-8等 ''' # 1.0 hex <--> bytes def hex2bytes(hh): ''' str("31323334") -> b"1234" ''' return bytes.fromhex(hh) def bytes2hex(bb): ''' b"1234" -> str("31323334") ''' return bb.hex() # 2.0 list <--> bytes def list2bytes(ll): ''' [0x31,0x32,0x33] -> b"123" ''' return bytes(ll) def bytes2list(bb): ''' b"123" -> [0x31,0x32,0x33] ''' return list(bb) # 3.0 list <--> hex def list2hex(ll): ''' [0x31,0x32,0x33] -> str("313233") ''' return bytes(ll).hex() def hex2list(hh): ''' str("313233") -> [0x31,0x32,0x33] ''' bb = bytes.fromhex(hh) return list(bb) # 4.0 str <--> list def str2list(ss): ''' str("123ABC") -> [0x31,0x32,0x33,0x41,0x42,0x43] str("我的世界")(本脚本为utf-8编码) -> [25105, 30340, 19990, 30028] (因为ord返回Unicode编码) ''' return [ord(c) for c in list(ss)] def list2str(ll): ''' [0x31,0x32,0x33,0x41,0x42,0x43] -> str("123ABC") ''' return ''.join([chr(i) for i in ll]) # 5.0 str <--> bytes def str2bytes(ss): ''' str("123ABC") -> b"123ABC" ''' return bytes(ss, encoding='utf-8') def bytes2str(bb): ''' b"123ABC" -> str("123ABC") ''' return str(bb, encoding='utf-8') # ... ''' 其他各种转换便不再多写了,主要是因为有以上一些接口, 对于实际应用的时候,用到什么,相互直接一调用也能实现各种数据之前的相互转化了。 以后若再扩展,则必定是更加简洁/高效...的方式 ''' def py36_str_hex_bytes_test(): # ------------------------------------------------------ ll = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] print('[list] {} \t {}'.format(type(ll),ll)) bb = list2bytes(ll) hh = list2hex(ll) print('[list2bytes] {} \t {}'.format(type(bb),bb)) print('[list2hex] {} \t {}'.format(type(hh),hh)) ll2 = bytes2list(bb) hh2 = bytes2hex(bb) print('[bytes2list] {} \t {}'.format(type(ll2),ll2)) print('[bytes2hex] {} \t {}'.format(type(hh2),hh2)) ll3 = hex2list(hh) bb2 = hex2bytes(hh) print('[hex2list] {} \t {}'.format(type(ll3),ll3)) print('[hex2bytes] {} \t {}'.format(type(bb2),bb2)) ll4 = str2list("我的世界") print('[str2list] {} \t {}'.format(type(ll4), ll4)) ss = list2str(ll4) print('[list2str] {} \t {}'.format(type(ss), ss)) bb4 = str2bytes(ss) print('[str2bytes] {} \t {}'.format(type(bb4), bb4)) ss4 = bytes2str(bb4) print('[bytes2str] {} \t {}'.format(type(ss4), ss4)) # 若想将汉字也转为list形式,可以相互调用实现 bb5 = str2bytes("我的世界") ll5 = bytes2list(bb5) print('[汉字2list] {} \t {}'.format(type(ll5), ll5)) # -------------- python2.7 ---------------------- def py27_bytes2hex(bb): b = bytes(bb) return b.encode('hex') def py27_hex2bytes(hh): return hh.decode('hex') def py27_list2bytes(ll): return bytearray(ll) def py27_bytes2list(bb): return list(bb) def py27_list2hex(ll): b = bytearray(ll) return bytes(b).encode('hex') def py27_hex2list(hh): s = hh.decode('hex') return list(bytearray(s)) def py27_str_hex_bytes_test(): # ------------------------------------------------------ ll = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38] print('[py27_list] {}'.format(ll)) bb = py27_list2bytes(ll) hh = py27_list2hex(ll) print('[py27_list2bytes] {}'.format(bb)) print('[py27_list2hex] {}'.format(hh)) ll2 = py27_bytes2list(bb) hh2 = py27_bytes2hex(bb) print('[py27_bytes2list] {}'.format(ll2)) print('[py27_bytes2hex] {}'.format(hh2)) ll3 = py27_hex2list(hh) bb2 = py27_hex2bytes(hh) print('[py27_hex2list] {}'.format(ll3)) print('[py27_hex2bytes] {}'.format(bb2)) py36_str_hex_bytes_test()
Java
UTF-8
3,703
3.890625
4
[]
no_license
package cs.homework1; /** * Comes up with the song to add in the PlayList. Including title, artist, * minutes, and seconds. * * Author Albert Cheng * AuthorID 113332562 * Recitation R30 * */ public class SongRecord { private String title; private String artist; private int minutes; private int seconds; /** * * @param title * Title of the SongRecord * @param artist * Artist of the SongRecord * @param minutes * Minutes of the SongRecord * @param seconds * Seconds of the SongRecord * @throws InvalidSecondException * Throws exception when seconds is greater than 60 or less than 0 * @throws InvalidMinuteException * Throws exception when minutes is less than 0 */ public SongRecord(String title, String artist, int minutes, int seconds) throws InvalidSecondException, InvalidMinuteException{ setTitle(title); setArtist(artist); setMinutes(minutes); setSeconds(seconds); } /** * Retrieves the title of the song * * @return returns * the title of the song */ public String getTitle() { return title; } /** * Sets the title of the song * * @param title * title this song will be set to */ public void setTitle(String title) { this.title = title; } /** * Retrieves the artist of the song * * @return * returns the artist of the song */ public String getArtist() { return artist; } /** * Sets the artist of the song * * @param artist * artist this song will be set to */ public void setArtist(String artist) { this.artist = artist; } /** * Retrieves the seconds of the song * * @return * returns the seconds of the song */ public int getSeconds() { return seconds; } /** * Sets the seconds of the song * * @param seconds * seconds this song will be set to * @throws InvalidSecondException * Invalid song length. Seconds must be between 0 and 60 other throw INvalidSecondException */ public void setSeconds(int seconds) throws InvalidSecondException { if (seconds < 60 && seconds > 0) { this.seconds = seconds; } else { throw new InvalidSecondException(); } } /** * Retrieves the minutes of the song * * @return * returns the minutes of the song */ public int getMinutes() { return minutes; } /** * Sets the minutes of the song * * @param minutes * minutes this song will be set to * @throws InvalidMinuteException * Must be greater than 0 otherwise throw InvalidMinuteException * throw InvalidMinuteException */ public void setMinutes(int minutes) throws InvalidMinuteException { if (minutes < 0) { throw new InvalidMinuteException(); } this.minutes = minutes; } /** * Returns the string representation of SongRecord * * @return * Returns the string representation of SongRecord */ public String toString() { return String.format("%-26s%-26s%20d:%02d", this.getTitle(), this.getArtist(), this.getMinutes(), this.getSeconds()); } /** * Checks if 2 PlayList are equal to each other. Title, artist, minutes, and seconds. * * @param obj * Obj to be compared to * * @return * Returns true if both SongRecord PlayList is equal * Returns false if both PlayList are not equal. */ public boolean equals(Object obj) { if(obj == null || !(obj instanceof SongRecord)) { return false; } SongRecord song = (SongRecord) obj; if (this.getTitle() == song.getTitle() && this.getArtist() == song.getArtist() && this.getMinutes() == song.getMinutes() && this.getSeconds() == song.getSeconds()) { return true; } else { return false; } } }
Swift
UTF-8
1,166
3.296875
3
[]
no_license
// // Expense.swift // BudgetApp // // Created by joe rho on 1/18/20. // Copyright © 2020 joe rho. All rights reserved. // import Foundation class Expense: Transaction { fileprivate var category_raw: String init(id: Int64? = nil, description: String = "", date: String = "", amount: Int = 0, category: String = Category.misc.rawValue, repeats: String = RepeatFrequency.never.rawValue) { self.category_raw = category super.init(id: id, description: description, date: date, amount: amount, repeats: repeats) } } // MARK: - Category extension Expense { enum Category: String { case misc = "Misc." case food = "Food 🍖" case transportation = "Transportation 🚗" case housing = "Housing 🏠" case utilities = "Utilities 🚰" case personal = "Personal 👑" case entertainment = "Entertainment 🏌️‍♂️" } } // MARK: - Computed Variables extension Expense { var category: Category { get{ return Category(rawValue: self.category_raw)! } set { self.category_raw = newValue.rawValue } } }
Python
UTF-8
1,772
3.578125
4
[]
no_license
from sklearn.model_selection import train_test_split from typing import Optional, Tuple, Dict import pandas as pd def fetch_csv_data(url: str, separator: Optional[str]) -> pd.DataFrame: """ This functions fetch the CSV data from a given path (or url) and returns a Pandas DataFrame. :param url: a string containing the address of the data (local path, url ...) :param separator: an optional separator to override the default separator (comma) :return: a Pandas Dataframe containing the loaded data """ try: args = dict(filepath_or_buffer=url) if separator: args.update(sep=separator) return pd.read_csv(**args) except Exception as e: raise Exception(f'Error while fetching data at url {url}: {e}') def build_train_test_sets(data: pd.DataFrame, label_col: str, train_size: float) -> \ Dict[str, Tuple[pd.DataFrame, pd.DataFrame]]: """ A function to split the data into training and test sets. :param data: a pandas dataframe :param label_col: the label column name :param train_size: float. The fraction of the whole dataset used for training. :return: a Dictionary of key (string) - value (tuple of pandas dataframes) containing training and test data. Dictionary keys: - train: contains (train_x, train_y) - test: contains (test_x, test_y """ try: train, test = train_test_split(data, train_size=train_size) x_y = lambda _data: (_data.drop([label_col], axis=1), _data[[label_col]]) train_x, train_y = x_y(train) test_x, test_y = x_y(test) return dict(train=(train_x, train_y), test=(test_x, test_y)) except Exception as e: raise Exception(f'Error while splitting data: {e}')
Python
UTF-8
512
3.390625
3
[]
no_license
from node import Node class GridNode(Node): """Modification of Node to only have four cardinal neighbors and store location.""" def __init__(self, x=0, y=0): self.x, self.y = x, y Node.__init__(self, (x, y)) def is_neighbor(self, other): if self == other: return False if self.x == other.x and abs(self.y - other.y) == 1: return True if self.y == other.y and abs(self.x - other.x) == 1: return True return False
Markdown
UTF-8
1,951
2.96875
3
[ "MIT" ]
permissive
--- layout: text/textblock --- Content authors should use the main content section of the template to write. The template also allows anyone involved in creating content to: - have context of the content and the user’s need - provide a checklist for reviewers, according to expertise - guide those not experienced in writing for the web ### [2]Page details Sets out the site location of the page and content type. Complete this section first and include important details such as go-live date and the content’s status. ### [2]Content planning Anyone can complete this section from their preparation of what the user needs to do or find. This helps everyone using the template to know the content’s objective. ### [2]Quality content checks Relevant experts use these checks to review the content for quality. Each expert can complete as done, or make notes for any changes. - subject expert — factual accuracy and relevance - product owner — product objectives - legal — legislative requirement - content or subject expert — metadata - content expert — readability and quality - content expert or publisher — accessibility - publishers — product owner and publisher ### [2]Main content area The content author, whether subject expert or content expert, to set out the content for the web page. ### [2]Priority 2 content The content author to complete for any callout content. ### [2]Priority 3 content Content author to complete any relevant related links and contact details. ### [2]Writing tips - The first sentence sets an expectation for what’s on the page. - Your main content contains your key message or user need. - Use a heading hierarchy (H1, H2, H3) to signpost the user’s journey through the page. - Use text that describes the link including the URL in brackets. - Add a call-to-action so that the user knows what to do. - Use steps or bullet points for instructions. - Use header rows for tables.
C++
UTF-8
6,124
3.046875
3
[]
no_license
#include <iostream> #include <variant> #include <string> #include <vector> #include <unordered_set> #include <fstream> #include <utility> #include <algorithm> #include <map> using namespace std; enum class SleepEvent { Wake, Sleep }; struct Event { long timestamp; variant<int, SleepEvent> info; }; string remove_all_from_string(const unordered_set<char>& chars_to_remove, const string& s) { string string_with_chars_removed {}; for (auto c : s) { if (chars_to_remove.count(c) == 0) string_with_chars_removed += c; } return string_with_chars_removed; } Event parse_line_into_event(string line) { int timestamp_start = line.find('[') + 1; int timestamp_end = line.find(']'); string timestamp_string = remove_all_from_string(unordered_set<char> { '-', ':', ' '}, line.substr(timestamp_start, timestamp_end - timestamp_start)); long timestamp = stol(timestamp_string); string info_string = line.substr(timestamp_end + 1); auto found_in_string = info_string.find("wake"); if (found_in_string != string::npos) return Event { timestamp, SleepEvent::Wake }; found_in_string = info_string.find("sleep"); if (found_in_string != string::npos) return Event { timestamp, SleepEvent::Sleep }; found_in_string = info_string.find("#"); string id_string {}; for (int i = found_in_string + 1; info_string[i] != ' '; ++i) id_string += info_string[i]; int id = stoi(id_string); return Event { timestamp, id }; } int compute_id_with_most_minutes_slept(const vector<Event>& events) { map<int, int> id_to_minutes_slept; int current_most_minutes = 0; int current_most_minutes_id = 0; int event_index = 0; Event current_event; while (event_index < events.size()) { int minutes = 0; // Get current, which will tell us the id current_event = events[event_index]; int next_sleep_index = event_index + 1; int next_wake_index = event_index + 2; Event next_sleep = events[next_sleep_index]; Event next_wake = events[next_wake_index]; if (holds_alternative<int>(next_sleep.info)) event_index++; else { while (holds_alternative<SleepEvent>(next_wake.info) && get<SleepEvent>(next_wake.info) == SleepEvent::Wake) { minutes += (next_wake.timestamp - next_sleep.timestamp - 1); event_index = next_wake_index + 1; next_sleep_index = next_wake_index + 1; next_wake_index = next_wake_index + 2; next_sleep = events[next_sleep_index]; next_wake = events[next_wake_index]; } if (id_to_minutes_slept.count(get<int>(current_event.info)) != 0) id_to_minutes_slept[get<int>(current_event.info)] += minutes; else id_to_minutes_slept.emplace(get<int>(current_event.info), minutes); if (id_to_minutes_slept.at(get<int>(current_event.info)) > current_most_minutes) { current_most_minutes = id_to_minutes_slept.at(get<int>(current_event.info)); current_most_minutes_id = get<int>(current_event.info); } } } return current_most_minutes_id; } pair<int, int> determine_most_common_minute_slept_for_id(int id, const vector<Event>& events) { int hour[59] {}; int event_index = 0; Event current_event; while (event_index < events.size()) { current_event = events[event_index]; if (holds_alternative<int>(current_event.info) && get<int>(current_event.info) == id) { int next_sleep_index = event_index + 1; int next_wake_index = event_index + 2; Event next_sleep = events[next_sleep_index]; Event next_wake = events[next_wake_index]; while (holds_alternative<SleepEvent>(next_wake.info) && get<SleepEvent>(next_wake.info) == SleepEvent::Wake) { string next_sleep_string = to_string(next_sleep.timestamp); string next_wake_string = to_string(next_wake.timestamp); int lower_bound = stoi(next_sleep_string.substr(next_sleep_string.size() - 2)); int upper_bound = stoi(next_wake_string.substr(next_wake_string.size() - 2)); for (int i = lower_bound; i < upper_bound; ++i) hour[i]++; event_index = next_wake_index + 1; next_sleep_index = next_wake_index + 1; next_wake_index = next_wake_index + 2; next_sleep = events[next_sleep_index]; next_wake = events[next_wake_index]; } } event_index++; } int current_max = 0; int current_max_index = 0; for (int i = 0; i < 59; ++i) { if (hour[i] > current_max) { current_max = hour[i]; current_max_index = i; } } return make_pair(current_max_index, current_max); } pair<int, int> compute_id_with_most_sleeps_on_a_minute(const vector<Event>& events) { unordered_set<int> processed_ids {}; int current_highest_sleeps = 0; int minute_with_highest_sleeps = 0; int current_highest_sleeps_id = 0; for (auto e : events) { if (holds_alternative<int>(e.info) && processed_ids.count(get<int>(e.info)) == 0) { int id = get<int>(e.info); processed_ids.emplace(id); pair<int, int> minute_and_id = determine_most_common_minute_slept_for_id(id, events); int highest_sleeps_for_id = minute_and_id.second; if (current_highest_sleeps < highest_sleeps_for_id) { current_highest_sleeps = highest_sleeps_for_id; minute_with_highest_sleeps = minute_and_id.first; current_highest_sleeps_id = id; } } } return make_pair(current_highest_sleeps_id, minute_with_highest_sleeps); } int main(int argc, char* argv[]) { if (argc < 2) cout << "Usage: ./a.out input.txt" << endl; ifstream events_file { argv[1] }; string line; vector<Event> events {}; while (getline(events_file, line)) { events.push_back(parse_line_into_event(line)); } // sort based on timestamp sort(events.begin(), events.end(), [](Event a, Event b) { return a.timestamp < b.timestamp; }); int sleepiest_id = compute_id_with_most_minutes_slept(events); cout << "Sleepy Id: " << sleepiest_id << " Sleepiest minute: " << determine_most_common_minute_slept_for_id(sleepiest_id, events).first << endl; pair<int, int> id_and_highest = compute_id_with_most_sleeps_on_a_minute(events); cout << "Id: " << id_and_highest.first << " Minute: " << id_and_highest.second << endl; return 0; }
C#
UTF-8
4,144
3.453125
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BinPacker { public sealed class Program { public static void Main(string[] args) { if (args.Length != 3) { PrintHelp(); return; } var path = args[0]; var numberOfBins = Convert.ToInt32(args[1]); var numberOfBytes = Convert.ToInt32(args[2]); var bins = InitializeBins(numberOfBins, numberOfBytes); List<Item> items = ParseCsv(path); try { AllocateItemsToBins(bins, items); } catch (Exception e) { Console.WriteLine(e.Message); return; } PrintBinContents(bins); Console.ReadKey(); } private static void PrintHelp() { Console.WriteLine("Usage: BinPacker \"path\to\file\" #ofBins"); Console.WriteLine("\te.g. BinPacker \"c:\\csv_listing.txt\" 15"); } private static Bin[] InitializeBins(int numberOfBins, int numberOfBytes) { var bins = new Bin[numberOfBins]; for (int i = 0; i < numberOfBins; i++) { bins[i] = new Bin(numberOfBytes); } return bins; } /// <summary> /// Parse the CSV file in format "length in bytes, name" into a List of Item objects /// </summary> private static List<Item> ParseCsv(string path) { var sizeToNameMap = File.ReadAllLines(path); var items = new List<Item>(sizeToNameMap.Length); foreach (var line in sizeToNameMap) { string[] tuple = line.Split(','); var item = new Item(); item.Size = Convert.ToDouble(tuple[0]); item.Name = tuple[1].Trim(); items.Add(item); } return items; } /// <summary> /// Longest Processing Time algorith (from scheduling theory): /// Sort the items by their processing time and then assigns them to the bin with the lowest fill level so far /// </summary> private static void AllocateItemsToBins(Bin[] bins, List<Item> items) { if (bins == null || bins.Length < 1) throw new ArgumentException("The bins array may not be null or empty", "bins"); if(items == null) throw new ArgumentException("The list of items cannot be uninitialized", "sortedItems"); List<Item> sortedItems = items.OrderByDescending(x => x.Size).ToList(); foreach (var item in sortedItems) { Bin bin = FindLeastFilledBin(bins, item.Size); bin.Fill += item.Size; bin.Items.Add(item); } } private static Bin FindLeastFilledBin(Bin[] bins, double itemSize) { if (bins == null || bins.Length < 1) throw new ArgumentException("The bins array may not be null or empty", "bins"); var candidate = bins.OrderBy(x => x.Fill).First(); if (candidate.Fill + itemSize > candidate.Size) throw new Exception("There are not enough bins to hold all the items"); return candidate; } private static void PrintBinContents(Bin[] bins) { if (bins == null || bins.Length < 1) return; for (int i = 0; i < bins.Length; i++) { var header = string.Format("Bin #{0} ({1}%)", i + 1, Math.Round(bins[i].Fill / bins[i].Size * 100, 1)); Console.WriteLine(header); foreach (var item in bins[i].Items) { Console.WriteLine("\t" + item.Name); } } } } }
C#
UTF-8
6,094
2.703125
3
[]
no_license
/// <summary> /// LOSocket. /// Created By 蓝鸥3G 2014.08.23 /// https://www.cnblogs.com/daxiaxiaohao/p/4402063.html /// </summary> /// /// using UnityEngine; using System.Collections; using System.Net; using System.Net.Sockets; using System.Text; //收到消息后的委托回调 public delegate void ReceiveCallBack(string content); public class TcpSocket{ //可以创建的Socket端口类型 public enum LOSocketType { CLIENT = 0, SERVER = 1, } #region --------取消构造器 private TcpSocket() { } #endregion #region --------公共代码 //通过静态方法获取不同的端口类型 public static TcpSocket GetSocket(TcpSocket.LOSocketType type) { TcpSocket socket = null; switch (type) { case LOSocketType.CLIENT: { //创建一个新的客户端 socket = new TcpSocket (); break; } case LOSocketType.SERVER: { //获取服务端 socket = GetServer (); break; } } return socket; } #endregion #region --------客户端部分代码 private Socket clientSocket; //声明客户端收到服务端返回消息后的回调委托函数 private ReceiveCallBack clientReceiveCallBack; //用来存储服务端返回的消息数据 byte[] Buffer = new byte[1024]; //初始化客户端Socket信息 public void InitClient(string ip,int port,ReceiveCallBack ccb) { this.clientReceiveCallBack = ccb; this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse (ip); IPEndPoint ep = new IPEndPoint (address, port); this.clientSocket.Connect(ep); //开始异步等待接收服务端消息 this.clientSocket.BeginReceive (Buffer, 0, Buffer.Length, SocketFlags.None, new System.AsyncCallback(ReceiveFromServer), this.clientSocket); } //收到服务端返回消息后的回调函数 void ReceiveFromServer(System.IAsyncResult ar) { //获取当前正在工作的Socket对象 Socket worker = ar.AsyncState as Socket; int ByteRead=0; try { //接收完毕消息后的字节数 ByteRead = worker.EndReceive(ar); } catch (System.Exception ex) { this.clientReceiveCallBack (ex.ToString ()); } if (ByteRead > 0) { string Content = Encoding.Default.GetString (Buffer); //通过回调函数将消息返回给调用者 this.clientReceiveCallBack (Content); } //继续异步等待接受服务器的返回消息 worker.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new System.AsyncCallback(ReceiveFromServer), worker); } //客户端主动发送消息 public void SendMessage(string message) { if (message == null) return; message += "\r\n"; byte[] sendData = Encoding.UTF8.GetBytes (message); //异步发送消息请求 clientSocket.BeginSend (sendData, 0, sendData.Length, SocketFlags.None, new System.AsyncCallback (SendToServer), clientSocket); } //发送消息结束的回调函数 void SendToServer(System.IAsyncResult ar) { Socket worker = ar.AsyncState as Socket; worker.EndSend (ar); } #endregion #region -------服务器部分代码 //服务器端收到消息的存储空间 byte[] ReceiveBuffer = new byte[1024]; //服务器收到消息后的回调委托 private ReceiveCallBack callback; //单例模式 private static TcpSocket serverSocket; private static TcpSocket GetServer() { if (serverSocket == null) { serverSocket = new TcpSocket(); } return serverSocket; } //初始化服务器信息 public void InitServer(ReceiveCallBack cb) { this.callback = cb; // 1. Socket server_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 2. IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 2222); // 3. server_socket.Bind(endPoint); // 4. server_socket.Listen(10); // 5.开始异步等待客户端的请求链接 server_socket.BeginAccept (new System.AsyncCallback (Accept), server_socket); this.callback ("开启服务器" + endPoint.ToString()); } //接受到客户端的链接请求后的回调函数 void Accept(System.IAsyncResult ar){ //获取正在工作的Socket对象 Socket socket = ar.AsyncState as Socket; //存储异步操作的信息,以及用户自定义的数据 Socket worker = socket.EndAccept(ar); SocketError error; //开始异步接收客户端发送消息内容 worker.BeginReceive (ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, new System.AsyncCallback (Receive), worker); //继续异步等待新的客户端链接请求 socket.BeginAccept(new System.AsyncCallback(Accept), socket); } //服务端收到客户端的消息后的回调函数 void Receive(System.IAsyncResult ar) { //获取正在工作的Socket对象 Socket worker = ar.AsyncState as Socket; int ByteRead=0; try { ByteRead = worker.EndReceive(ar); } catch (System.Exception ex) { this.callback (ex.ToString ()); } if (ByteRead > 0) { string Content = Encoding.Default.GetString (ReceiveBuffer); this.callback (Content); } //继续异步等待客户端的发送消息请求 worker.BeginReceive(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, new System.AsyncCallback(Receive), worker); } #endregion }
C++
UTF-8
1,204
3.015625
3
[]
no_license
#include <iostream> #include <memory> #include <unistd.h> #include "../Include/Utils.h" #include "../Include/ProgramInfo.h" #include "../Include/Debugger.h" TinyDBG::ProgramInfo ParseArguments(size_t argc, char **argv) noexcept { TinyDBG::ProgramInfo program{}; program.name = argv[1]; program.arguments_n = argc - 2; program.arguments = std::make_unique<std::string[]>(argc - 2); for (size_t i = 2U; i < argc; ++i) { program.arguments[i - 2] = argv[i]; } return program; } int main(int argc, char **argv) { if (argc < 2) { std::cerr << "You must provide more arguments!" << std::endl; exit(EXIT_FAILURE); } TinyDBG::ProgramInfo programInfo = ParseArguments(static_cast<size_t>(argc), argv); pid_t pid = fork(); if (pid == 0) { // Child process TinyDBG::Utils::RegisterTrace(); TinyDBG::Utils::ExecuteProgram(programInfo); } else if (pid > 0) { // parent process TinyDBG::Debugger dgb{programInfo, pid}; dgb.Run(); } else { std::cerr << "Error while creating the new process. Terminating..." << std::endl; exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
C
UTF-8
2,173
2.90625
3
[]
no_license
#include <math.h> #include <stdlib.h> #include <string.h> #include "newton.h" #include "myinterp.h" void addPoly(my_interp * a, my_interp * b){ if(a->size == b->size) { int i = a->size; while(i--) { a->coeff[i] += b->coeff[i]; } } } my_interp * copy(my_interp * p){ my_interp * ret = my_interp_alloc(p->T, p->size); int i = p->size; while(i--) { ret->coeff[i] = p->coeff[i]; } return ret; } void mulmono(my_interp * p, double c){ int i= p->size; my_interp * cpy = copy(p); while(i-- > 1){ p->coeff[i] = c * cpy->coeff[i]; p->coeff[i] += cpy->coeff[i-1]; } p->coeff[0] = c * cpy->coeff[0]; } void mulc(my_interp * p, double c){ int i = p->size; while(i--) { p->coeff[i] *= c; } } void newton(const double * x, const double * y, int num, my_interp * p) { int roots = p->size; int i = roots; int j = roots; double ** tab = malloc(roots * sizeof(double*)); while(j--) { tab[j] = malloc( (j+1)* sizeof(double) ); } j=roots; while(j--) { tab[j][0] = y[j]; } j=1; while(j < roots) { int k=1; while(k <= j) { tab[j][k] = (tab[j][k-1]-tab[j-1][k-1]) / (x[j] - x[j-k]); k++; } j++; } my_interp * tmp = my_interp_alloc(p->T, p->size); my_interp * n = my_interp_alloc(p->T, p->size); n->coeff[0]=1; i=0; while(i < roots) { my_interp * m = copy(n); mulc(n, tab[i][i]); addPoly(tmp, n); j = roots; n = m; mulmono(n, -x[i]); i++; } i = roots; while(i--) { p->coeff[i] = tmp->coeff[i]; } my_interp_free(tmp); my_interp_free(n); } int newton_interp_init(my_interp * interp, const double * xs, const double * ys, size_t size) { newton(xs, ys, size, interp); return 0; } double newton_interp_eval(const my_interp * interp, double x) { double res = 0.; int i = interp->size - 1; while(i < interp->size) { res = res * x + interp->coeff[i]; i--; } return res; }
Java
UTF-8
618
2.984375
3
[]
no_license
//https://leetcode.com/problems/course-schedule-iii/ // 3rd May class Solution { public int scheduleCourse(int[][] courses) { PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->b-a); Arrays.sort(courses,(a,b)->a[1]-b[1]); int time = 0; int i=0; int n = courses.length; while(i<n){ time+=courses[i][0]; pq.add(courses[i][0]); if(time>courses[i][1]){ int temp = pq.poll(); time-=temp; } i++; } return pq.size(); } }
Python
UTF-8
4,126
2.546875
3
[]
no_license
import pyrebase import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import os import requests import json import pyrebase import firebase_admin import random from flask import Flask, request, jsonify, make_response from yelp.client import Client from bussiness import distance_calculator MY_API_KEY = "b7wSeZeFykMFbPx-n7VpQD9gwi8EZWYYjaPEoa3ExSZv5c4LlGpANEhKR-sUW51218X6M3RO6t90tQGvbBAcX7pP9A3KnEo8FRfYZ1t1efZ_SXvj7POdAmmyqptTXnYx" client = Client(MY_API_KEY) if (not len(firebase_admin._apps)): cred = credentials.Certificate('./confidential.json') default_app = firebase_admin.initialize_app(cred) db = firestore.client() endpoint = "https://api.yelp.com/v3/businesses/search" header = {'Authorization': 'bearer %s' % MY_API_KEY} data = {"userId" : "PUGAMfSoEZgvT2C9mthlpOmTo453", "date": {}, "price": {"$": "false", "$$": "true", "$$$": "false"}, "time": {"h": "1", "m": "15", "a": "pm"}, "duration": 7 } def makeDay(data): userId = data["userId"] snapshot = db.collection('users').document(userId) doc_ref = snapshot.get() doc_items = doc_ref.to_dict() old_names = doc_items["usedBusinesses"] restaurants = [] activities = [] for cuisine in doc_items["food"]: restaurant_info = yelp_business_info(cuisine, old_names) restaurants.append(restaurant_info) for activity in doc_items["activities"]: activity_info = yelp_business_info(activity, old_names) activities.append(activity_info) plannedDay = arrange_in_order(restaurants, activities, data["duration"]) outputedNames = plannedDay.values() usedBusinessNames = [] for name in outputedNames: usedBusinessNames.append(name[0]) usedBusinessNames = usedBusinessNames[:-1] + old_names snapshot.set({"usedBusinesses": usedBusinessNames}, merge=True) return(plannedDay) def yelp_business_info(tag, old_names): yelp_business_names = {} parameters = {'term': tag, 'location': 'Dublin'} response = requests.get(url=endpoint, params=parameters, headers=header) business_data = response.json() for business in business_data['businesses']: if business['name'] not in old_names: yelp_business_names[business['name']] = { 'location' : business['coordinates'], 'url' : business['url'], 'tag' : tag} if len(yelp_business_names) == 0: return "none found" return yelp_business_names def arrange_in_order(restaurants, activities, duration): day = {} times = [0] if duration >= 6: restaurant_counter = 2 elif duration >= 3: restaurant_counter = 1 else: restaurant_counter = 0 activity_by_option = random.choice(activities) activity = activity_by_option.popitem() day[0] = activity for event_number in range(1, duration): if event_number % 2 == 0 and event_number != 0 and restaurant_counter != 0: restaurant_by_cuisine = random.choice(restaurants) restaurant = restaurant_by_cuisine.popitem() last_event_location = str(day[event_number - 1][1]['location']['longitude']), str(day[event_number - 1][1]['location']['latitude']) time = distance_calculator(last_event_location[0], last_event_location[1], str(restaurant[1]['location']['longitude']), str(restaurant[1]['location']['latitude'])) times.append(time) day[event_number] = restaurant restaurant_counter -= 1 else: activity_by_option = random.choice(activities) activity = activity_by_option.popitem() last_event_location = str(day[event_number - 1][1]['location']['longitude']), str(day[event_number - 1][1]['location']['latitude']) time = distance_calculator(last_event_location[0], last_event_location[1], str(activity[1]['location']['longitude']), str(activity[1]['location']['latitude'])) times.append(time) day[event_number] = activity day["times"] = times return day #print(makeDay(data))
Java
UTF-8
750
1.796875
2
[]
no_license
package com.springboot.microservice.ccyconversion.services; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.io.Serializable; import java.math.BigDecimal; /** * CurrencyConversionBean * * @author "Andrei Prokofiev" */ @Data @AllArgsConstructor //@Service @NoArgsConstructor public class CurrencyConversionBean implements Serializable { // static final long SerialVersionUID = -4862926644813433707L; private Long id; private String from; private String to; private BigDecimal conversionMultiple; private BigDecimal quantity; private BigDecimal multiply; private int port; }
JavaScript
UTF-8
1,332
2.609375
3
[]
no_license
// During the test the env variable is set to test process.env.NODE_ENV = "test"; const { expect } = require("chai"); const mongoose = require("mongoose"); const MongoMemoryServer = require("mongodb-memory-server"); const { guid } = require("./guid"); let mongoServer; before(done => { mongoServer = new MongoMemoryServer.default({ /* debug: true, */ }); mongoServer .getConnectionString() .then(mongoUri => mongoose.connect(mongoUri, { useNewUrlParser: true }, err => { if (err) done(err); }) ) .then(() => done()); }); after(() => { mongoose.disconnect(); mongoServer.stop(); }); describe("guid util", () => { it("isGuid - Pass valid guid - Must be valid", async () => { // Arrange const guidValue = guid.new(); // Act & Assert expect(guid.isGuid(guidValue)).to.be.true; }); it("new - Calls for a new guid - Must be valid and always different", async () => { // Arrange const usedGuid = []; let guidValue; for (let i = 0; i < 50; i += 1) { guidValue = guid.new(); // Act & Assert expect(guid.isGuid(guidValue)).to.be.true; expect(usedGuid).does.not.include( guidValue.toString(), "Guid must not be repeated" ); // Arrange usedGuid.push(guidValue.toString()); } }); });
Markdown
UTF-8
1,839
2.59375
3
[ "Apache-2.0" ]
permissive
# IOTA-Timestamping ## Overview Iota-Timestamping is a Rest API that can be used to create and retrieve timestamps from a public ledger. It uses the cryptocurrency IOTA to achieve this free of cost. You can find the documentation [here](https://github.com/GabrielScheibler/iota-timestamping/wiki). ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development purposes. See deployment for notes on how to deploy the project on a live system. ### Prerequisites - maven 3.3.9 or newer - <code>sudo apt-get install maven</code> (on ubuntu) - java jdk 1.8 or newer - <code>sudo apt-get install openjdk-8-jdk</code> (on ubuntu) - git 2.7.4 or newer - <code>sudo apt-get install git</code> (on ubuntu) ### Installing - clone the repository - <code>sudo git clone https://github.com/GabrielScheibler/iota-timestamping.git iota-timestamping</code> - change into cloned iota-timestamping directory - <code>sudo cd iota-timestamping</code> - compile using maven - <code>sudo mvn compile</code> - build jar - <code>sudo mvn package</code> - run jar - <code>sudo java -jar target/iota-timestamping-1.0.jar</code> ## Deployment Run the jar file from before: <code>java -jar iota-timestamping-1.0.jar</code> You can specify the port, the api should run on via <code>--server.port=8181</code>. By default it is 8080. The port and other properties can also be specified in the .properties files within the .jar file. ## Built With - Maven - Dependency Management - SpringBoot - Framework ## Authors - Gabriel Scheibler See also the list of [contributors](https://github.com/GabrielScheibler/iota-timestamping/graphs/contributors) who participated in this project. ## License This project is licensed under the Apache License 2.0 - see the [LICENSE.md](LICENSE) file for details
JavaScript
UTF-8
1,812
2.78125
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "MIT" ]
permissive
$(document).ready(function () { procAdStats(); }); function procAdStats() { $('#adStat').find('.sparkline').each(function () { var url = $(this).attr('data-url'); var e = $(this); if (url) { $.ajax({ url: url, type: 'get', dataType: 'json', success: function (data) { var vals = consumeJSONData(data); e.sparkline(vals, { type: 'line', width: '100%', height: '65', lineColor: 'rgba(255,255,255,0.4)', fillColor: 'rgba(0,0,0,0.2)', lineWidth: 1.25 }); } }); } }); $('#adStat').find('.stat-chart').each(function () { var target = $(this).find('h2'); var toAnimate = target.attr('data-value'); // Animate the element's value from x to y: $({someValue: 0}).animate({someValue: toAnimate}, { duration: 1000, easing: 'swing', // can be anything step: function () { // called on every step // Update the element's text with rounded-up value: target.text(commaSeparateNumber(Math.round(this.someValue))); } }); function commaSeparateNumber(val) { while (/(\d+)(\d{3})/.test(val.toString())) { val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); } return val; } }); } function consumeJSONData(sparkData) { var i = 0; var vals = new Array(); for (var key in sparkData) { vals[i++] = parseInt(sparkData[key]); } return vals; }
Java
UTF-8
863
2.21875
2
[]
no_license
package com.example.demo.dao; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import com.example.demo.model.HelloModel; @Component public class HelloDAO { @Autowired private JdbcTemplate jdbcTemplate; public void find() { jdbcTemplate.query(this.getSQL(), this.getMapper()); } private String getSQL() { return ""; } private RowMapper<HelloModel> getMapper() { RowMapper<HelloModel> mapper = new RowMapper<HelloModel>() { public HelloModel mapRow(ResultSet rs, int rowNum) throws SQLException { HelloModel model = new HelloModel(); return model; } }; return mapper; } }
Markdown
UTF-8
3,479
2.921875
3
[]
no_license
# 一、Vim是什么? **Vim** 是从 [vi](https://zh.wikipedia.org/wiki/Vi "Vi") 发展出来的一个 [文本编辑器](https://zh.wikipedia.org/wiki/%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8 "文本编辑器")。其代码补完、编译及错误跳转等方便编程的功能特别丰富,在程序员中被广泛使用。和 [Emacs](https://zh.wikipedia.org/wiki/Emacs "Emacs") 并列成为 [类 Unix 系统](https://zh.wikipedia.org/wiki/%E7%B1%BBUnix%E7%B3%BB%E7%BB%9F "类Unix系统")用户最喜欢的编辑器。 Vim 的第一个版本由[布莱姆・米勒](https://zh.wikipedia.org/wiki/%E5%B8%83%E8%90%8A%E5%A7%86%C2%B7%E7%B1%B3%E5%8B%92 "布莱姆·米勒")在 1991 年发布。最初的简称是 **V**i **IM**itation,随着功能的不断增加,正式名称改成了 **V**i **IM**proved。现在是在[开放源代码](https://zh.wikipedia.org/wiki/%E5%BC%80%E6%94%BE%E6%BA%90%E4%BB%A3%E7%A0%81 "开放源代码")方式下发行的[自由软件](https://zh.wikipedia.org/wiki/%E8%87%AA%E7%94%B1%E8%BD%AF%E4%BB%B6 "自由软件")。 当前,VIM 是按照 VIM 许可证发布的开源软件,这个协议兼容 [GPL](https://zh.wikipedia.org/wiki/GPL "GPL")。[[1]](https://zh.wikipedia.org/wiki/Vim#cite_note-Vim%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC%E4%B8%8E%E5%AF%B9GPL%E7%9A%84%E5%85%BC%E5%AE%B9%E6%80%A7-4) 它的协议中包含一些慈善条款,建议用户向 [荷兰](https://zh.wikipedia.org/wiki/%E8%8D%B7%E5%85%B0 "荷兰") [ICCF](https://zh.wikipedia.org/w/index.php?title=ICCF&action=edit&redlink=1 "ICCF(页面不存在)") 捐款,用于帮助 [乌干达](https://zh.wikipedia.org/wiki/%E4%B9%8C%E5%B9%B2%E8%BE%BE "乌干达")的[艾滋病](https://zh.wikipedia.org/wiki/%E8%89%BE%E6%BB%8B%E7%97%85 "艾滋病")患者。VIM 启动时会显示「**Help poor children in Uganda!**」的字样,在中文版本中则是「**请帮助乌干达的可怜孩童!**」。 # 二、为什么要学习Vim? ## 优点 - 速度快 - 拓展能力强【[https://vimawesome.com/](https://vimawesome.com/)插件成千上万】 - IDE很多都带有Vim的插件 所以我们只需要学习Vim的**编辑模式**就可以应对各种环境了 我个人不太推荐大型项目使用**Vim编辑器**来开发,但是支持你在IDE里面安装**Vim插件**支持来开发 Vim对我来说贵在的是它的编辑模式,而不是软件它本身,所以我们不要本末倒置,不要一味地追求Vim的全能,是我们玩Vim,而不是Vim在玩我们 ## 缺点 * 大文件读取速度很慢(可在 vim.org 下载并安装名为 LargeFile 的 Script 来优化)[LargeFile](http://www.vim.org/scripts/script.php?script_id=1506) * 即使文件不大,如果有非常长的行的话,处理也会变慢(同上) * vim 自己的脚本语言处理速度不快,若是安插过多脚本包,引导速度会变慢。 * 存在类似 Ctrl-1 等不能被映射的键(限于某些字符终端的性能) # 三、如何学习Vim? 虽然对新手不太友好,但是入门了之后真香,所以希望新手们能坚持 - [Vim快捷键大全](https://itgoyo.github.io/2018/02/09/Vim%E5%B8%B8%E7%94%A8%E5%BF%AB%E6%8D%B7%E9%94%AE%E5%A4%A7%E5%85%A8/) !!!推荐:先过2遍 - [Vim游戏:大冒险](https://vim-adventures.com/) 先熟悉方向键 - [Vim参考手册](http://vimcdoc.sourceforge.net/doc/help.html) - 视频入门教程 - 《Vim实用技巧》等进阶的书籍 - 自己日常在**项目**和**生活**中的使用
Ruby
UTF-8
1,102
3.4375
3
[]
no_license
## Memento ## # ブラックジャックを行うプレイヤーがいるとする #+BEGIN_SRC class Player attr_accessor :cards def initialize @cards = [] end def take @cards << rand(1..13) end def score @cards.sum end end #+END_SRC # 5回カードを引くゲームを3回行うと全部21を越えてしまった #+BEGIN_SRC 3.times do player = Player.new 5.times { player.take } player.score # => 33, 45, 28 end #+END_SRC # そこで Memento パターンを使う #+BEGIN_SRC class Player def create_memento @cards.clone end def restore_memento(object) @cards = object.clone end end #+END_SRC # 21点未満の状態を保持しておき21を越えたら元に戻す #+BEGIN_SRC 3.times do player = Player.new memento = nil 5.times do player.take if player.score < 21 memento = player.create_memento elsif player.score > 21 player.restore_memento(memento) end end player.score # => 20, 20, 19 end #+END_SRC # memento には復元に必要なものだけ入れとく
JavaScript
UTF-8
738
3.640625
4
[]
no_license
// link to the problem: http://judge.telerikacademy.com/problem/27maxsuminmatrix let dimensions = gets().split(' ').map(Number); let arr = []; for (let i = 0; i < dimensions[0]; i += 1) { const currentRow = gets().split(' ').map(Number); arr.push(currentRow); } let max = -Infinity; let count = 0; for (let row = 0; row < arr.length - 2; row += 1) { for (let col = 0; col < arr[row].length - 2; col += 1) { count = arr[row][col] + arr[row][col + 1] + arr[row][col + 2] + arr[row + 1][col] + arr[row + 1][col + 1] + arr[row + 1][col + 2] + arr[row + 2][col] + arr[row + 2][col + 1] + arr[row + 2][col + 2]; if (count > max) { max = count; } } } print(max);
JavaScript
UTF-8
2,429
3.578125
4
[]
no_license
var userBalance = 0; var lastClick = 0; var timeArray = [0]; // Gets called whenever the money finished tweening to the bottom. function addFromCatch(value) { timeArray.unshift(lastClick); var timeBetween = timeArray[0] - timeArray[1]; var delay = 2000 - timeBetween; setTimeout(function() { userBalance += value; updateBalance(userBalance); }, delay); } // Gets called every frame. // Time elapsed since the last update is passed into the function(milliseconds) function onUpdate({ delta }) { lastClick += delta; } function processSlots(input) { let chain = []; for (var i = 0; i < input.length; i++) { for (var j = 0; j < input[i].length; j++) { console.log(input[i][j]); let firstCheck = input[i][j]; let index1 = input[i][j + 1]; let index2 = input[i][j + 2]; let index3 = input[i][j + 3]; let index4 = input[i][j + 4]; let index1Array1 = input[i + 1][j + 1]; let index2Array2 = input[i + 2][j + 2]; let index3Array1 = input[i + 1][j + 3]; let index4Array0 = input[i][j + 4]; let index2Array0 = input[i][j + 2]; let index0Array2 = input[i + 2][j]; let index4Array2 = input[i + 2][j + 4]; if ( (firstCheck === index1 && firstCheck === index2 && firstCheck === index3 && firstCheck === index4) || (firstCheck === index1Array1 && firstCheck === index2Array2 && firstCheck === index3Array1 && firstCheck === index4Array0) || (index0Array2 === index1Array1 && index0Array2 === index2Array0 && index0Array2 === index3Array1 && index0Array2 === index4Array2) ) console.log("5 in a row"); else if ( (firstCheck === index1 && firstCheck === index2 && firstCheck === index3) || (firstCheck === index1Array1 && firstCheck === index2Array2 && firstCheck === index3Array1) || (index0Array2 === index1Array1 && index0Array2 === index2Array0 && index0Array2 === index3Array1) ) console.log("4 in a row"); } } } // examples input var array = [[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0]]; //Output: '1 winning line, scoring 20 points.' var array2 = [[2, 4, 2, 2, 3], [1, 1, 1, 4, 1], [3, 3, 3, 4, 2]]; //Output: '2 winning lines, scoring a total 30 points.' processSlots(array);
Java
UTF-8
1,686
2.65625
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
package edu.cmu.sphinx.demo; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.TreeMap; import edu.cmu.sphinx.demo.aligner.AlignerDemo; import edu.cmu.sphinx.demo.allphone.AllphoneDemo; import edu.cmu.sphinx.demo.dialog.DialogDemo; import edu.cmu.sphinx.demo.speakerid.SpeakerIdentificationDemo; import edu.cmu.sphinx.demo.transcriber.TranscriberDemo; import static java.util.Arrays.copyOfRange; public class DemoRunner { static final Class<?>[] paramTypes = new Class<?>[] {String[].class}; private static final Map<String, Class<?>> classes = new TreeMap<String, Class<?>>(); static { classes.put("aligner", AlignerDemo.class); classes.put("allphone", AllphoneDemo.class); classes.put("dialog", DialogDemo.class); classes.put("speakerid", SpeakerIdentificationDemo.class); classes.put("transcriber", TranscriberDemo.class); } public static void printUsage() { System.err.println("Usage: DemoRunner <DEMO> [<ARG> ...]\n"); System.err.println("Demo names:"); for (String name : classes.keySet()) System.err.println(" " + name); } public static void main(String[] args) throws Throwable { if (0 == args.length || !classes.containsKey(args[0])) { printUsage(); System.exit(1); } try { Method main = classes.get(args[0]).getMethod("main", paramTypes); main.invoke(null, new Object[]{copyOfRange(args, 1, args.length)}); } catch (InvocationTargetException e) { throw e.getCause(); } } }
Java
UTF-8
946
3.34375
3
[]
no_license
public abstract class Plus extends Seq{ public Plus() {} //blank fucking constructor public static Seq plus(Constant c1, Constant c2) { //create consant sequences for c1, c2 //implement plus algorithm int n = (c1.num < c2.num) ? c1.num : c2.num; int v = c1.value + c2.value; return new Constant(n, v); } public static Seq plus(Delta d1, Delta d2) { //create delta sequences for d1, d2 //implement plus int v1=0, v2=0; int n = (d1.num < d2.num) ? d1.num : d2.num; int i = d1.initial + d2.initial; int d = d1.delta + d2.delta; return new Delta(n, i, d); } public static Seq plus(Jumble j1, Jumble j2) { //create jumble sequences for j1, j2 //implement more fucking pluses int max = (j1.values.length < j2.values.length) ? j1.values.length : j2.values.length; int [] v = new int [max]; for(int i = 0; i < max; i++) v[i] = j1.values[i] + j2.values[i]; return new Jumble(v); } }
TypeScript
UTF-8
1,138
3.140625
3
[ "MIT" ]
permissive
/*external modules*/ import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException, } from '@nestjs/common'; import { validate } from 'class-validator'; import { plainToClass } from 'class-transformer'; @Injectable() export class ValidationPipe implements PipeTransform<any> { async transform(value: any, { metatype }: ArgumentMetadata) { if (!metatype || !this.toValidate(metatype)) { return value; } // transform plain JavaScript argument object into a typed object const object = plainToClass(metatype, value); const errors = await validate(object); if (errors.length > 0) { throw new BadRequestException('Validation failed'); } return value; } // It's responsible for bypassing the validation step when // the current argument being processed is a native JavaScript type // (these can't have validation decorators attached, so there's no reason to run them through the validation step). private toValidate(metatype: Function): boolean { const types: Function[] = [String, Boolean, Number, Array, Object]; return !types.includes(metatype); } }
Java
UTF-8
3,509
2.296875
2
[]
no_license
package rcs.auth.controllers; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.ResponseEntity; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import rcs.auth.api.models.AuthenticatedUser; import rcs.auth.api.models.LoginCredentials; import rcs.auth.api.models.UpdatePasswordRequest; import rcs.auth.api.models.UserAuthority; import rcs.auth.services.UserCredentialsService; import rcs.auth.utils.AuthUtils; import java.util.Optional; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class AuthControllerTest { @Mock private AuthUtils authUtils; @Mock private UserCredentialsService userCredentialsService; @InjectMocks private AuthController target; @Test public void testGetLoggedInUser() { // Arrange User user = new User( "username", "password", UserAuthority.ADMIN.getRoles().stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList())); when(authUtils.tryGetLoggedInUser()) .thenReturn(Optional.of(user)); // Act ResponseEntity<AuthenticatedUser> actual = target.getLoggedInUser(); // Assert assertThat(actual.getBody().getUsername()).isEqualTo(user.getUsername()); assertThat(actual.getBody().getRoles()) .containsAll(user.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList())); } @Test public void testGetLoggedInUserWhenNotLoggedIn() { // Arrange when(authUtils.tryGetLoggedInUser()) .thenReturn(Optional.empty()); // Act ResponseEntity<AuthenticatedUser> actual = target.getLoggedInUser(); // Assert assertThat(actual.getStatusCodeValue()).isEqualTo(401); } @Test public void testCreateUser() { // Arrange LoginCredentials request = new LoginCredentials("username", "password"); // Act ResponseEntity<Void> actual = target.createUser(request); // Assert assertThat(actual.getStatusCodeValue()).isEqualTo(200); verify(userCredentialsService).save(request); } @Test public void testUpdatePassword() { // Arrange String username = "username"; UpdatePasswordRequest request = new UpdatePasswordRequest("newPassword"); // Act ResponseEntity<Void> actual = target.updatePassword(username, request); // Assert assertThat(actual.getStatusCodeValue()).isEqualTo(200); verify(userCredentialsService).updatePassword(username, request.getPassword()); } @Test public void testDeleteUser() { // Arrange String username = "username"; // Act ResponseEntity<Void> actual = target.deleteUser(username); // Assert assertThat(actual.getStatusCodeValue()).isEqualTo(200); verify(userCredentialsService).delete(username); } }
C++
UTF-8
2,820
3.390625
3
[]
no_license
/* * //********************************************2521. Distinct Prime Factors of Product of Array.***************************************** https://leetcode.com/problems/distinct-prime-factors-of-product-of-array/ *******************************************************************TEST CASES:************************************************************ //These are the examples I had created, tweaked and worked on. [2,4,3,7,10,6] [2,4,3,8,16] [4,7,5,4,7,88,6,4,3,3] [3,9,27,81] [3,5,7,11] [5,4,7,78,8,87,6,5,4,322,3,87] // Time Complexity: O(n*sqrt(m)). //n-#nums in the array, m-maxm. num in the array. // Space Complexity: O(m). //********************************************************THIS IS LEET ACCEPTED CODE.*************************************************** */ //************************************************************Solution 1:************************************************************ //*****************************************************THIS IS LEET ACCEPTED CODE.*********************************************** // Time Complexity: O(n*sqrt(m)). //n-#nums in the array, m-maxm. num in the array. // Space Complexity: O(m). // This algorithm is Factorization based. We iter. over all nums in the array and calc. prime factors for each of the nums and mark them has occurred in another // array. After iterating the array, we visit primeFactor array and count how many prime factors had occurred while calc. factors for the nums and return the // count of #primes occurred. // As the range of nums is small, we used a bool array to track prime factors that occurred while factorizing nums in the array. class Solution { public: void getPrimeFactors(int num, vector<bool>&primeFactors) { // Calc. prime factors for a number. int temp=num; while(temp%2==0) { primeFactors[2]=true; // Marking a prime factor has occurred. temp/=2; } for(int i=3;i*i<=num;i+=2) { if(temp%i!=0) continue; primeFactors[i]=true; while(temp%i==0) temp/=i; } if(temp>1) primeFactors[temp]=true; return ; } int distinctPrimeFactors(vector<int>& v) { int res=0; int maxm=*max_element(v.begin(), v.end()); vector<bool>primeFactors(maxm+1, false); for(int&num:v) { // Iter. over all nums and calc. their prime factors. getPrimeFactors(num, primeFactors); } for(int i=1;i<=maxm;i++) { // Iter. and counting #prime factors that occurred while factorizing nums in arr. if(primeFactors[i]) res++; } return res; // Returning total #unique prime factors that occurred while factorizing nums. } };
Ruby
UTF-8
784
2.625
3
[ "Apache-2.0" ]
permissive
require 'test_helper' #调用test——helper里的函数 class CardTest < ActiveSupport::TestCase def setup @card=Card.create(:content => "我是小卡片的内容") end test "the truth" do assert true end test "should be valid" do #测试card是否存在 assert @card end test "card should not be nil" do assert_not_nil @card end test "content should not be nil" do #测试content不为nil assert_not_nil @card.content end test "content should not be empty"do assert_not_empty @card.content end test "should not have the same card"do #测试card不相同 card = Card.new card1 = Card.new assert_not_same card,card1 end end
Markdown
UTF-8
5,185
3.375
3
[ "MIT" ]
permissive
# Concerning Immutability Immutable data structures can help us to create simpler applications by being able to rely on the state of data at any point in time. When coupled with top-down rendering suddenly we have the ability to reason about the affects our actions will take on our state and be confident that our state remains consistent across as it traverses our view layer. Raid doesn’t try to reinvent the wheel and builds on top of the work done on [immutablejs](https://facebook.github.io/immutable-js/) and [immstruct](https://github.com/omniscientjs/immstruct) to create a centralised state implementation that emits events when it has been updated. ## *“It’s Alive!”* If you’ve never worked with immutable data structures then getting your head around how to create changes, or *mutations*, in your data (and therefore your state in this case) is crucial in getting your application to respond to actions. > *Immutable data structures can not be changed.* Yep, I think we got that one. So, when we want to our application to respond to events we need to recreate the entire state tree and pass that to our rendering to see the update of our action. Sounds expensive right? Well, it is, or, more accurately, it can be. ImmutableJS has done a lot of work to make this process as efficient as possible by reusing parts of the previous state tree that have not changed. There are some advantages here too in that testing for changes to your data structure becomes significantly easier, again, ImmutableJS handles this and Raid is just able to use that functionality by accepting a new state object to emit whenever you are processing an action. ## Referential Transparency I promise the long words are going to stop soon. Referential transparency, or, pure functions, are simply functions which produce no side effects, their output remains consistent when called with a given set of inputs and they touch only their own inputs. Use of referentially transparent functions liberally throughout an application, but in particular use in our update and render functions, can help create a predictable application by helping us to strictly manage where and how changes occur. Having a predictable state tree is great for developers, the advantages of being able to say *"Something has changed, now render everything"* are great as we don’t have to concern ourselves with working out what changed, or even why, or how it relates to the previous state, we simply render whatever our data is currently saying. We stay firmly in the present. Simply rendering everything whenever any change occurs is sometimes fast enough, but, ordinarily, it is a huge overdraw, which usually leads to poor rendering performance. Thankfully, there are some things we can do about that. Raid was built with [React](https://facebook.github.io/react/) in mind and as the structure is immutable we can make some predictions about the state of the render tree and try to reduce any overdraw resulting from top-down rendering. A quick recap on React rendering. React implements a [virtual DOM](https://facebook.github.io/react/docs/glossary.html) and it uses this tree to make diffs and try to work out what has changed. It does this by comparing properties passed to components. Out of the box React must at least check every component to see if it has changed before deciding how to proceed, this is actually fairly fast but we can make it faster. The problem React has is that if components have their own state then we can not make predictions about child nodes based on parent props so we must evaluate every node for changes before batching only those changes that result in operations on the DOM. By moving individual component state into a centralised state and passing state through to components via render properties we can remove this restriction and employ much faster techniques to assert changes to branches of our state diagram. An immutable state tree means that any operation on data creates a new state tree which we can evaluate from the top-down, as properties are passed from parent to child through the render tree we can make the assertion that if a parent’s properties do not change then neither have their children and skip rendering that entire subtree. React implements this using a [pure render mixin](https://facebook.github.io/react/docs/pure-render-mixin.html) that can make this evaluation really fast, if, and only if, it can be sure that stuff further down the tree has not changed. Raid also intones that update functions should also be pure, they are handed the state tree and an event to work against and that should be all they require to make changes to the state tree and return a new version of it. Whilst not a requirement for Raid, Immutability can help here as it will eliminate the chance of rogue state changes creeping in to our view layer when we are preparing data for render and give components freedom to make any changes they need to before preparation without risk of mutating the same data structure (or parts of a data structure) used by a different component. State becomes consistent and updates occur in one place.
JavaScript
UTF-8
1,347
2.5625
3
[ "MIT" ]
permissive
$(document).ready(function(){ /* 表示中のグローバルナビのアクティブ化 -----------------*/ var myServer; //サーバ var myUrl = location.href; myServer = 'www.aaa.com/'; //本番サーバ(最後のスラッシュ"/"までつけること) myUrl = myUrl.substr( myUrl.indexOf('//') + 2, myUrl.length); myUrl = myUrl.substr(myServer.length,myUrl.length); myUrl = myUrl.substr(0,myUrl.indexOf("/")); if(myUrl.length == 0 || myUrl.length > 20) myUrl = 'home'; $('li#gnav_' + myUrl).addClass('active'); /* ===== pagetop ===== */ var windowRoll = $(window), topBtn = $('#btnPagetop'), showFlug = false; topBtn.css('bottom', '-100px'); //一定距離スクロールで表示 windowRoll.scroll(function() { var h = $(this).scrollTop(); if(h > 200) { if(showFlug == false) { showFlug = true; topBtn.stop().animate({'bottom' : '45px' }, 300); } } else { if(showFlug) { showFlug = false; topBtn.stop().animate({'bottom' : '-45px'}, 500); } } }); //ページスクロール $('.scroll').click(function(event){ event.preventDefault(); var url = this.href; var parts = url.split('#'); var target = parts[1]; var target_offset = $('#'+target).offset(); var target_top = target_offset.top; $('html,body').animate({scrollTop:target_top}, 500); }); });
Markdown
UTF-8
2,661
2.890625
3
[]
no_license
# Entrega trabajo práctico Bioinformática Nº1 Integrantes: - Leonardo Di Carlo - Lucio Francioni - Nahuel Pereyra --- #### RETO I: ¿Podrías buscar un ejemplo de macromoléculas que almacenen información sobre la ‘identidad’ de un organismo dado? *Los ácidos nucleicos son macromoléculas que guardan identidad de los organismos. Un ejemplo claro es el ADN.* #### RETO II: Proponé una forma de expresar la información contenida en la estructura primaria de las proteínas usando tipos de datos de los lenguajes de programación que conocés. *La estructura primaria de las proteínas se basa en los aminoácidos (hay una tabla periódica de 20 aminoácidos, y cada uno se representa con 3 letras). Cada aminoácido se simplifica en una letra sola, por lo que un tipo de dato adecuado para representrar dicha estructura sería un String.* #### RETO III: ¿ En qué tipo de datos podrías expresar la información de la estructura terciaria proteica? *Existen dos tipos de estructura terciaria para las proteínas: fibrosa o regular. Al ser sólo dos valores podrían incluso expresarse como booleanos. Otra forma es expresarlos también con un String.* #### RETO IV: Rosalind Franklin es una científica muy relevante, que tuvo menos reconocimiento del merecido. ¿Cuáles fueron sus contribuciones en este campo? ¿Qué nos cuenta su historia acerca del mundo de la ciencia? *Rosalind Franklin fue una científica Inglesa que realizó grandes contribuciones a la ciencia en la época de la Segunda Guerra Mundial. Mediante el estudio bajo la técnica de difracción de Rayos X pudo describir la estructura del ADN, descubriendo así la forma de "doble hélice" de las moléculas. Hay quienes sostienen incluso que ella habia llegado a la conclusion de la estructura helicoidal unos meses antes de la publicacion realizada por Watson y Crick. Pero que por no haber realizado ninguna publicación aún con los resultados de sus investigaciones e imágenes tomadas, que resultaron fundamentales para sostener la propuesta, no logró tener el reconocimiento merecido.* #### RETO V: Proponé en pseudocódigo un programa que prediga la estructura secundaria que adoptará cada residuo de la secuencia proteica dada, especificandola como H (si es una hélice), B (si es una hoja beta plegada) y L (si es un bucle o loop). *Ver archivo BIOINFO-TP1.py* #### RETO VI: ¿Qué hace distintos a dos individuos de una especie? Propone una forma de corroborar tu respuesta realizando un diagrama de un posible método computacional para dicho fin. Cada individuo posee una secuencia de ADN única e irrepetible, y esto es lo que nos hace diferentes a nivel molecular.
Java
UTF-8
938
2
2
[ "MIT" ]
permissive
package br.com.vehicle.support.handler; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Component; import br.com.vehicle.model.I18nMessage; @Component public class I18nHandler { @Autowired private MessageSource messageSource; public String getMessage(I18nMessage appCode, Locale locale, Object... args) { return messageSource.getMessage(appCode.getCode(), args, locale); } public String getMessage(String code, Locale locale, Object... args) { return messageSource.getMessage(code, args, locale); } public String getMessage(I18nMessage appCode, Locale locale) { return messageSource.getMessage(appCode.getCode(), null, locale); } public String getMessage(String code, Locale locale) { return messageSource.getMessage(code, null, locale); } }
Java
UTF-8
411
2.25
2
[]
no_license
package entidade; public class RetornoVeiculo extends RetornoPadrao{ private Veiculo veiculo; private Cliente cliente; public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Veiculo getVeiculo() { return veiculo; } public void setVeiculo(Veiculo veiculo) { this.veiculo = veiculo; } }
Java
UTF-8
10,793
2.875
3
[]
no_license
package com.michaelzanussi.astar; /** * Provides global access to various puzzle statistics and file * handles. Being global, all methods can be called from anywhere. * * @author <a href="mailto:iosdevx@gmail.com">Michael Zanussi</a> * @version 1.0 (29 Mar 2004) */ public class Global { // Debug mode flag. private static boolean _debug; // STATS options. private static int _nodesClosed; private static int _nodesOpened; private static int _nodesReopened; private static int _openListBound; private static int _openListMaxLen; private static long _timeBound; private static int _totalNodesBound; // RESULTS private static boolean _statePath; // Application start time. private static long _startTime; // Other useful stats. private static int _closedListSize; private static double _maxRatio; private static double _minRatio; private static int _openListSize; // Define the output files. private static TextFileWriter _outFile = null; private static TextFileWriter _logFile = null; private static TextFileWriter _errFile = null; // Unit test support. private static String data; /** * No-arg constructor. */ public Global() { reset(); } /** * Outputs a line of text to the standard output or an error file. * If the file handle is <code>null</code>, output goes to the standard * output; otherwise, output is directed to the necessary file. * * @param message the message to log. */ public static void error( String message ) { if( getErrFile() == null ) { System.err.println( message ); } else { getErrFile().writeln( message ); } } /** * Returns the debug status. * * @return the debug status. */ public static boolean getDebug() { return _debug; } /** * Returns the error file. * * @return the error file. */ public static TextFileWriter getErrFile() { return _errFile; } /** * Returns the log file. * * @return the log file. */ public static TextFileWriter getLogFile() { return _logFile; } /** * Returns the maximum ratio of open list nodes to closed * list nodes. * * @return the maximum ratio. */ public static double getMaxRatio() { return _maxRatio; } /** * Returns the minimum ratio of open list nodes to closed * list nodes. * * @return the minimum ratio. */ public static double getMinRatio() { return _minRatio; } /** * Returns the total number of nodes on the closed list. * * @return the total number of nodes on the closed list. */ public static int getNodesClosed() { return _nodesClosed; } /** * Returns the total number of nodes opened during the search. * * @return the total number of nodes opened during the search. */ public static int getNodesOpened() { return _nodesOpened; } /** * Returns the number of nodes moved from the closed list to * the open list during the search. * * @return the number of nodes moved from the closed list to * the open list. */ public static int getNodesReopened() { return _nodesReopened; } /** * Returns the maximum number of elements that are allowed in the * open list. The search is terminated if this value is exceeded. * The default value is <code>Integer.MAX_VALUE</code>. * * @return the maximum allowable size of the open list. */ public static int getOpenListBound() { return _openListBound; } /** * Returns the maximum number of nodes on the open list encountered * so far. * * @return the maximum number of nodes on the open list. */ public static int getOpenListMaxLen() { return _openListMaxLen; } /** * Returns the output file. * * @return the output file. */ public static TextFileWriter getOutFile() { return _outFile; } /** * Returns the maximum number of nodes that can be in the search * at one time (total of the open list and the closed list). The * search is terminated if this number is exceeded. The default * value is <code>Integer.MAX_VALUE</code>. * * @return the maximum allowable number of nodes. */ public static int getTotalNodesBound() { return _totalNodesBound; } /** * Increment the open node count. */ public static void incNodesOpened() { _nodesOpened++; } /** * Increment the reopened node count. */ public static void incNodesReopened() { _nodesReopened++; } /** * Returns <code>true</code> if the amount of time spent searching * (current time - start time) exceeds the time bound, otherwise * returns <code>false</code>. * * @return <code>true</code> if time is up, otherwise <code>false</code>. */ public static boolean isTimeUp() { return ( System.currentTimeMillis() - _startTime > _timeBound ? true : false ); } /** * Return data for unit testing. * * @return data for unit testing. */ public static String getData() { return data; } /** * Outputs a line of text to the standard output or a log file. * If the file handle is <code>null</code>, output goes to the standard * output; otherwise, output is directed to the necessary file. * * @param message the message to log. */ public static void log( String message ) { data += message; // unit testing if( getLogFile() == null ) { System.out.println( message ); } else { getLogFile().writeln( message ); } } /** * Outputs a line of text to the standard output or an output file. * If the file handle is <code>null</code>, output goes to the standard * output; otherwise, output is directed to the necessary file. * * @param message the message to output. */ public static void output( String message ) { data += message; // unit testing if( getOutFile() == null ) { System.out.println( message ); } else { getOutFile().writeln( message ); } } /** * Returns whether to report the complete sequence of states encountered * on the solution path, including the start and goal states. * * @return whether to report the complete sequence of states encountered. */ public static boolean reportStatePath() { return _statePath; } /** * Reset the puzzle statistics. */ public static void reset() { _closedListSize = 0; _debug = false; _maxRatio = 0.0; _minRatio = 0.0; _nodesClosed = 0; _nodesOpened = 0; _nodesReopened = 0; _openListBound = Integer.MAX_VALUE; _openListMaxLen = 0; _openListSize = 0; _startTime = System.currentTimeMillis(); _statePath = false; _timeBound = Long.MAX_VALUE; _totalNodesBound = Integer.MAX_VALUE; data = ""; } /** * Set the size of the closed list. * * @param value the size of the closed list. */ public static void setClosedListSize( int value ) { _closedListSize = value; _calculateRatios(); } /** * Set the debug status. * * @param value the debug status. */ public static void setDebug( boolean value ) { _debug = value; } /** * Sets the error file. * * @param tfw the error file. */ public static void setErrFile( TextFileWriter tfw ) { _errFile = tfw; } /** * Sets the log file. * * @param tfw the log file. */ public static void setLogFile( TextFileWriter tfw ) { _logFile = tfw; } /** * Set the number of nodes currently on the closed list. * * @param value the number of closed nodes. */ public static void setNodesClosed( int value ) { _nodesClosed = value; } /** * Sets the maximum number of elements that may be in the * open list. The search is terminated if this number is exceeded. * The default value is <code>Integer.MAX_VALUE</code>. * * @param value the maximum number of elements. */ public static void setOpenListBound( int value ) { _openListBound = value; } /** * Set the size of the open list. Also updates the open * list maximum length as necessary. * * @param value the size of the open list. */ public static void setOpenListSize( int value ) { _openListSize = value; if( _openListSize > _openListMaxLen ) { _openListMaxLen = _openListSize; } _calculateRatios(); } /** * Sets the output file. * * @param tfw the output file. * @throws NullPointerException If <code>tfw</code> is <code>null</code>. */ public static void setOutFile( TextFileWriter tfw ) { _outFile = tfw; } /** * Set whether to report the complete sequence of states encountered * on the solution path. The default value is <code>false</code>. * * @param value the number of closed nodes. */ public static void setStatePath( boolean value ) { _statePath = value; } /** * Sets the maximum running time of the search, given in milliseconds. * The search is terminated if this value is exceeded. The default * value is <code>Long.MAX_VALUE</code>. * * @param value the maximum running time. */ public static void setTimeBound( long value ) { _timeBound = value; } /** * Sets the maximum number of nodes that can be in the search * at one time (total of the open list and the closed list). The * search is terminated if this number is exceeded. The default * value is <code>Integer.MAX_VALUE</code>. * * @param value the maxium number of nodes. */ public static void setTotalNodesBound( int value ) { _totalNodesBound = value; } /** * Helper function Calculates the min and max ratios of the size * of the open list to the size of the closed list. */ private static void _calculateRatios() { // The calculated ratio. double ratio = 0.0; // Special case when there are no closed nodes. if( _closedListSize == 0) { if( _openListSize == 0) { ratio = 1.0; } else { ratio = (double)_openListSize; } } // Normal case, both lists have nodes. else { ratio = (double)_openListSize / _closedListSize; } // Set max ratio. if( ratio > _maxRatio ) { _maxRatio = ratio; } // Set min ratio. if( ratio < _minRatio ) { _minRatio = ratio; } // *DEBUG* if( Global.getDebug() ) { System.out.println("*DEBUG* Open/Closed ratio: " + ratio ); } } }