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
1,789
2.6875
3
[]
no_license
window.VecinxsMap = class VecinxsMap{ constructor(options){ this.options = options; this.map = null; } init(){ try{ this.map = new L.Map(this.options['container']); }catch(e){ console.log(e); } var osmUrl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; var osmAttrib='Map data © <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'; var osm = new L.TileLayer(osmUrl, {minZoom: 1, maxZoom: 20, attribution: osmAttrib}); this.map.setView([this.options["lat"], this.options["lng"]],this.options["zoom"]); this.map.addLayer(osm); } setMarkers(markersData){ markersData.forEach((markerData) => { let icon = L.icon({ iconUrl: markerData.iconPath, iconSize: [35, 42], //iconAnchor: [22, 94], popupAnchor: [0, 5], //shadowUrl: 'my-icon-shadow.png', //shadowSize: [68, 95], //shadowAnchor: [22, 94] }); marker = new L.marker([markerData.lat, markerData.lng], {icon: icon}); marker.bindPopup(this.popUpContent(markerData)).openPopup(); this.map.addLayer(marker); }); } popUpContent(markerData){ let html = $("#" + this.options["neighbourDataTemplate"]).find(".content").html(); html = html.replace("%address%", markerData['address']); html = markerData['name'] ? html.replace("%name%", markerData['name']) : html.replace("%name%", ""); if(markerData['neighbours'].length == 0){ html = html.replace("%neighbours%", "No hay vecinxs en esta parada"); } else { html = html.replace("%neighbours%", markerData['neighbours'].map((neighbour)=>{ return "<i class='fa fa-user' ></i> " + neighbour['name']; }).join("<br />")); } return html; } }
Java
UTF-8
802
2.0625
2
[]
no_license
package com.example.user.authentication.api; import com.example.item.domain.Item; import com.example.user.authentication.domain.AppUser; import com.example.user.authentication.service.AppUserService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Optional; @Controller @AllArgsConstructor @Path("user") public class AppUserAPI { private AppUserService appUserService; @GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Optional<AppUser> getByUserName(@QueryParam("name") String name) { return appUserService.getByUserName(name); } }
Shell
UTF-8
353
2.828125
3
[]
no_license
if [[ $1 == "" ]] then echo "Usage: sh bin/vm_bool.sh CHAMPION" else ./vm/corewar $1 -verbose > bin/my ./resources/corewar $1 -v 31 -a > bin/origin if [ "$(diff -u bin/my bin/origin)" == "" ] then num=$(cat bin/origin | grep "It is now cycle" | tail -1 | cut -c 17-) sh bin/dump.sh $1 $(($num-1)) else echo "\033[31mVERBOSE KO\033[0m" fi fi
PHP
UTF-8
1,280
2.546875
3
[]
no_license
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddCodeToAreaTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('area', function (Blueprint $table) { $table->unsignedInteger('code')->unique()->nullable()->comment('编号'); }); $list = \SMG\Area\AreaModel::get(['id', 'name', 'parent_id', '_lft','_rgt'])->toTree(); $start = 10000000; $i = 1; $level = 1; foreach ($list as $one) { $code = $start + $i*1000000; $this->updateCode($one,$code, $level); $i++; } } public function updateCode($cur,$code, $level=1) { $cur->code = $code; $cur->save(); if ($cur->children) { $i = 1; $level++; foreach ($cur->children as $one) { $new_code = $code + $i*pow(10, (4-$level)*2); $this->updateCode($one, $new_code, $level); $i++; } } } /** * Reverse the migrations. * * @return void */ public function down() { } }
Markdown
UTF-8
4,516
3.578125
4
[]
no_license
# Destructuring **Definition**: Per [the docs](https:/-/developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), "Destructuring" allows you to pull out data from arrays and objects into distinct variables with concise syntax. ## Arrays ### Variable Swapping Given two variables, swap their values in one line of code. ```js var thing1 = 'apple' var thing2 = 'banana' // => thing1 = 'banana' // => thing2 = 'apple' ``` SOLUTION: ``` [thing1, thing2] = [thing2, thing1] ``` ### Assigning New Variable Names to Object Keys Given an object, in one line, assign variables to the values of object using different names than the keys already in the object. ```js const object = {name: 'elvis', title: 'hip swinger'} // console.log(person) => 'elvis' // console.log(job) => 'hip swinger' ``` ### Variable Swapping: Array What if I want to grab the values of the first and second elements of a given array and then swap those variables? ```js const items = ['apple', 'banana', 'pear'] // Currently, I would get the following returns: console.log(items1) => 'apple' console.log(items2) => 'banana' // Assign variables using ES6 so that we get (note, you cannot just make a completely new array): console.log(items1) => 'banana'; console.log(items2) => 'apple'; ``` ### Object Matching Given an object, write one line of code that assigns variables to the keys. ```js const object = { user: 'brenna', id: 1, date: 'monday', class: 3 } ``` // console.log(user) => 'brenna' ### Object Matching: Deep Matching Given an object with nested objects, write one line of code that assigns variables to the keys. ```js const object = { user: 'elvis', address: { city: 'denver', state: 'colorado' }, id: 1 } ``` ## Parameter Matching Provided the arguments below, write a function that logs both arguments. ```js // Array ['hello', 'taylor'] // => 'hello, taylor!' // Object with keys const greeting="hello" const name="taylor" {greeting, name} // => 'hello, taylor!' //Object with key value pairs {greeting: 'hello', name: 'taylor'} // => 'hello, taylor!' ``` ### Variables and Rest Assign 2 elements of an array to specific variables, and then assign the remaining values collectively to another variable ```js ['apple', 'banana', 'chocolate', 'pears', 'oats', 'pizza'] // console.log(thing1) => 'apple' // console.log(thing2) => 'banana' // console.log(others) => ['chocolate, 'pears', 'oats', 'pizza'] ``` ### Object Variable Assignment Without Declaration Given a couple declared, empty variables, write a line of code that assigns those variables to values as keys within an object. ```js let name, title // console.log(name) => 'elvis' // console.log(title) => 'hip swinger' ``` ### Array Variable Assignment Given a set of variables, assign the values in one line. ```js let firstName, lastName, city, state; // YOUR CODE HERE // console.log(firstName) => 'marilyn' // console.log(lastName) => 'monroe' // console.log(city) => 'new york' // console.log(state) => 'new york' ``` ### Default Values: Array Now write the same thing, but set default values, and leave off an assignment on the right side of the statement. ### Default Values: Object Given an object, assign each value to a variable but "forget" a couple. Use default values to ensure validity. ### Parsing An Array From A Function Return Given a function that returns an array, use ES6 to parse said array so that each value is accessible directly. ```js const x = () => { return ['hello', 'world'] } // console.log(greeting) => 'hello' // console.log(target) => 'world' ``` ### Object Destructuring Given an object, in one line of code pull out the individual keys to be accessible directly. ```js const object = {name: 'elvis', title: 'hip swinger'} // console.log(name) => 'elvis' // console.log(title) => 'hip swinger' ``` ### For Of Iteration Given a crazy array of objects with nested objects, iterate over it and grab just the artist and the third album title. ```js const singers = [ { artist: 'Elvis', albums: { album1: 'this first title for Elvis', album2: 'another second title for Elvis' album3: 'third title for Elvis' } }, { artist: 'Cher', albums: { album1: 'this first title for Cher', album2: 'another second title for Cher' album3: 'third title for Cher' } } ] // 'Artist: Elvis, Third Album: third title for Elvis' // 'Artist: Cher, Third Album: third title for Cher' ```
C++
UTF-8
526
2.859375
3
[]
no_license
// Hello Die.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Die.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //Alternative dice roll cout << "Enter number of rolls" << endl; int NumberOfRolls = 0; cin >> NumberOfRolls; //Can and will store letters in int? cout << NumberOfRolls << endl; for (int i = 0; i + 1 < NumberOfRolls; i++) { int Value = rand() % 6 + 1; cout << "Roll " << i << ": " << Value << endl; } return 0; }
PHP
UTF-8
11,486
2.671875
3
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
<?php // vim: foldmethod=marker /** * Ethna_DB_ADOdb.php * * @package Ethna * @author halt feits <halt.feits@gmail.com> * @version $Id: Ethna_DB_ADOdb.php 493 2008-04-04 15:09:44Z mumumu-org $ */ /** * ADOdb config setting */ define('ADODB_OUTP', 'ethna_adodb_logger'); //disable output error require_once 'adodb/adodb.inc.php'; function ethna_adodb_logger ($msg, $newline) { $c = Ethna_Controller::getInstance(); $logger =& $c->getLogger(); $logger->log(LOG_DEBUG, strip_tags(str_replace("\n", "", $msg))); } /** * Ethna_DB_ADOdb * * EthnaのフレームワークでADOdbオブジェクトを扱うための抽象クラス * * @package Ethna * @author halt feits <halt.feits@gmail.com> * @access public */ class Ethna_DB_ADOdb extends Ethna_DB { /**#@+ * @access private */ /** @var object DB DBオブジェクト */ var $db; /** @var string dsn */ var $dsn; /**#@-*/ /** * コンストラクタ * * @access public * @param object Ethna_Controller &$controller コントローラオブジェクト * @param string $dsn DSN * @param bool $persistent 持続接続設定 */ function Ethna_DB_ADOdb(&$controller, $dsn, $persistent) { parent::Ethna_DB($controller, $dsn, $persistent); $this->logger =& $controller->getLogger(); } //{{{ connect /** * DBに接続する * * @access public * @return mixed 0:正常終了 Ethna_Error:エラー */ function connect() { $dsn = $this->parseDSN($this->dsn); if ($dsn['phptype'] == 'sqlite') { $path = $dsn['database']; $this->db = ADONewConnection("sqlite"); $this->db->Connect($path); } else { $this->db = ADONewConnection($this->dsn); } if ( $this->db ) { $this->db->SetFetchMode(ADODB_FETCH_ASSOC); return true; } else { return false; } } //}}} //{{{ disconnect /** * DB接続を切断する * * @access public */ function disconnect() { //$this->db->close(); return 0; } //}}} //{{{ isValid /** * DB接続状態を返す * * @access public * @return bool true:正常(接続済み) false:エラー/未接続 */ function isValid() { if ( is_object($this->db) ) { return true; } else { return false; } } //}}} //{{{ begin /** * DBトランザクションを開始する * * @access public * @return mixed 0:正常終了 Ethna_Error:エラー */ function begin() { return $this->db->BeginTrans(); } //}}} //{{{ rollback /** * DBトランザクションを中断する * * @access public * @return mixed 0:正常終了 Ethna_Error:エラー */ function rollback() { $this->db->RollbackTrans(); return 0; } //}}} //{{{ commit /** * DBトランザクションを終了する * * @access public * @return mixed 0:正常終了 Ethna_Error:エラー */ function commit() { $this->db->CommitTrans(); return 0; } //}}} //{{{ query /** * クエリを発行する * * @access public * @param string $query SQL文 * @return mixed DB_Result:結果オブジェクト Ethna_Error:エラー */ function &query($query, $inputarr = false) { return $this->_query($query, $inputarr); } //}}} //{{{ _query /** * クエリを発行する * * @access private * @param string $query SQL文 * @return mixed DB_Result:結果オブジェクト Ethna_Error:エラー */ function &_query($query, $inputarr = false) { $this->logger->log(LOG_DEBUG, $query); $r =& $this->db->execute($query, $inputarr); if ($r === false) { $error = Ethna::raiseError('エラー SQL[%s] CODE[%d] MESSAGE[%s]', E_DB_QUERY, $query, $this->db->ErrorNo(), $this->db->ErrorMsg()); return $error; } return $r; } //}}} //{{{ getAll /** * getAll * * @access public */ function getAll($query, $inputarr = false) { $this->db->SetFetchMode(ADODB_FETCH_ASSOC); return $this->db->getAll($query, $inputarr); } //}}} //{{{ getOne function getOne($query, $inputarr = false) { return $this->db->GetOne($query, $inputarr); } //}}} //{{{ getRow function getRow($query, $inputarr = false) { return $this->db->GetRow($query, $inputarr); } //}}} //{{{ getCol function getCol($query, $inputarr = false) { return $this->db->GetCol($query, $inputarr); } //}}} //{{{ execute function execute($query, $inputarr = false) { return $this->db->Execute($query, $inputarr); } //}}} //{{{ replace function replace($table, $arrFields, $keyCols, $autoQuote = false) { return $this->db->Replace($table, $arrFields, $keyCols, $autoQuote); } //}}} //{{{ autoExecute function autoExecute($table, $fields, $mode, $where = false, $forceUpdate = true, $magicq = false) { return $this->db->AutoExecute($table, $fields, $mode, $where, $forceUpdate, $magicq); } //}}} //{{{ pageExecute /** * pageExecute * * @param string $query * @param string $nrows * @param integer $page * @param array $inputarr */ function pageExecute($query, $nrows, $page, $inputarr = false) { return $this->db->PageExecute($query, $nrows, $page, $inputarr); } //}}} // {{{ parseDSN() /** * Parse a data source name * * Additional keys can be added by appending a URI query string to the * end of the DSN. * * The format of the supplied DSN is in its fullest form: * <code> * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true * </code> * * Most variations are allowed: * <code> * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 * phptype://username:password@hostspec/database_name * phptype://username:password@hostspec * phptype://username@hostspec * phptype://hostspec/database * phptype://hostspec * phptype(dbsyntax) * phptype * </code> * * @param string $dsn Data Source Name to be parsed * * @return array an associative array with the following keys: * + phptype: Database backend used in PHP (mysql, odbc etc.) * + dbsyntax: Database used with regards to SQL syntax etc. * + protocol: Communication protocol to use (tcp, unix etc.) * + hostspec: Host specification (hostname[:port]) * + database: Database to use on the DBMS server * + username: User name for login * + password: Password for login */ function parseDSN($dsn) { $parsed = array( 'phptype' => false, 'dbsyntax' => false, 'username' => false, 'password' => false, 'protocol' => false, 'hostspec' => false, 'port' => false, 'socket' => false, 'database' => false, ); if (is_array($dsn)) { $dsn = array_merge($parsed, $dsn); if (!$dsn['dbsyntax']) { $dsn['dbsyntax'] = $dsn['phptype']; } return $dsn; } // Find phptype and dbsyntax if (($pos = strpos($dsn, '://')) !== false) { $str = substr($dsn, 0, $pos); $dsn = substr($dsn, $pos + 3); } else { $str = $dsn; $dsn = null; } // Get phptype and dbsyntax // $str => phptype(dbsyntax) if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { $parsed['phptype'] = $arr[1]; $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; } else { $parsed['phptype'] = $str; $parsed['dbsyntax'] = $str; } if (!count($dsn)) { return $parsed; } // Get (if found): username and password // $dsn => username:password@protocol+hostspec/database if (($at = strrpos($dsn, '@')) !== false) { $str = substr($dsn, 0, $at); $dsn = substr($dsn, $at + 1); if (($pos = strpos($str, ':')) !== false) { $parsed['username'] = rawurldecode(substr($str, 0, $pos)); $parsed['password'] = rawurldecode(substr($str, $pos + 1)); } else { $parsed['username'] = rawurldecode($str); } } // Find protocol and hostspec if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { // $dsn => proto(proto_opts)/database $proto = $match[1]; $proto_opts = $match[2] ? $match[2] : false; $dsn = $match[3]; } else { // $dsn => protocol+hostspec/database (old format) if (strpos($dsn, '+') !== false) { list($proto, $dsn) = explode('+', $dsn, 2); } if (strpos($dsn, '/') !== false) { list($proto_opts, $dsn) = explode('/', $dsn, 2); } else { $proto_opts = $dsn; $dsn = null; } } // process the different protocol options $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; $proto_opts = rawurldecode($proto_opts); if ($parsed['protocol'] == 'tcp') { if (strpos($proto_opts, ':') !== false) { list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts); } else { $parsed['hostspec'] = $proto_opts; } } elseif ($parsed['protocol'] == 'unix') { $parsed['socket'] = $proto_opts; } // Get dabase if any // $dsn => database if ($dsn) { if (($pos = strpos($dsn, '?')) === false) { // /database $parsed['database'] = rawurldecode($dsn); } else { // /database?param1=value1&param2=value2 $parsed['database'] = rawurldecode(substr($dsn, 0, $pos)); $dsn = substr($dsn, $pos + 1); if (strpos($dsn, '&') !== false) { $opts = explode('&', $dsn); } else { // database?param1=value1 $opts = array($dsn); } foreach ($opts as $opt) { list($key, $value) = explode('=', $opt); if (!isset($parsed[$key])) { // don't allow params overwrite $parsed[$key] = rawurldecode($value); } } } } return $parsed; } // }}} } ?>
C++
UTF-8
2,540
2.578125
3
[ "MIT" ]
permissive
#include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Geometry> #include <iostream> #include <math.h> #include "yaml-cpp/yaml.h" #include <string.h> #include <random> //used to simulate sensors using namespace Eigen; class parameters{ private: YAML::Node node; std::string file; int n_params; public: parameters(std::string); // contructor ~parameters(); // destructor // return parameters - Followin the sequence in yaml file VectorXd get_parameters(); }; class sensors_class{ private: VectorXd gyro; VectorXd accel; VectorXd gps; double bar; std::random_device rd; std::mt19937 gen{rd()}; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW sensors_class(double); //Construtor ~sensors_class(); //Destructor // void update_sensors(); void update_sensors(VectorXd, VectorXd); Vector3d get_gyro(); Vector3d get_accel(); Vector3d get_gps(); double get_bar(); VectorXd get_sensors(); }; class drone_class{ private: // States of the drone VectorXd states; // Propeller commands VectorXd controls; // Time stamp double dt; // parameters double m; double g; double drag; VectorXd current_acc; public: sensors_class *sensors; EIGEN_MAKE_ALIGNED_OPERATOR_NEW drone_class(double, VectorXd); //Construtor ~drone_class(); //Destructor // Method to perform an integration step void itegration_step(); // Method to set the values of the propeller commands void set_controls(VectorXd); // Method to set the values of the propeller commands from a acrorate command void set_controls_acro(VectorXd); //Method to computethe drone full dynamics VectorXd continuous_model(VectorXd, VectorXd, double); // Get drone states data VectorXd get_states(); // Get drone position data VectorXd get_pos(); // Get drone current acceleration ("applied forces", ths does not include gravity force effect) VectorXd get_current_acc(); // Get drone current controls VectorXd get_controls(); void update_sensors(); //Useful functions // Convert Euler to Quaternion VectorXd EulertoQuaternion(VectorXd); VectorXd quat2eulerangle(VectorXd); MatrixXd angle2rotm(VectorXd); VectorXd rotm2angle(MatrixXd); MatrixXd quat2rotm(VectorXd); VectorXd quat_derivative(VectorXd, VectorXd); VectorXd quat_normalize(VectorXd); };
TypeScript
UTF-8
584
2.609375
3
[]
no_license
import { IHasCreatedBy } from './IHasCreatedBy'; import { IHasPTA } from './IHasPTA'; import { IVantageCoreTypeWithoutVersioning } from './IVantageCoreTypeWithoutVersioning'; import { VantageTypeBaseWithVersioning } from './VantageTypeBaseWithVersioning'; export class TRating extends VantageTypeBaseWithVersioning implements IVantageCoreTypeWithoutVersioning, IHasPTA, IHasCreatedBy { public description: string; public value: number; public isDeleted: boolean; public constructor(init?: Partial<TRating>) { super(init); (Object as any).assign(this, init); } }
Java
UTF-8
2,658
3.453125
3
[]
no_license
package week13d02; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; public class Quiz { private Map<String, List<Character>> answers = new HashMap<>(); private char[] goodAnswers; public void loadFromFile(BufferedReader br) { try { String line = br.readLine(); goodAnswers = line.toCharArray(); while ((line = br.readLine()) != null) { putToMap(line); } br.close(); } catch (IOException ioe) { throw new IllegalStateException("Can not handle file.", ioe); } } private void putToMap(String line) { String[] temp = line.split(" "); String id = temp[0]; char answer = temp[1].charAt(0); if (!answers.containsKey(id)) { answers.put(id, new ArrayList<>()); } answers.get(id).add(answer); } public boolean wasItAGoodAnswer(String id, int i) { if (i < 1 || i > 5) { throw new IllegalArgumentException("There was five questions in the quiz. Add a number between 1 and 5!"); } if (!answers.containsKey(id)) { throw new IllegalArgumentException("This competitioner didn't took part in the quiz."); } char answer = answers.get(id).get(i - 1); return answer == goodAnswers[i - 1]; } public String whichCompetitionerHasMostXes() { String id = null; int max = 0; for (String s : answers.keySet()) { int counter = countXes(answers.get(s)); if (counter > max) { max = counter; id = s; } } return id; } private int countXes(List<Character> listOfAnswersById) { int counter = 0; for (char c : listOfAnswersById) { if (c == 'X') { counter++; } } return counter; } public String whichCompetitionerHasMostPoints() { String id = null; int max = 0; for (String s : answers.keySet()) { int counter = countPoints(answers.get(s)); if (counter > max) { max = counter; id = s; } } return id; } private int countPoints(List<Character> listOfAnswersById) { int counter = 0; for (int i = 1; i <= listOfAnswersById.size(); i++) { if (listOfAnswersById.get(i - 1) == goodAnswers[i - 1]) { counter += i; } } return counter; } }
C#
UTF-8
6,020
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace VehiclesTracking.Models { public class DbHandle { private SqlConnection con; private void connection() { string constring = ConfigurationManager.ConnectionStrings["defaultconnection"].ToString(); con = new SqlConnection(constring); } // **************** ADD NEW VEHICLE ********************* public bool AddVehicle(Vehicle vehicle) { connection(); SqlCommand cmd = new SqlCommand("AddNewVehicle", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Make", vehicle.Make); cmd.Parameters.AddWithValue("@Model", vehicle.Model); cmd.Parameters.AddWithValue("@Color", vehicle.Color); cmd.Parameters.AddWithValue("@RegistrationNumber", vehicle.RegistrationNumber); cmd.Parameters.AddWithValue("@DOR", vehicle.DOR); cmd.Parameters.AddWithValue("@FirstName", vehicle.FirstName); cmd.Parameters.AddWithValue("@LastName", vehicle.LastName); cmd.Parameters.AddWithValue("@PhoneNumber", vehicle.PhoneNumber); cmd.Parameters.AddWithValue("@UnitNumber", vehicle.UnitNumber); cmd.Parameters.AddWithValue("@AptNumber", vehicle.AptNumber); con.Open(); int i = cmd.ExecuteNonQuery(); con.Close(); if (i >= 1) return true; else return false; } // ********** VIEW VEHICLE DETAILS ******************** public List<Vehicle> GetVehicle() { connection(); List<Vehicle> vehicleList = new List<Vehicle>(); SqlCommand cmd = new SqlCommand("GetVehicleDetails", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter sd = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); con.Open(); sd.Fill(dt); con.Close(); foreach (DataRow dr in dt.Rows) { vehicleList.Add( new Vehicle { Id = Convert.ToInt32(dr["Id"]), Make = Convert.ToString(dr["Make"]), Model = Convert.ToString(dr["Model"]), Color = Convert.ToString(dr["Color"]), RegistrationNumber = Convert.ToInt32(dr["RegistrationNumber"]), DOR = Convert.ToDateTime(dr["DOR"]), FirstName = Convert.ToString(dr["FirstName"]), LastName = Convert.ToString(dr["LastName"]), PhoneNumber = Convert.ToString(dr["PhoneNumber"]), UnitNumber = Convert.ToInt32(dr["UnitNumber"]), AptNumber = Convert.ToInt32(dr["AptNumber"]) }); } return vehicleList; } // ***************** UPDATE VEHICLE DETAILS ********************* public bool UpdateVehicle(Vehicle vehicle) { connection(); SqlCommand cmd = new SqlCommand("UpdateVehicleDetails", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@VehicleId", vehicle.Id); cmd.Parameters.AddWithValue("@Make", vehicle.Make); cmd.Parameters.AddWithValue("@Model", vehicle.Model); cmd.Parameters.AddWithValue("@Color", vehicle.Color); cmd.Parameters.AddWithValue("@RegistrationNumber", vehicle.RegistrationNumber); cmd.Parameters.AddWithValue("@DOR", vehicle.DOR); cmd.Parameters.AddWithValue("@FirstName", vehicle.FirstName); cmd.Parameters.AddWithValue("@LastName", vehicle.LastName); cmd.Parameters.AddWithValue("@PhoneNumber", vehicle.PhoneNumber); cmd.Parameters.AddWithValue("@UnitNumber", vehicle.UnitNumber); cmd.Parameters.AddWithValue("@AptNumber", vehicle.AptNumber); con.Open(); int i = cmd.ExecuteNonQuery(); con.Close(); if (i >= 1) return true; else return false; } // ********************** DELETE VEHICLE DETAILS ******************* public bool DeleteVehicle(int id) { connection(); SqlCommand cmd = new SqlCommand("DeleteVehicle", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@VehicleId", id); con.Open(); int i = cmd.ExecuteNonQuery(); con.Close(); if (i >= 1) return true; else return false; } // ********** SEARCH VEHICLE OWNER'S ******************** public OwnerContactDto GetVehicleOwner(int registrationNumber) { connection(); SqlCommand cmd = new SqlCommand("GetVehicleOwner", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@RegistrationNumber", registrationNumber); SqlDataAdapter sd = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); con.Open(); sd.Fill(dt); if(dt.Rows.Count < 1) { return null; } con.Close(); OwnerContactDto owner = new OwnerContactDto { FirstName = Convert.ToString(dt.Rows[0]["FirstName"]), PhoneNumber = Convert.ToString(dt.Rows[0]["PhoneNumber"]), RegistrationNumber = Convert.ToInt32(dt.Rows[0]["RegistrationNumber"]) }; return owner; } } }
Python
UTF-8
1,127
3.046875
3
[]
no_license
#!/usr/bin/python import pandas as pd from lxml import html import requests #Names as reference names = ['Airfish', 'Seren', 'Move-ez', 'MAVERICK', 'Pandawacakra', 'The Zero Heroes', 'HKU-ARG', 'FlyLite', 'NI Aerospace', 'Waitless Technology Group'] #import dataframe df = pd.read_csv('video_data.csv') #scrape airbus data page = requests.get('https://www.airbus-fyi.com/video-competition/') tree = html.fromstring(page.content) #This will create a list of teams: teams = tree.xpath('//span[@class="teamname"]/text()') #This will create a list of totals totals = tree.xpath('//span[@class="tot"]/text()') #create dictionary for mapping indices dct = {'Airfish':0,'Seren':1, 'Move-ez':2,'MAVERICK':3,'Pandawacakra':4, 'The Zero Heroes':5,'HKU-ARG':6,'FlyLite':7,'NI Aerospace':8,'Waitless Technology Group':9} # put the mapping in to a list mapping = [dct[k] for k in teams] # create an empty list import numpy as np a_list = np.empty(10, dtype=int) for a in mapping: a_list[a] = totals[mapping.index(a)] df2 = pd.DataFrame([a_list], columns=names) df = pd.concat([df,df2]) df.to_csv('video_data.csv', index=False)
PHP
UTF-8
1,246
2.703125
3
[]
no_license
<?php // abifunktsioonid include 'helper.php'; $fullTimeNow = date("d.m.Y H:i:s"); // <p>Lehe avamise hetkel oli: <strong>31.01.2020 11:32:07</strong></p> $timeHTML = "\n <p>Lehe avamise hetkel oli: <strong>" . $fullTimeNow . "</strong></p> \n"; $hourNow = date("H"); $partOfDay = "hägune aeg"; // Kodune_1 #3 määran muutuja vaikeväärtused $partOfDayBg = "f1f1f1"; $partOfDayFo = "000"; if ($hourNow < 10) { $partOfDay = "hommik"; } elseif ($hourNow >= 10 and $hourNow <= 18) { $partOfDay = "aeg aktiivselt tegutseda"; } else { // Kodune_1 #3 Kui kell on peale 6-te õhtul, // siis vahetab tausta- ja fondi värvi $partOfDay = "õhtu"; $partOfDayBg = "142634"; $partOfDayFo = "bdc7c1"; } $partOfDayHTML = "<p>Käes on " . $partOfDay . "!</p> \n"; ?> <!DOCTYPE html> <html lang="et"> <head> <meta charset="utf-8"> <title>Veebirakendused ja nende loomine 2020</title> <style> body { background-color: #<?php echo $partOfDayBg ?>; color: #<?php echo $partOfDayFo ?>; } </style> </head> <body> <!-- <h1><?php echo $myName ?></h1> --> <!-- <p>See leht on valminud õppetöö raames!</p> --> <?php echo $timeHTML; echo $partOfDayHTML; // echo $semesterProgressHTML; ?> </body> </html>
C#
UTF-8
5,251
2.9375
3
[]
no_license
using System; using System.Linq; using Parser.Parser.Expressions; using Parser.Parser.Statements; namespace Parser.ILCompiler { public class ExpressionVisitor { protected virtual IStatement VisitStatement(IStatement statement) { switch (statement.ExpressionType) { case ExpressionType.Assignment: return VisitAssignment((AssignmentStatement) statement); case ExpressionType.Return: return VisitReturn((ReturnStatement) statement); case ExpressionType.IfElse: return VisitIfElse((IfElseStatement) statement); case ExpressionType.VoidMethodCallStatement: return VisitVoidMethod((VoidMethodCallStatement) statement); case ExpressionType.Statement: return VisitVoidMethod((VoidMethodCallStatement) statement); default: throw new ArgumentOutOfRangeException(); } } protected virtual VoidMethodCallStatement VisitVoidMethod(VoidMethodCallStatement statement) { var method = VisitMethod(statement.Method); return new VoidMethodCallStatement(method); } protected virtual IExpression VisitExpression(IExpression expression) { return expression.ExpressionType switch { ExpressionType.LocalVariable => (IExpression) VisitLocalVariable((LocalVariableExpression) expression), ExpressionType.FieldVariable => (IExpression) VisitField((FieldVariableExpression) expression), ExpressionType.MethodArgVariable => (IExpression) VisitMethodArgument( (MethodArgumentVariableExpression) expression), ExpressionType.Primary => VisitPrimary((PrimaryExpression) expression), ExpressionType.Binary => VisitBinary((BinaryExpression) expression), ExpressionType.Unary => VisitUnary((UnaryExpression) expression), ExpressionType.MethodCallParameter => VisitMethodCallParameter( (MethodCallParameterExpression) expression), ExpressionType.MethodCallExpression => VisitMethod((MethodCallExpression) expression), ExpressionType.Logical => VisitLogical((LogicalBinaryExpression) expression), _ => throw new ArgumentOutOfRangeException() }; } protected virtual MethodCallParameterExpression VisitMethodCallParameter(MethodCallParameterExpression exp) { var newExp = VisitExpression(exp.Expression); return new MethodCallParameterExpression(newExp, exp.ParameterInfo); } protected virtual MethodArgumentVariableExpression VisitMethodArgument( MethodArgumentVariableExpression expression) { return expression; } protected virtual FieldVariableExpression VisitField(FieldVariableExpression expression) { return expression; } protected virtual LogicalBinaryExpression VisitLogical(LogicalBinaryExpression logical) { return logical; } protected virtual Statement VisitStatement(Statement statement) { return new Statement(statement.Statements.Select(VisitStatement).ToArray()); } protected virtual IfElseStatement VisitIfElse(IfElseStatement statement) => statement; protected virtual BinaryExpression VisitBinary(BinaryExpression binaryExpression) { var left = VisitExpression(binaryExpression.Left); var right = VisitExpression(binaryExpression.Right); return new BinaryExpression(left, right, binaryExpression.TokenType); } protected virtual ReturnStatement VisitReturn(ReturnStatement returnStatement) { VisitExpression(returnStatement.Returned); return returnStatement; } protected virtual AssignmentStatement VisitAssignment(AssignmentStatement assignmentStatement) { VisitExpression(assignmentStatement.Right); return assignmentStatement; } protected virtual IExpression VisitUnary(UnaryExpression unaryExpression) { var expression = VisitExpression(unaryExpression.Expression); return new UnaryExpression(expression, UnaryType.Negative); } protected virtual PrimaryExpression VisitPrimary(PrimaryExpression primaryExpression) { return primaryExpression; } protected virtual MethodCallExpression VisitMethod(MethodCallExpression methodCallExpression) { var expressions = methodCallExpression.Parameters.Select(VisitExpression) .Cast<MethodCallParameterExpression>() .ToArray(); return new MethodCallExpression(methodCallExpression.Name, methodCallExpression.MethodInfo, expressions); } protected virtual VariableExpression VisitLocalVariable(LocalVariableExpression variable) { return variable; } } }
Swift
UTF-8
5,005
5.03125
5
[]
no_license
import UIKit // Optionals: is a type that represents two possibilities, either we have a value or we do not have a value (nil). // Swift data types support optionals, e.g. /* String - this is a literal string */ //============================================== // Introduction of Optionals //============================================== var name:String = "Stephanie" print(name) var age: Int? = 21 // the question mark sets it as optional print(age) // prints nil. var num = Int("5") // using the int initializer to a string, the variable is automatically assigned to an optional int because its not certain it is definately a value. 5 could have been five. //============================================== // Ways to Unwrap Optionals //============================================== /* 1. Forced unwrapping using an exclamation mark ! or some programming refer to it as banging ! 2. Nil-coalescing using two question marks ?? followed by a default value that we provide 3. Optional-binding using if let, where a value is assigned the existing if one is available. 4. Implicit unwrapping e.g. var name: String! (this will be discussed later in unit 2.) */ //============================================== // Forced Unwrapping //============================================== let decadeFromNow = age! + 10 // int optional and int print(decadeFromNow) // you cannot add these datatypes // however if you add ! after the age you can infer the optional nil to an optional. // the application still crashes because you cannot force unwrap a nil. // the application still crashes if your value is a string int "21" //============================================== // Nil-Coalescing //============================================== var temp: Int? = 75 // degrees let validTemperature = temp ?? 67 // the new variable unwraps temperature (75) with the nil-coalescing. 67 is the new temperature in case if temperature is nil print("Temperature is \(validTemperature)") var cohort: Int? var nextYearCohort = (cohort ?? 5) + 1 // you have to option to add the parathensis print(nextYearCohort) //============================================== // Optional Binding: if let, while let //============================================== var wage:Int? // dollars var year:Int? // nil by default if let validWage = wage, let validYear = year { // the wage and year must have to be a valid in order to it printed. this acts like an &&. // look at wage (int 40,000)and if let wage (optional) has a valid value and not a nil, then assign it to bindedValue constant int data type. This is also a condition print("You entered \(validWage) as your wage in the current year \(validYear)") // if wage has a value then if let is true, validWage is a constant // if wage is nil then if let is false } else { print("You did not enter a valid value, \(String(describing: wage)) or values are unavailable") // because wage is an optional int it assigns it to a string describing to grab the value of wage // string interpolation cannot have an optional datatype // string describing silences the error } // this is another way of verifying only if wage is not a nil if wage != nil { // 1. wage within the if is still optional // 2. not idiomatic swift (swifty) } // quite note if 5 < 10 { // this is a condition } // string interpolation var modelYear: Int? = 2016 print("Model year is \(modelYear ?? 1959)") // if you don't have an optional int valid value //============================================== // Testing Optional for Equality //============================================== var someValue: Int? = 7 if someValue == 7 { print("\(String(describing: someValue)) is equal to 7") // optional 7 would print in the console pane // you can also force unwrap in the string interpolation } //============================================== // Looping Through an Optional Array //============================================== var numbers:[Int?] // the ? inside the square brackets indicates it is an optional array of ints. numbers = [4, 9, nil, 10, 20, nil] // add only valid ints var sumUnwrappedUsingOptionalBinding = 0 var sumUsingNilCoalescing = 0 for num in numbers { // num is an optional int // if you put the var sum = 0 inside the block then it creates an error because the varibale has already been declared in the for loop if let validNum = num { // validNum is an int. optional binding to unwrap the current num. sumUnwrappedUsingOptionalBinding += validNum } sumUsingNilCoalescing += num ?? 0 // this still prints all the ints // you would have to nil coalescene it } print("The sum of numbers is \(sumUnwrappedUsingOptionalBinding)") print("The sum of numbers is \(sumUsingNilCoalescing)") var isAbscent: Bool? if let unwrappedValue = isAbscent { print(unwrappedValue) } else { print("This does not have a value") }
Python
UTF-8
90
2.875
3
[]
no_license
import json a = {'a': 'a', 'b': ['a', 'b']} print(a) json_a = json.dumps(a) print(json_a)
Python
UTF-8
510
2.984375
3
[]
no_license
import os import pandas as pd input_file_name = 'sai' excel_file = input_file_name+'.xlsx' cwd=os.getcwd() df = pd.read_excel(excel_file,sheet_name='Sheet4') first = list(df['first']) second = list(df['second']) first = [x.strip() for x in first if type(x) == str] second = [x.strip() for x in second if type(x) == str] first= list(set(first)) second = list(set(second)) counter = 0 for i in first: for j in second: if i ==j: counter+=1 print(i,j) print(counter)
Java
UTF-8
3,240
2.3125
2
[]
no_license
package org.realty.entity; import javax.persistence.*; import java.util.List; @Entity @Table(name = "advert") public class Advert { private String addedDate; private String category; private int rooms; // private Long adressId; private int coast; private String description; private Long advertId; // private Long userId; private List<Comment> comments; private Adress adress; private User user; public Advert() { } @Column(name = "added_date") public String getAddedDate() { return addedDate; } @Column(name = "category") public String getCategory() { return category; } @Column(name = "coast") public int getCoast() { return coast; } @Column(name = "description") public String getDescription() { return description; } @Id @Column(name = "advert_id") @GeneratedValue public Long getAdvertId() { return advertId; } public void setAddedDate(String addedDate) { this.addedDate = addedDate; } public void setCategory(String newVal) { this.category = newVal; } public void setCoast(int newVal) { this.coast = newVal; } public void setDescription(String newVal) { this.description = newVal; } public void setAdvertId(Long newVal) { this.advertId = newVal; } /* @Column(name = "user_id") public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; }*/ @Column(name = "rooms") public int getRooms() { return rooms; } public void setRooms(int rooms) { this.rooms = rooms; } /* // @Column(name="adressId") @Transient public Long getAdressId() { return adressId; } public void setAdressId(Long adressId) { this.adressId = adressId; }*/ @Override public boolean equals(Object other) { return (other instanceof Advert) && (advertId != null) ? advertId .equals(((Advert) other).advertId) : (other == this); } @Override public int hashCode() { return (advertId != null) ? (this.getClass().hashCode() + advertId .hashCode()) : super.hashCode(); } /* @Override public String toString() { return String.format("Advert[addedDate=%s,category=%s,rooms=%s,adressId=%d," + " coast=%d, description=%s, advertId=%d, userId=%d]", addedDate, category, getRooms(), getAdressId(), coast, description, advertId, userId); }*/ @OneToMany(mappedBy="advert") public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } @OneToOne(cascade = CascadeType.REMOVE) @JoinColumn(name="adressId") public Adress getAdress() { return adress; } public void setAdress(Adress adress) { this.adress = adress; } @ManyToOne @JoinColumn(name="user_id") public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
Markdown
UTF-8
8,194
3.96875
4
[ "Apache-2.0", "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
--- layout: default description: Some operators expect their operands to have a certain data type --- Type check and cast functions ============================= Some operators expect their operands to have a certain data type. For example, logical operators expect their operands to be boolean values, and the arithmetic operators expect their operands to be numeric values. If an operation is performed with operands of other types, an automatic conversion to the expected types is tried. This is called implicit type casting. It helps to avoid query aborts. Type casts can also be performed upon request by invoking a type cast function. This is called explicit type casting. AQL offers several functions for this. Each of the these functions takes an operand of any data type and returns a result value with the type corresponding to the function name. For example, *TO_NUMBER()* will return a numeric value. Type casting functions ---------------------- ### TO_BOOL() `TO_BOOL(value) → bool` Take an input *value* of any type and convert it into the appropriate boolean value. - **value** (any): input of arbitrary type - returns **bool** (boolean): - *null* is converted to *false* - Numbers are converted to *true*, except for 0, which is converted to *false* - Strings are converted to *true* if they are non-empty, and to *false* otherwise - Arrays are always converted to *true* (even if empty) - Objects / documents are always converted to *true* It's also possible to use double negation to cast to boolean: ```aql !!1 // true !!0 // false !!-0.0 // false not not 1 // true !!"non-empty string" // true !!"" // false ``` `TO_BOOL()` is preferred however, because it states the intention clearer. ### TO_NUMBER() `TO_NUMBER(value) → number` Take an input *value* of any type and convert it into a numeric value. - **value** (any): input of arbitrary type - returns **number** (number): - *null* and *false* are converted to the value *0* - *true* is converted to *1* - Numbers keep their original value - Strings are converted to their numeric equivalent if the string contains a valid representation of a number. Whitespace at the start and end of the string is allowed. String values that do not contain any valid representation of a number will be converted to the number *0*. - An empty array is converted to *0*, an array with one member is converted into the result of `TO_NUMBER()` for its sole member. An array with two or more members is converted to the number *0*. - An object / document is converted to the number *0*. - A unary plus will also cast to a number, but `TO_NUMBER()` is the preferred way: ```aql +'5' // 5 +[8] // 8 +[8,9] // 0 +{} // 0 ``` - A unary minus works likewise, except that a numeric value is also negated: ```aql -'5' // -5 -[8] // -8 -[8,9] // 0 -{} // 0 ``` ### TO_STRING() `TO_STRING(value) → str` Take an input *value* of any type and convert it into a string value. - **value** (any): input of arbitrary type - returns **str** (string): - *null* is converted to an empty string `""` - *false* is converted to the string *"false"*, *true* to the string *"true"* - Numbers are converted to their string representations. This can also be a scientific notation (e.g. "2e-7") - Arrays and objects / documents are converted to string representations, which means JSON-encoded strings with no additional whitespace ```aql TO_STRING(null) // "" TO_STRING(true) // "true" TO_STRING(false) // "false" TO_STRING(123) // "123" TO_STRING(+1.23) // "1.23" TO_STRING(-1.23) // "-1.23" TO_STRING(0.0000002) // "2e-7" TO_STRING( [1, 2, 3] ) // "[1,2,3]" TO_STRING( { foo: "bar", baz: null } ) // "{\"foo\":\"bar\",\"baz\":null}" ``` ### TO_ARRAY() `TO_ARRAY(value) → array` Take an input *value* of any type and convert it into an array value. - **value** (any): input of arbitrary type - returns **array** (array): - *null* is converted to an empty array - Boolean values, numbers and strings are converted to an array containing the original value as its single element - Arrays keep their original value - Objects / documents are converted to an array containing their attribute **values** as array elements, just like [VALUES()](functions-document.html#values) ```aql TO_ARRAY(null) // [] TO_ARRAY(false) // [false] TO_ARRAY(true) // [true] TO_ARRAY(5) // [5] TO_ARRAY("foo") // ["foo"] TO_ARRAY([1, 2, "foo"]) // [1, 2, "foo"] TO_ARRAY({foo: 1, bar: 2, baz: [3, 4, 5]}) // [1, 2, [3, 4, 5]] ``` ### TO_LIST() `TO_LIST(value) → array` This is an alias for [TO_ARRAY()](#to_array). Type check functions -------------------- AQL also offers functions to check the data type of a value at runtime. The following type check functions are available. Each of these functions takes an argument of any data type and returns true if the value has the type that is checked for, and false otherwise. ### IS_NULL() `IS_NULL(value) → bool` Check whether *value* is *null*. Identical to `value == null`. To test if an attribute exists, see [HAS()](functions-document.html#has) instead. - **value** (any): value to test - returns **bool** (boolean): *true* if *value* is `null`, *false* otherwise ### IS_BOOL() `IS_BOOL(value) → bool` Check whether *value* is a *boolean* value - **value** (any): value to test - returns **bool** (boolean): *true* if *value* is `true` or `false`, *false* otherwise ### IS_NUMBER() `IS_NUMBER(value) → bool` Check whether *value* is a number - **value** (any): value to test - returns **bool** (boolean): *true* if *value* is a number, *false* otherwise ### IS_STRING() `IS_STRING(value) → bool` Check whether *value* is a string - **value** (any): value to test - returns **bool** (boolean): *true* if *value* is a string, *false* otherwise ### IS_ARRAY() `IS_ARRAY(value) → bool` Check whether *value* is an array / list - **value** (any): value to test - returns **bool** (boolean): *true* if *value* is an array / list, *false* otherwise ### IS_LIST() `IS_LIST(value) → bool` This is an alias for [IS_ARRAY()](#is_array) ### IS_OBJECT() `IS_OBJECT(value) → bool` Check whether *value* is an object / document - **value** (any): value to test - returns **bool** (boolean): *true* if *value* is an object / document, *false* otherwise ### IS_DOCUMENT() `IS_DOCUMENT(value) → bool` This is an alias for [IS_OBJECT()](#is_object) ### IS_DATESTRING() `IS_DATESTRING(str) → bool` Check whether *value* is a string that can be used in a date function. This includes partial dates such as *"2015"* or *"2015-10"* and strings containing properly formatted but invalid dates such as *"2015-02-31"*. - **str** (string): date string to test - returns **bool** (boolean): *true* if *str* is a correctly formatted date string, *false* otherwise including all non-string values, even if some of them may be usable in date functions (numeric timestamps) ### IS_IPV4() See [String Functions](functions-string.html#is_ipv4). ### IS_KEY() `IS_KEY(str) → bool` Check whether *value* is a string that can be used as a document key, i.e. as the value of the *_key* attribute. See [Document keys](../data-modeling-documents.html#document-keys). - **str** (string): document key to test - returns **bool** (boolean): whether *str* can be used as document key ### TYPENAME() `TYPENAME(value) → typeName` Return the data type name of *value*. - **value** (any): input of arbitrary type - returns **typeName** (string): data type name of *value* (`"null"`, `"bool"`, `"number"`, `"string"`, `"array"` or `"object"`) Example Value | Data Type Name ---------------:|--------------- `null` | `"null"` `true` | `"bool"` `false` | `"bool"` `123` | `"number"` `-4.56` | `"number"` `0` | `"number"` `"foobar"` | `"string"` `"123"` | `"string"` `""` | `"string"` `[ 1, 2, 3 ]` | `"array"` `["foo",true]` | `"array"` `[ ]` | `"array"` `{"foo":"bar"}` | `"object"` `{"foo": null}` | `"object"` `{ }` | `"object"`
Python
UTF-8
1,273
3.109375
3
[ "MIT" ]
permissive
""" Account class used to store liquid balance and market value of session. The class integrates with the trade log class in order to check market value. """ # from trade_log import TradeLog as tl class Account: def __init__(self, cash): self.cash = cash self.market_val = 0 # self.trade_log = trade_log # Getters def available_cash(self): return self.cash def get_market_value(self): return self.market_val # Accessors def set_market_value(self, market_value): # trade_log function 'portfolio_to_value' needs to be used to get # market value self.market_val = market_value pass def update(self, amount, action, market_value): if action == "buy": if self.cash - amount < 0: raise Exception("Account's cash balance cannot go negative") self.cash -= amount self.set_market_value(market_value) if action == "sell": self.cash += amount self.set_market_value(market_value) # Status def solvent(self): if self.market_val + self.cash > 0: return True else: raise RuntimeError('Account is no longer solvent') return False
C#
UTF-8
10,545
2.65625
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using HandlebarsDotNet; namespace Blockfrost.Api.Generate { internal partial class Program { internal static string Source { get; set; } internal static DirectoryInfo TemplateDir { get; set; } internal static DirectoryInfo OutputDir { get; set; } internal static char[] GeneratorSwitch { get; set; } = "smav".ToCharArray(); internal static string[] PreservationFilters { get; set; } = Array.Empty<string>(); internal static string[] PurgeFilters { get; set; } = new[] { "*.generated*" }; internal static bool ShouldWrite(char flag) { return GeneratorSwitch.Contains(flag); } internal static async Task Main(string[] args) { try { var context = await SetupEnvironment(args); PurgeFiles(); Console.WriteLine("Generating blockfrost-dotnet boilerplate..."); await WriteVarious(context); await WriteAttributes(context); await WriteModels(context); await WriteServices(context); Console.WriteLine("done!"); } catch (KeyNotFoundException) { StringBuilder usage = new StringBuilder(); usage.AppendLine("Blockfrost.Api.Generate.exe -s SOURCE -o OUTPUT_DIR -t TEMPLATE_DIR -g <[m]odels | [s]ervices | [a]ttributes | [v]arious>"); usage.AppendLine(""); usage.AppendLine("Parameters:"); usage.Append(" -s").Append('\t').AppendLine("Local path or Uri of Blockfrost OpenApi Specification. Supported formats: [json, yaml]"); usage.Append(" -t").Append('\t').AppendLine("Local template directory"); usage.Append(" -o").Append('\t').AppendLine("Local output directory"); usage.Append(" -g").Append('\t').AppendLine("Generator switch (default '-g smav' = all"); usage.Append(" --purge [searchPattern, ...]").Append('\t').AppendLine("Delete all files matching one of the expressions (default '*.generated*')"); usage.Append(" --preserve [searchPattern, ...]").Append('\t').AppendLine("Preserve all files matching one of the expressions (default '' = none"); System.Console.WriteLine(usage.ToString()); } catch (Exception ex) { Console.Error.WriteLine("An error has occurred"); Console.Error.WriteLine(ex); } } private static void PurgeFiles() { var purgeFiles = PurgeFilters.SelectMany(searchPattern => OutputDir.GetDirectories("*", SearchOption.AllDirectories).SelectMany(dir => dir.GetFiles(searchPattern, new EnumerationOptions() { MatchCasing = MatchCasing.CaseSensitive } ))).ToList(); if (purgeFiles.Any()) { Console.WriteLine(); Console.WriteLine($"Purging [{string.Join(',', PurgeFilters)}]..."); Console.WriteLine($"There are {purgeFiles.Count} files that will be deleted."); Console.WriteLine("Delete all files? [Y]es to all, [N]o to all, [I]nteractive"); var key = Console.ReadKey().Key; foreach (var file in purgeFiles) { if (key == ConsoleKey.N) { break; } if (key == ConsoleKey.I) { Console.WriteLine($"Delete '{file.FullName}'? (ENTER: confirm, OTHER: skip)"); if (Console.ReadKey().Key == ConsoleKey.Enter) file.Delete(); } if (key == ConsoleKey.Y) { file.Delete(); } } } } private static void WriteInfo(OpenApiDocumentContext context) { StringBuilder info = new StringBuilder(); info.AppendLine($"Blockfrost Specification: {context.Spec.Info.Version}"); Console.WriteLine(info.ToString()); } private static async Task<OpenApiDocumentContext> SetupEnvironment(string[] args) { var list = args.ToList(); var opt = new Dictionary<string, string>(); while (list.Any()) { var hasOption = list.Count > 1 && !list[1].StartsWith("-"); if (hasOption) { opt.Add(list[0], list[1]); list = list.Skip(2).ToList(); } else { opt.Add(list[0], null); list = list.Skip(1).ToList(); } } if (opt.ContainsKey("-g") && opt["-g"] != null) { GeneratorSwitch = opt["-g"].ToCharArray(); } if (opt.ContainsKey("--preserve") && opt["--preserve"] != null) { PreservationFilters = opt["--preserve"].Split(",").Select(pattern => pattern.Trim()).ToArray(); } if (opt.ContainsKey("--purge") && opt["--purge"] != null) { PurgeFilters = opt["--purge"].Split(",").Select(pattern => pattern.Trim()).ToArray(); } OutputDir = new DirectoryInfo(opt["-o"]); if (!OutputDir.Exists) { OutputDir.Create(); } TemplateDir = new DirectoryInfo(opt["-t"]); TemplateHelper.RegisterPartials(TemplateDir); Source = opt["-s"]; var docs = await TemplateHelper.GetSpecsAsync(Source); var context = new OpenApiDocumentContext(OutputDir, docs); TemplateHelper.RegisterHelpers(); WriteInfo(context); return context; } private static async Task WriteVarious(OpenApiDocumentContext context) { if (!ShouldWrite('v')) return; await WriteFile(context.ServiceExtension, "BlockfrostServiceExtensions.hbr", "Extensions", "BlockfrostServiceExtensions.cs"); await WriteFile(null, "StringBuilderExtensions.hbr", "Extensions", "StringBuilderExtensions.cs"); await WriteFile(null, "BlockfrostHashCode.hbr", "Utils", "BlockfrostHashCode.cs"); await WriteFile(null, "Enums.hbr", "Models", "Enums.cs"); await WriteFile(null, "ApiException.hbr", "Models", "Http", "ApiException.cs"); await WriteFile(null, "HttpErrorResponse.hbr", "Models", "Http", "HttpErrorResponse.cs"); await WriteFile(null, "IBlockfrostService.hbr", "Services", "IBlockfrostService.cs"); await WriteFile(null, "ABlockfrostService.hbr", "Services", "ABlockfrostService.cs"); Console.WriteLine(); } private static async Task WriteServices(OpenApiDocumentContext context) { if (!ShouldWrite('s')) return; foreach (var serviceContext in context.Services) { await WriteFile(serviceContext, "service_interface.hbr", "Services", $"I{TemplateHelper.PascalCase(serviceContext.ServiceName)}Service.cs"); await WriteFile(serviceContext, "service.hbr", "Services", serviceContext.GroupName, $"{TemplateHelper.PascalCase(serviceContext.ServiceName)}Service.cs"); } Console.WriteLine(); } private static async Task WriteModels(OpenApiDocumentContext context) { if (!ShouldWrite('m')) return; // Write StringCollection for untyped responses await WriteFile(null, "StringCollection.hbr", "Models", "StringCollection.cs"); // write Models foreach (var modelContext in context.Models) { await WriteFile(modelContext, "model.hbr", "Models", $"{TemplateHelper.PascalCase(modelContext.ClassName)}.cs"); // write items if any if (modelContext.HasItem) { await WriteFile(modelContext.ItemContext, "model.hbr", "Models", $"{TemplateHelper.PascalCase(modelContext.ItemContext.ClassName)}.cs"); } } Console.WriteLine(); } private static async Task WriteAttributes(OpenApiDocumentContext context) { if (!ShouldWrite('a')) return; foreach (var attributeContext in context.HttpAttributes) { await WriteFile(attributeContext, "httpAtts.hbr", "Http", $"{TemplateHelper.PascalCase(attributeContext.HttpMethod)}Attribute.cs"); } Console.WriteLine(); } internal static async Task WriteFile(object data, string templateFileName, params string[] filepath) { var file = new FileInfo(Path.Combine(OutputDir.FullName, Path.Combine(filepath))); if (!file.Directory.Exists) { Console.WriteLine($"Creating\t{file.Directory}"); file.Directory.Create(); } var preserveExisting = PreservationFilters.SelectMany(searchPattern => file.Directory.GetFiles(searchPattern)).Any(f => f.FullName.Equals(file.FullName)); if (file.Exists && preserveExisting) { var fullname = file.FullName; var ix = fullname.LastIndexOf('.'); Console.WriteLine($"Preserving\t{file.FullName}"); await WriteFile(data, templateFileName, fullname.Insert(ix, ".generated")); return; } using var fi = file.CreateText(); var template = Handlebars.Compile(File.ReadAllText(Path.Combine(TemplateDir.FullName, templateFileName))); var bytes = fi.Encoding.GetBytes(template(data)); if (file.Exists) { Console.WriteLine($"Overwriting\t{file.FullName}"); } else { Console.WriteLine($"Writing \t{file.FullName}"); } await fi.WriteLineAsync(Encoding.UTF8.GetString(bytes)); await fi.FlushAsync(); fi.Close(); } } }
C++
UTF-8
1,031
2.703125
3
[ "MIT" ]
permissive
#ifndef CUBOID_H #define CUBOID_H #include "GPoint.h" #include "GVector.h" #include <algorithm> class GCuboid{ private: bool bDetector = false; public: //Diagonal points defining the cuboid GPoint bl; GPoint tr; //Jiawei-Jan03 //This is a dangerous bug. I lef them as public so that //GVector* GCuboidSource::GenerateOneRay() could call them. Need to fix. GCuboid(bool bIsDetector = false){ bDetector = bIsDetector; bl.SetPos(0,0,0); tr.SetPos(0,0,0); } GCuboid(double x1, double y1, double z1, double x2, double y2, double z2, bool bIsDetector = false){ bDetector = bIsDetector; bl.SetPos(x1, y1, z1); tr.SetPos(x2, y2, z2); } GCuboid(GPoint gs_InBl, GPoint gs_InTr, bool bIsDetector = false){ bDetector = bIsDetector; bl.SetPos(gs_InBl.x, gs_InBl.y, gs_InBl.z); tr.SetPos(gs_InTr.x, gs_InTr.y, gs_InTr.z); } //If a vector "collides" with cuboid. Return the timing of enter and exit. bool IfCollide(GVector* g_sVec, double& t1, double &t2); bool IsDetector(){ return bDetector; } }; #endif
Ruby
UTF-8
2,196
2.59375
3
[ "MIT" ]
permissive
module Zeitungen class IndexPage def initialize(url, password) @url = url @password = password end def links(date) date_string = date.to_s # date.strftime("%Y-%m-%d") t = Time.now all_quotidie_links = [] puts "Downloading zeitungens for #{date_string}" puts "-----------------------------------" agent = Mechanize.new agent.get(@url) do |page| # compilo form autenticazione form = page.forms.first form.password = @password # non so perche arriva un'altro form precompilato form2 = agent.submit(form).forms.first # la pagina con i diversi giorni quotidie_page = agent.submit(form2) # finalmente l'url della pagina con la lista dei quotidiani rgxp = Regexp.new("^"+date.strftime("%d.%m.%Y")) page = quotidie_page # puts page # exit # puts page.links.map{|l| "#{l} -> #{l.attributes.parent.parent.path}"}.inspect # /html/body/section/section/div/div[1]/article[1]/div/section[1]/div/div # tutti i link utili [0,1,2,3].each do |a| all_quotidie_links = page.links.find_all { |link| link.attributes.parent.parent.path == "/html/body/section/section/div/article[#{a}]/div/section[1]/div/div" } break if all_quotidie_links.size > 3 end if all_quotidie_links.size==0 [0,1,2,3].each do |a| all_quotidie_links = page.links.find_all { |link| link.attributes.parent.parent.path == "/html/body/section/section/div/div/article[#{a}]/div/section[1]/div/div" } break if all_quotidie_links.size > 3 end end if all_quotidie_links.size==0 [0,1,2,3].each do |a| all_quotidie_links = page.links.find_all do |link| link.attributes.parent.parent.path == "/html/body/section/section/div/div[1]/article[#{a}]/div/section[1]/div/div" end break if all_quotidie_links.size > 3 end end end puts "Parsing zeitungen page takes #{Time.now-t}s" all_quotidie_links end end end
Shell
UTF-8
832
3.296875
3
[ "MIT" ]
permissive
#!/bin/bash REMOTE_ORIGIN_URL=$(git config --local remote.origin.url | cut -d'/' -f1) GIT_URL="git@github.com:yuxia228" GIT_USER_NAME="yuxia228" GIT_USER_EMAIL="yuxia228@gmail.com" USER_NAME=`git config user.name` USER_EMAIL=`git config user.email` ERROR () { echo "git config is wrong." echo " user.name is $USER_NAME" echo " user.email is $USER_EMAIL" echo "Please execute following commands" echo " git config --local user.name $GIT_USER_NAME" echo " git config --local user.email $GIT_USER_EMAIL" echo "" echo "If you ignore this pre-commit, please add 'git commit --no-verify'" exit 1 } if [[ "$REMOTE_ORIGIN_URL" = "$GIT_URL" ]]; then if [[ "$USER_NAME" != "$GIT_USER_NAME" ]]; then ERROR elif [[ "$USER_EMAIL" != "$GIT_USER_EMAIL" ]]; then ERROR fi fi exit 0
Java
UTF-8
1,871
1.789063
2
[]
no_license
package com.arrow.trade.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Entity @Getter @Setter @Table(name = "CHANGE_REQUEST") @ToString public class ChangeRequests { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence") @SequenceGenerator(name = "id_Sequence", sequenceName = "ID_SEQ") private Long id; @ManyToOne @JoinColumn(name = "changeSetId") private ChangeSet changeSet; @Column(name = "PART_KEY") private String partKey; @Column(name = "FIELD_NAME") private String fieldName; @Column(name = "ORIGINAL_VALUE") private String originalValue; @Column(name = "NEW_VALUE") private String newValue; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) @Column(name = "CREATED_AT") private Date createdAt; @UpdateTimestamp @Temporal(TemporalType.TIMESTAMP) @Column(name = "UPDATED_AT") private Date updatedAt; @Column(name = "UPDATED_BY") private String updatedBy; @Column(name = "APPROVED") private String approved; @Column(name = "APPROVED_BY") private String approvedBy; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) @Column(name = "APPROVAL_DATE") private Date approvalDate; @Column(name = "HAS_ORDER_NUMBER") private boolean hasOrderNumber; }
C#
UTF-8
1,085
3.484375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace orderOfOps { class Program { static void Main(string[] args) { /* Noel Mowatt 08/31/2016 Order Of Operations PEMDAS Parenthesis Exponent Multiplication Division Addition Subtraction */ //--Find mean of 4 quiz scores //--Create quiz scores double quiz = 85; double quiz2 = 100; double quiz3 = 80; double quiz4 = 90; //--Average double mean = (quiz + quiz2 + quiz3 + quiz4) / 4; Console.WriteLine("The mean of your quiz scores is: " + mean); //--Find perimeter of rectangle int length = 8; int widthRect = 6; int perimeterRect = (2 * length) + (2 * widthRect); Console.WriteLine("The perimeter is: " + perimeterRect); } } }
Java
UTF-8
2,935
2.28125
2
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "MIT" ]
permissive
package com.testingbot.tunnel.proxy; import com.testingbot.tunnel.App; import org.eclipse.jetty.servlets.ProxyServlet; import java.net.MalformedURLException; import java.util.Arrays; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.HttpExchange; import org.eclipse.jetty.http.HttpURI; public class ForwarderServlet extends ProxyServlet { private final App app; public ForwarderServlet(App app) { this.app = app; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); } @Override protected HttpURI proxyHttpURI(String scheme, String serverName, int serverPort, String uri) throws MalformedURLException { if (!validateDestination(serverName,uri)) return null; return new HttpURI("http://127.0.0.1:4446" + uri); } @Override protected void customizeExchange(HttpExchange exchange, HttpServletRequest request) { exchange.addRequestHeader("TB-Tunnel", this.app.getServerIP()); exchange.addRequestHeader("TB-Credentials", this.app.getClientKey() + "_" + this.app.getClientSecret()); exchange.addRequestHeader("TB-Tunnel-Version", this.app.getVersion()); if (this.app.isBypassingSquid()) { exchange.addRequestHeader("TB-Tunnel-Port", "2010"); } for (String key : app.getCustomHeaders().keySet()) { exchange.addRequestHeader(key, app.getCustomHeaders().get(key)); } Logger.getLogger(ForwarderServlet.class.getName()).log(Level.INFO, " >> [{0}] {1}", new Object[]{request.getMethod(), request.getRequestURL()}); if (app.isDebugMode()) { Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { StringBuilder sb = new StringBuilder(); String header; while (headerNames.hasMoreElements()) { header = headerNames.nextElement(); sb.append(header).append(": ").append(request.getHeader(header)).append(System.getProperty("line.separator")); } Logger.getLogger(ForwarderServlet.class.getName()).log(Level.INFO, sb.toString()); } } } @Override protected void handleOnException(Throwable ex, HttpServletRequest request, HttpServletResponse response) { super.handleOnException(ex, request, response); Logger.getLogger(ForwarderServlet.class.getName()).log(Level.WARNING, "Error when forwarding request: {0} {1}", new Object[]{ex.getMessage(), Arrays.toString(ex.getStackTrace())}); } }
JavaScript
UTF-8
3,675
2.765625
3
[ "MIT" ]
permissive
const Iconv = require('iconv-lite'); const Long = require('long'); function readUInt64BE(buffer,offset) { const high = buffer.readUInt32BE(offset); const low = buffer.readUInt32BE(offset+4); return new Long(low,high,true); } function readUInt64LE(buffer,offset) { const low = buffer.readUInt32LE(offset); const high = buffer.readUInt32LE(offset+4); return new Long(low,high,true); } function Reader(query,buffer) { this.query = query; this.buffer = buffer; this.i = 0; } Reader.prototype = { offset: function() { return this.i; }, skip: function(i) { this.i += i; }, string: function() { const args = Array.prototype.slice.call(arguments); let options = {}; if(args.length == 0) { options = {}; } else if(args.length == 1) { if(typeof args[0] === 'string') {options = { delimiter: args[0] };} else if(typeof args[0] === 'number') {options = { length: args[0] };} else {options = args[0];} } options.encoding = options.encoding || this.query.encoding; if(options.encoding == 'latin1') {options.encoding = 'win1252';} const start = this.i+0; let end = start; if(!('length' in options)) { // terminated by the delimiter let delim = options.delimiter || this.query.delimiter; if(typeof delim === 'string') {delim = delim.charCodeAt(0);} while(true) { if(end >= this.buffer.length) { end = this.buffer.length; break; } if(this.buffer.readUInt8(end) == delim) {break;} end++; } this.i = end+1; } else { end = start+options.length; if(end >= this.buffer.length) { end = this.buffer.length; } this.i = end; } let out = this.buffer.slice(start, end); const enc = options.encoding; if(enc == 'utf8' || enc == 'ucs2' || enc == 'binary') { out = out.toString(enc); } else { out = Iconv.decode(out,enc); } return out; }, int: function(bytes) { let r = 0; if(this.remaining() >= bytes) { if(this.query.byteorder == 'be') { if(bytes == 1) {r = this.buffer.readInt8(this.i);} else if(bytes == 2) {r = this.buffer.readInt16BE(this.i);} else if(bytes == 4) {r = this.buffer.readInt32BE(this.i);} } else { if(bytes == 1) {r = this.buffer.readInt8(this.i);} else if(bytes == 2) {r = this.buffer.readInt16LE(this.i);} else if(bytes == 4) {r = this.buffer.readInt32LE(this.i);} } } this.i += bytes; return r; }, uint: function(bytes) { let r = 0; if(this.remaining() >= bytes) { if(this.query.byteorder == 'be') { if(bytes == 1) {r = this.buffer.readUInt8(this.i);} else if(bytes == 2) {r = this.buffer.readUInt16BE(this.i);} else if(bytes == 4) {r = this.buffer.readUInt32BE(this.i);} else if(bytes == 8) {r = readUInt64BE(this.buffer,this.i).toString();} } else { if(bytes == 1) {r = this.buffer.readUInt8(this.i);} else if(bytes == 2) {r = this.buffer.readUInt16LE(this.i);} else if(bytes == 4) {r = this.buffer.readUInt32LE(this.i);} else if(bytes == 8) {r = readUInt64LE(this.buffer,this.i).toString();} } } this.i += bytes; return r; }, float: function() { let r = 0; if(this.remaining() >= 4) { if(this.query.byteorder == 'be') {r = this.buffer.readFloatBE(this.i);} else {r = this.buffer.readFloatLE(this.i);} } this.i += 4; return r; }, part: function(bytes) { let r; if(this.remaining() >= bytes) { r = this.buffer.slice(this.i,this.i+bytes); } else { r = new Buffer(); } this.i += bytes; return r; }, remaining: function() { return this.buffer.length-this.i; }, rest: function() { return this.buffer.slice(this.i); }, done: function() { return this.i >= this.buffer.length; } }; module.exports = Reader;
Java
UTF-8
855
2.890625
3
[]
no_license
package socket.client.tcp; import socket.common.BookServiceException; import socket.common.Message; import java.io.IOException; import java.net.Socket; public class TcpClient{ public Message sendAndReceive(Message request) { try (var socket = new Socket(Message.HOST, Message.PORT); var is = socket.getInputStream(); var os = socket.getOutputStream() ) { //System.out.println("sendAndReceive - sending request: " + request); request.writeTo(os); //System.out.println("sendAndReceive - received response: "); Message response = new Message(); response.readFrom(is); return response; } catch (IOException e) { throw new BookServiceException("Error connection to server " + e.getMessage(), e); } } }
C
UTF-8
1,970
3.84375
4
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { //각종 변수들 선언 FILE *fp; char path[1024] = "/Users/taylor/prog/code/unix/project/quest/"; int answer[10]; char x[10]; int i = 0; int c = 0; int j = 0; int count = 0; // 레시피 순서 맞췄는지를 판단하는 변수 char *menu = argv[1]; // 프로세스를 생성할때 (execv()함수를 자식프로세스에서 불름) menu입력값으로 인자로 받아옴 // 인자값과 절대경로를 합쳐 파일을 여는데 사용 strcat(path, menu); if ((fp = fopen(path, "r")) == NULL) { perror("cannot open file"); exit(10); } // quest의 파일 맨 윗줄에는 답이 적혀있음, 한글자씩 가져와 x배열에 하나씩 저장 while ((c = fgetc(fp)) != '\n') { x[i] = c; i++; } // 섞인 레시피의 순서를 보여줌 while ((c = fgetc(fp)) != EOF) { printf("%c", c); } printf("\n"); while (x[j] > 0) { printf("답을한글자씩 입력하세요 \n"); scanf("%d", &answer[j]); //입력 받은 답과 같은지를 판단, 맞으면 count를 증가, 틀리면 아무것도 하지 않음 if ((x[j] - '0') == (answer[j])) { printf("맞았습니다!\n"); count++; } else { printf("틀렸습니다! \n"); } j++; } // count가 x배열의 길이(총 몇번의 레시피가 있는지)가 같으면 모두 맞음, exit(1)로 부모프로세스의 wait상태에 영향을 줌( 모두 맞췄을 경우 전역 변수인 proj.c의 count를 증가시켜 총 몇 번 맞췄는지를 알려줌) if (count == i) { printf("정답입니다! \n"); exit(1); } else { printf("오답입니다! \n"); exit(10); } }
Python
UTF-8
3,772
3.46875
3
[]
no_license
import pygame from pygame.sprite import Sprite class Ship(Sprite): def __init__(self, ai_settings, screen): """初始化飞船并设置其初始位置""" super().__init__() self.screen = screen self.ai_settings = ai_settings #加载飞船图像 self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom #旧屏幕数据,用于缩放 self.screen_old_bottom = float(self.screen_rect.bottom) self.screen_old_centerx = float(self.screen_rect.centerx) #在飞船的属性center中存储小数 self.center = float(self.rect.centerx) self.top = float(self.rect.top) #移动标志 #self.moving_right = False #self.moving_left = False #上下移动 #self.moving_up = False #self.moving_down = False def update(self): """根据移动标志调整飞船位置""" self.rect.centerx = self.center self.rect.top = self.top def blitme(self, screen): """在指定位置绘制飞船""" #将每艘新飞船放在屏幕底部中央 #在更改屏幕大小时要注意,如果将下面代码放在__init__里,会导致飞船位置无法和屏幕大小一起改变 #原因是self.screen_rect的参数没有随着screen类中参数的改变而改变 #解决方法有两种: #1.每次刷新屏幕时都更新ship实例,这样可以将下面代码放到__init__里 #2.做如此处的修改,增加缩放, 并在blitme中添加参数screen,使得self.screen_rect随着screen的改变而改变 self.screen_rect = screen.get_rect() #缩放 self.rect.centerx = self.rect.centerx * float(self.screen_rect.centerx/self.screen_old_centerx) self.rect.bottom = self.rect.bottom * float(self.screen_rect.bottom/self.screen_old_bottom) #print(self.rect.centerx) #print(self.rect.bottom) #更新旧屏幕数据 self.screen_old_centerx = self.screen_rect.centerx self.screen_old_bottom = self.screen_rect.bottom #更新位置信息 self.center = float(self.rect.centerx) self.top = float(self.rect.top) #跟踪rect位置 self.screen.blit(self.image, self.rect) #self.screen_rect = screen.get_rect() #if screen.get_width() == 1200: #if self.moving_right and self.rect.right < self.screen_rect.right: #self.center += self.ai_settings.ship_speed_factor #print(self.moving_right) #elif self.moving_left and self.rect.left > 0: #self.center -= self.ai_settings.ship_speed_factor #elif self.moving_up and self.rect.top > 0: #self.top -= self.ai_settings.ship_speed_factor #elif self.moving_down and self.rect.bottom < self.screen_rect.bottom: #self.top += self.ai_settings.ship_speed_factor #elif screen.get_width() == 1280: #if self.moving_right and self.rect.right < self.screen_rect.right: #self.center += self.ai_settings.ship_speed_factor * float(1280/1200) #elif self.moving_left and self.rect.left > 0: #self.center -= self.ai_settings.ship_speed_factor * float(1280/1200) #elif self.moving_up and self.rect.top > 0: #self.top -= self.ai_settings.ship_speed_factor * float(697/600) #elif self.moving_down and self.rect.bottom < self.screen_rect.bottom: #self.top += self.ai_settings.ship_speed_factor * float(697/600)
Java
UTF-8
104
1.640625
2
[]
no_license
package com.mls.kicker.reservation.engine; public interface TimeoutHandler { void timedOut(); }
Python
UTF-8
1,387
3.921875
4
[]
no_license
# 10. The bedbathandbeyond.com problem def decompose_into_dictionary_words(domain, dictionary): # when the algorithm finishes, last_length[i] != -1 indicates domain[:i + 1] has a valid # decomposition, and the length of the last string in the decomposition is last_length[i]. last_length = [-1] * len(domain) for i in range(len(domain)): # if domain[:i + 1] is a dictionary word, set last_length[i] to the length of that word. if domain[:i + 1] in dictionary: last_length[i] = i + 1 # if last_length[i] = -1 look for j < i such that domain[:j+1] has a valid decomposition # and domain[j + 1 : i + 1] is a dictionary word. if so, record the length of that word in last_length[i]. if last_length[i] == -1: for j in range(i): if last_length[j] != -1 and domain[j + 1 : i + 1] in dictionary: last_length[i] = i - j break decompositions = [] if last_length[-1] != -1: # domain can be assembled by dictionary words. idx = len(domain) - 1 while idx >= 0: decompositions.append(domain[idx + 1 - last_length[idx]:idx + 1]) idx -= last_length[idx] decompositions = decompositions[::-1] return decompositions print(decompose_into_dictionary_words('amana', ['a', 'am', 'an']))
Python
UTF-8
3,657
3.390625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ ##summarize_dataset, summarize_by_class, calculate_class_probabilities NAKIJKEN LET OP ALS class_value, dit is nu 'target' Verdeling training en test maken. """ import numpy as np from sklearn.datasets import load_diabetes, load_breast_cancer import copy import matplotlib.pyplot as plt # Split the dataset by classifier target, returns a dictionary def separate_by_class(dataset): separated = dict() for i in range(len(dataset)): valuetarget = dataset[i] target = dataset[i,1] if (target not in separated): separated[target] = list() separated[target].append(valuetarget) return separated # Calculate the mean, std and count for each column in the dataset def summarize_dataset(dataset): summaries = [(np.mean(column), np.std(column), len(column)) for column in zip(*dataset)] del(summaries[-1]) return summaries # Split dataset by class then calculate statistics for each row def summarize_by_class(dataset): separated = separate_by_class(dataset) summaries = dict() for class_value, rows in separated.items(): summaries[class_value] = summarize_dataset(rows) return summaries # Gaussian probability distribution function for x def gaussian_probability(x, mean, std): gaussian=(1 / (np.sqrt(2 * np.pi) * std)) * np.exp(-((x-mean)**2 / (2 * std**2 ))) return gaussian # Calculate the probabilities of predicting each class for a given row def calculate_class_probabilities(summaries, row): total_rows = sum([summaries[label][0][2] for label in summaries]) probabilities = dict() for class_value, class_summaries in summaries.items(): probabilities[class_value] = summaries[class_value][0][2]/float(total_rows) for i in range(len(class_summaries)): mean, std, _ = class_summaries[i] probabilities[class_value] *= gaussian_probability(row[i], mean, std) return probabilities def normalize(probs): prob_factor = 1 / sum(probs) return [prob_factor * p for p in probs] breast_cancer = load_breast_cancer() feature_names = breast_cancer.feature_names #verdeling nog aanpassen met training en test set, nu resp. 300 : 269 probability_0 = np.ones((269,30)) probability_1 = np.ones((269,30)) for k in range(0,len(feature_names)): X_train = breast_cancer.data[:300, k] y_train = breast_cancer.target[:300] X_test = breast_cancer.data[300:, k] y_test = breast_cancer.target[300:] #onderstaande regel wordt volgens mij verder nergens gebruikt in het script dataset_0 = np.append(np.transpose(X_train), np.transpose(y_train)) #Create datasets which contains the values for the k-feature and the corresponding target dataset = np.ones((len(X_train),2)) dataset_test = np.ones((len(X_test),2)) for i in range(0,len(X_train)): dataset[i] = [X_train[i],y_train[i]] for i in range(0,len(X_test)): dataset_test[i] = [X_test[i],y_test[i]] summaries = summarize_by_class(dataset) for j in range(0,len(y_test)): probability = calculate_class_probabilities(summaries, dataset_test[j]) prob_0 = probability[0] prob_1 = probability[1] probs = [prob_0,prob_1] prob_0,prob_1 = normalize(probs) probability_0[j,k] = prob_0 probability_1[j,k] = prob_1 fig, axs = plt.subplots(6,5, figsize=(45, 45), facecolor='w', edgecolor='k') fig.subplots_adjust(hspace = .5, wspace=.001) axs = axs.ravel() for i in range(30): axs[i].plot(probability_0[:,i], 'bx', label='malignant') axs[i].plot(probability_1[:,i], 'rx', label='benign') axs[i].set_title(feature_names[i]) axs[i].set_ylabel('Probability') # axs[i].legend()
Java
UTF-8
476
2.84375
3
[]
no_license
package org.pke854.redbull.util; import java.util.Comparator; public class NameComparator implements Comparator<String> { public int compare(String s1, String s2) { if (s1 != null && s2 != null) { if (s1.contains(s2)) return -1; else if (s2.contains(s1)) return 1; else return s1.compareTo(s2); } else { if (s1 == null && s2 == null) return 0; else if (s1 == null) return -1; else return 1; } } }
Java
UHC
4,929
1.953125
2
[]
no_license
package dream.doc.manual.dao.sqlImpl; import java.util.List; import common.bean.User; import common.spring.BaseJdbcDaoSupportSql; import common.util.QuerySqlBuffer; import dream.doc.manual.dao.DocManualListDAO; import dream.doc.manual.dto.DocManualCommonDTO; /** * ڸŴ - dao * @author ghlee * @version $Id:$ * @since 1.0 * @spring.bean id="docManualListDAOTarget" * @spring.txbn id="docManualListDAO" * @spring.property name="dataSource" ref="dataSource" */ public class DocManualListDAOSqlImpl extends BaseJdbcDaoSupportSql implements DocManualListDAO { /** * grid find * @author ghlee * @version $Id:$ * @since 1.0 * * @param docManualCommonDTO * @return List */ public List findHelpList(DocManualCommonDTO docManualCommonDTO, User user) { QuerySqlBuffer query = new QuerySqlBuffer(); query.append("SELECT "); query.append(" '' ISDELCHECK "); query.append(" ,'' SEQNO "); query.append(" ,a.onlinehelp_id onlineHelpNo "); query.append(" ,a.description title "); query.append(" ,a.upd_date updDate "); query.append(" ,(SELECT description FROM TADEPT "); query.append(" WHERE dept_id = (SELECT dept_id FROM TAEMP "); query.append(" WHERE emp_id = a.emp_id "); query.append(" AND comp_no = a.comp_no )) updDept "); query.append(" ,a.emp_name updBy "); query.append(" ,a.onlinehelp_id onlineHelpId "); query.append("FROM TAONLINEHELP a "); query.append("WHERE 1=1 "); query.append(this.getWhere(docManualCommonDTO, user)); query.getOrderByQuery("a.comp_no","a.onlinehelp_id", docManualCommonDTO.getOrderBy(), docManualCommonDTO.getDirection()); return getJdbcTemplate().queryForList(query.toString(docManualCommonDTO.getIsLoadMaxCount(), docManualCommonDTO.getFirstRow())); } /** * delete * @author ghlee * @version $Id:$ * @since 1.0 * * @param docManualDTOList * @return */ public int deleteHelp(String id, User user) { QuerySqlBuffer query = new QuerySqlBuffer(); int rtnValue = 0; query.append("DELETE FROM TAONLINEHELP "); query.append("WHERE onlinehelp_id = '"+id+"' "); query.append(" AND comp_no = '"+user.getCompNo()+"' "); rtnValue = this.getJdbcTemplate().update(query.toString()); return rtnValue; } /** * Filter * @author ghlee * @version $Id:$ * @since 1.0 * * @param docManualCommonDTO * @return * @throws Exception */ private String getWhere(DocManualCommonDTO docManualCommonDTO, User user) { QuerySqlBuffer query = new QuerySqlBuffer(); query.getAndQuery("a.comp_no", user.getCompNo()); if (!"".equals(docManualCommonDTO.getOnlineHelpId())) { query.getAndQuery("a.onlinehelp_id", docManualCommonDTO.getOnlineHelpId()); return query.toString(); } query.getLikeQuery("a.description", docManualCommonDTO.getFilterTitle()); if(!"".equals(docManualCommonDTO.getFilterMenuId()) ) { query.append("AND a.file_name IN(SELECT file_name FROM TAPAGE "); query.append(" WHERE page_id IN(SELECT page_id FROM dbo.SFAPGPAGEINMENU_ALL("+docManualCommonDTO.getFilterMenuId()+") ) "); query.append(" ) "); } return query.toString(); } public String findTotalCount(DocManualCommonDTO docManualCommonDTO, User user) throws Exception { QuerySqlBuffer query = new QuerySqlBuffer(); query.append("SELECT "); query.append(" COUNT(1) "); query.append("FROM TAONLINEHELP a "); query.append("WHERE 1=1 "); query.append(this.getWhere(docManualCommonDTO, user)); List resultList= getJdbcTemplate().queryForList(query.toString()); return QuerySqlBuffer.listToString(resultList); } }
Java
UTF-8
2,624
2.171875
2
[]
no_license
package com.sensesnet.impl; import com.sensesnet.TestQuestionService; import com.sensesnet.connection.ConnectionPoolException; import com.sensesnet.dao.DaoFactory; import com.sensesnet.dao.exception.DaoException; import com.sensesnet.dao.test.dao.TestQuestionDao; import com.sensesnet.dao.user.dao.UserDao; import com.sensesnet.exception.ServiceException; import com.sensesnet.pojo.test.Test; import com.sensesnet.pojo.test.TestQuestion; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.List; /** * @author sensesnet <br /> * Copyright 2019 Eshted LLC. All rights reserved. * <p> * Service: Test question service */ public class TestQuestionServiceImpl implements TestQuestionService { private static final Logger log = LogManager.getLogger(TestQuestionServiceImpl.class); private TestQuestionDao testQuestionDao = DaoFactory.getTestQuestionDao(); @Override public List<TestQuestion> listOfQuestionsByTestId(Integer testId) throws ServiceException { log.info("[" + this.getClass().getName() + "] Get list of questions by test id [" + testId + "]."); try { return testQuestionDao.listOfQuestionsByTestId(testId); } catch (ConnectionPoolException | DaoException e) { throw new ServiceException("[" + this.getClass().getName() + "] " + "Questions list has not found at test system. Service exception", e); } } @Override public TestQuestion getQuestionById(Integer questionId) throws ServiceException { log.info("[" + this.getClass().getName() + "] Get questions by id [" + questionId + "]."); try { return testQuestionDao.getQuestionsById(questionId); } catch (ConnectionPoolException | DaoException e) { throw new ServiceException("[" + this.getClass().getName() + "] " + "Questions [" + questionId + "] has not found at test system. Service exception", e); } } @Override public void updateQuestion(TestQuestion testQuestion) throws ServiceException { log.info("[" + this.getClass().getName() + "] New question [" + testQuestion + "]."); try { testQuestionDao.editEntity(testQuestion); } catch (ConnectionPoolException | DaoException e) { throw new ServiceException("[" + this.getClass().getName() + "] " + "New question [" + testQuestion + "] has not updated at test system. Service exception", e); } } }
C
UTF-8
4,405
2.671875
3
[]
no_license
#include <syslog.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "exploit.h" #include "findmemmove.h" /////////////////////////////////////// Find Memmove /////////////////////////////////////// static int insn_is_32bit(uint16_t* i) { return (*i & 0xe000) == 0xe000 && (*i & 0x1800) != 0x0; } static int insn_is_bl(uint16_t* i) { if((*i & 0xf800) == 0xf000 && (*(i + 1) & 0xd000) == 0xd000) return 1; else if((*i & 0xf800) == 0xf000 && (*(i + 1) & 0xd001) == 0xc000) return 1; else return 0; } static uint32_t insn_bl_imm32(uint16_t* i) { uint16_t insn0 = *i; uint16_t insn1 = *(i + 1); uint32_t s = (insn0 >> 10) & 1; uint32_t j1 = (insn1 >> 13) & 1; uint32_t j2 = (insn1 >> 11) & 1; uint32_t i1 = ~(j1 ^ s) & 1; uint32_t i2 = ~(j2 ^ s) & 1; uint32_t imm10 = insn0 & 0x3ff; uint32_t imm11 = insn1 & 0x7ff; uint32_t imm32 = (imm11 << 1) | (imm10 << 12) | (i2 << 22) | (i1 << 23) | (s ? 0xff000000 : 0); return imm32; } static uint16_t* find_next_insn_matching(uint32_t region, uint8_t* kdata, size_t ksize, uint16_t* current_instruction, int (*match_func)(uint16_t*)) { while((uintptr_t)current_instruction < (uintptr_t)(kdata + ksize)) { if(insn_is_32bit(current_instruction)) { current_instruction += 2; } else { ++current_instruction; } if(match_func(current_instruction)) { return current_instruction; } } return NULL; } static uint32_t find_memmove_arm(uint32_t region, uint8_t* kdata, size_t ksize) { const uint8_t search[] = {0x00, 0x00, 0x52, 0xE3, 0x01, 0x00, 0x50, 0x11, 0x1E, 0xFF, 0x2F, 0x01, 0xB1, 0x40, 0x2D, 0xE9}; void* ptr = memmem(kdata, ksize, search, sizeof(search)); if(!ptr) return 0; return ((uintptr_t)ptr) - ((uintptr_t)kdata); } static uint32_t find_memmove_thumb(uint32_t region, uint8_t* kdata, size_t ksize) { const uint8_t search[] = {0x03, 0x46, 0x08, 0x46, 0x19, 0x46, 0x80, 0xB5}; void* ptr = memmem(kdata, ksize, search, sizeof(search)); if(!ptr) return 0; return ((uintptr_t)ptr + 6 + 1) - ((uintptr_t)kdata); } // Helper gadget. static uint32_t find_memmove(uint32_t region, uint8_t* kdata, size_t ksize) { uint32_t thumb = find_memmove_thumb(region, kdata, ksize); if(thumb) return thumb; return find_memmove_arm(region, kdata, ksize); } uint32_t get_memmove() { io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOUSBDeviceInterface")); io_connect_t connect; IOServiceOpen(service, mach_task_self(), 0, &connect); uint32_t memmove = get_memmove2(connect); IOServiceClose(connect); return memmove; } uint32_t get_memmove2(io_connect_t connect) { uint32_t kernel_region = get_kernel_region(connect); uint32_t kernel_text_start = kernel_region + get_kernel_text_start(); // Dump the default_pager function to help us locate memmove. // The default_pager function seems to always be the very first function in the kernel text. uint8_t* default_pager = kernel_read_exception_vector(connect, kernel_text_start, 0x1000); // Find the second function call in this function, it will be memset. uint16_t* first_function_call = find_next_insn_matching(kernel_region, default_pager, 0x1000, (uint16_t*) default_pager, insn_is_bl); if(!first_function_call) return 0; uint16_t* second_function_call = find_next_insn_matching(kernel_region, default_pager, 0x1000, first_function_call, insn_is_bl); if(!second_function_call) return 0; uint32_t second_function_call_address = kernel_text_start + ((intptr_t)second_function_call - (intptr_t)default_pager); uint32_t imm32 = insn_bl_imm32(second_function_call); uint32_t memset = second_function_call_address + 4 + imm32; free(default_pager); uint32_t memmove_search_start = memset - 0x2000; uint8_t* memmove_search = kernel_read_exception_vector(connect, memmove_search_start, 0x2000); uint32_t memmove_offset = find_memmove(memmove_search_start, memmove_search, 0x2000); uint32_t memmove_address = memmove_search_start + memmove_offset; uint32_t memmove = memmove_address - kernel_region; free(memmove_search); return memmove; }
C++
UTF-8
2,753
3.203125
3
[]
no_license
#include "ragnarstest.h" #include "studentssortings.h" #include <iostream> #include <string> using namespace std; typedef void(*sortFunction)(float* pBegin, float* pEnd); /************************************************************** ANROP: swap((a),(b)); VERSION: 2005-10-05 NORA UPPGIFT: Byter a mot b. **************************************************************/ static void swap(float &a, float &b) { float tmp = a; a = b; b = tmp; }// swap // Testar om angiven sorteringsalgoritm fungerar. // Felutskrift om så inte är fallet. // Returnerar true omm ok. bool testAlgorithm(sortFunction simpleSort, string name){ const int size = 100; // skapa en sekvens (seq) av slumptal sorterad i stigande ordn. float seq[size]; seq[0] = -10; // size; for (int i = 1; i<size; ++i) { float d = (float)rand() / RAND_MAX; seq[i] = seq[i - 1] + d; // - d; } // låt mixed innehålla samma tal men i slumpordning // p varje sida utanför arrayen ligger det en 1a, som // ej får ändras av sorteringsalgoritmenn float mixedExtraLarge[size + 2]; float *mixed = &mixedExtraLarge[1]; // -1...size for (int i = 0; i<size; ++i) mixed[i] = seq[i]; for (int i = 0; i<size; ++i) swap((mixed[i]), (mixed[rand() % size])); mixed[-1] = 1; mixed[size] = 1; // testa att simpleSort fungerar simpleSort( &mixed[0], &mixed[size]); bool ok = true; if (mixed[-1] != 1 || mixed[size] != 1){ cout << "BUG: Algoritmen " << name << " skriver utanför (array)minnet!\7\n"; ok = false; } if (ok) for (int i = 0; i<size; ++i) if (mixed[i] != seq[i]) { cout << "BUG: i algoritm " << name << " mixed[" << i << "]==" << mixed[i] <<" != " << seq[i] << endl; ok = false; } return ok; } //*********************************************************************** // ANROP: ragnarsTest( myIdentity ); // VERSION: 2010-01-15 // UPPFIFT: Testar en eller flera rutiner som studenten har skrivit. //*********************************************************************** bool ragnarsTest(const string& myIdentity){ setlocale(LC_ALL, "Swedish" ); if (myIdentity.find("Homer")!=string::npos){ std::cerr << "Felaktig identitet : " << myIdentity << "\7\7\n"; std::cerr << "Använd DITT förnamn och de sista 4 siffrorna i DITT personnunmmer!!\n"; system("pause"); exit( 0 ); } bool ok = testAlgorithm(bubbleSort, "bubbleSort") && testAlgorithm(insertSort, "insertSort"); if (ok) cout << "Grattis, självtesten lyckades!!!" << endl; return ok; }// ragnarsTest
Markdown
UTF-8
2,803
2.6875
3
[]
no_license
# 太平洋网站计数器 **【备注:演示代码均以太平洋汽车网为例,栏目计数器id为9999】** ## 历史版本 #### 第三阶段【2014年10月】 当用户在移动设备上通过搜索引擎比如百度,google搜到PC端的页面时,PC端的页面会自动跳转到WAP端页面,这时候WAP端的计数器请求来源【document.referrer】记录的是PC端页面,但是正确的来源应该是百度,google才对,因此需要修正WAP端计数器请求来源。 **PC端** ``` 在设备跳转代码中检测到如果PC端的来源是非本站PC端的页面时,则把来源存到cookie中【cookie名:referrerUrl,有效期:10秒】,PC端计数器代码不用修改。 ``` **WAP端:取页面来源时,先检测有没有cookie,如果有cookie,则把 cookie作为来源,如果没有,才用【document.referrer】作为来源,之后清除cookie** ``` document.body.insertBefore(document.createElement("script"),document.body.firstChild).src="http://count.count.com.cn/count.php?channel=9999&screen="+screen.width+"*"+screen.height+"&refer="+encodeURIComponent(!!document.cookie.match(/(^|; )referrerUrl=[^;]+/)?document.cookie.match(/(^|; )referrerUrl=([^;]+)/)[2]:document.referrer)+"&anticache="+new Date().getTime()+"&url="+encodeURIComponent(location.href);document.cookie="referrerUrl=;expires="+new Date(new Date().getTime()-10000).toGMTString()+";path=/;domain=.pcauto.com.cn"; ``` 备注:这个方案当时只用于汽车网,并未普及六网,没有做成CMS置标。 #### 第二版本【2014年】 为了应对UC、QQ等手机浏览器无图模式导致计数器无法激活的问题,WAP端页面需要修改为使用 script 来请求的方式,其他规范与PC端计数器一致。 比如:区别静/动态应用,静态页面,需在原栏目计数器上添加&from=cms参数,而动态应用则不需要。 **WAP端改为** ``` /* JS版本 */ document.body.insertBefore(document.createElement("script"),document.body.firstChild).src="http://count.pcauto.com.cn/count.php?channel=9999&screen="+screen.width+"*"+screen.height+"&refer="+encodeURIComponent(document.referrer)+"&anticache="+new Date().getTime()+"&url="+encodeURIComponent(location.href); /* CMS版本 */ <cms:channel property="count_code2">{栏目计数器代码}</cms:channel> ``` #### 最初版本【2013年】 **PC端和WAP端都统一用** ``` /* JS版本 */ document.write("<img style=display:none src=http://count.pcauto.com.cn/count.php?channel=9999&screen="+screen.width+"*"+screen.height+"&refer="+escape(document.referrer)+"&anticache="+new Date().getTime()+location.hash.replace(/^#ad=/,"&ad=")+" >"); /* CMS版本 */ <cms:channel property="count_code">{栏目计数器代码}</cms:channel> ```
Java
UTF-8
624
2.015625
2
[]
no_license
package com.example.demo.web; import com.example.demo.entity.DemoInfo; import com.example.demo.mapper.DemoMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DemoController { @RequestMapping("/hello") public String hello(){ return "hello"; } @Autowired private DemoMapper infoMapper; @RequestMapping("/get") public DemoInfo getdemoInfo(Integer id){ return infoMapper.selectByPrimaryKey(id); } }
C++
UTF-8
2,293
3.25
3
[]
no_license
#pragma once #include <iostream> #include <cstdlib> #include <ctime> using namespace std; #define MIN_TEST_COUNT 1 #define MAX_TEST_COUNT USHRT_MAX #define MIN_TEST_LIST 1 #define MAX_TEST_LIST 15 #define MIN_TEST_NUM 1 #define MAX_TEST_NUM 100 class SortCommon { protected: std::size_t* arr; std::size_t size; SortCommon() : arr(nullptr), size(0) { static bool init = false; if (false == init) { srand((unsigned int)time(NULL)); init = true; } } void Swap(std::size_t& a, std::size_t& b) { std::size_t temp = a; a = b; b = temp; } private: bool Verify() { if (nullptr == arr) return false; for (int i = 1; i < size; ++i) if (arr[i - 1] > arr[i]) return false; return true; } public: bool DoTest(std::size_t testCountNum, bool showProc) { if (MIN_TEST_COUNT > testCountNum || MAX_TEST_COUNT < testCountNum) { std::cout << " * usage : test count number range : " << MIN_TEST_COUNT << " ~ " << MAX_TEST_COUNT << " * " << std::endl; return false; } for (std::size_t i = 0; i < testCountNum; ++i) { size = ((std::size_t)rand() % (MAX_TEST_LIST - MIN_TEST_LIST + 1)) + MIN_TEST_LIST; if (nullptr != arr) delete[] arr; arr = new std::size_t[size]; if (nullptr == arr) { std::cout << " * allocating failed * " << std::endl; return false; } if (showProc) { std::cout << "[" << i + 1 << "] test.. test list num : " << size << std::endl; std::cout << " test numbers : "; } for (std::size_t j = 0; j < size; ++j) { arr[j] = ((std::size_t)rand() % (MAX_TEST_NUM - MIN_TEST_NUM + 1)) + MIN_TEST_NUM; if (showProc) std::cout << arr[j] << " "; } if (showProc) std::cout << std::endl; Sort(); if (showProc) { std::cout << " test result : "; for (std::size_t j = 0; j < size; ++j) std::cout << arr[j] << " "; std::cout << std::endl; } if (false == Verify()) { std::cout << " * verifying failed * " << std::endl; return false; } } if (nullptr != arr) { delete[] arr; arr = nullptr; } std::cout << " * all test succeeded * " << std::endl; return true; } virtual ~SortCommon() { if (nullptr != arr) { delete[] arr; arr = nullptr; } } virtual void Sort() = 0; };
Markdown
UTF-8
954
3.328125
3
[ "MIT" ]
permissive
# enforce usage of `this` in template (weex/vue/this-in-template) - :gear: This rule is included in `"plugin:weex/vue/recommended"`. ## :book: Rule Details :-1: Examples of **incorrect** code for this rule: ```html <a :href="this.url"> {{ this.text }} </a> ``` :+1: Examples of **correct** code for this rule: ```html <a :href="url"> {{ text }} </a> ``` ## :wrench: Options Default is set to `never`. ``` 'vue/this-in-template': [2, 'always'|'never'] ``` ### `"always"` - Always use `this` while accessing properties from Vue :-1: Examples of **incorrect** code: ```html <a :href="url"> {{ text }} </a> ``` :+1: Examples of **correct** code`: ```html <a :href="this.url"> {{ this.text }} </a> ``` ### `"never"` - Never use `this` keyword in expressions :-1: Examples of **incorrect** code: ```html <a :href="this.url"> {{ this.text }} </a> ``` :+1: Examples of **correct** code: ```html <a :href="url"> {{ text }} </a> ```
C#
UTF-8
37,208
2.546875
3
[]
no_license
using ServiceStore.Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace ServiceStore.Data { public class DBObjects { public static void Initial(AppDBContent content) { if (!content.Service.Any()) content.AddRange ( new Service { Name = "", Desc = "Формирование первичной учетной документации по выполненным строительно-монтажным работам", Img = "/img/services/smeta1.jpg", Price = "от 500", FullDesc1 ="* Анализ учетной документации по выполненным строительно - монтажным работам ", FullDesc2 ="* Cоставлять акты о приемке выполненных строительно - монтажных работах ", FullDesc3 ="* Составлять справки о стоимости выполненных строительно - монтажных работ и затратах", FullDesc4 =" ", FullDesc5 =" ", FullDesc6 =" ", FullDesc7 =" ", FullDesc8 =" ", }, new Service { Name = "", Desc = "Расчет себестоимости строительно-монтажных работ", Img = "/img/services/smeta2.jpg", Price = "от 500", FullDesc1 = "* Расчет сметной и плановой себестоимости строительно-монтажных работ и величин основных статей затрат", FullDesc2 = "* Расчет фактической себестоимости строительно-монтажных работ", FullDesc3 = "* Определение величины прямых и косвенных затрат в составе фактической себестоимости строительно-монтажных работ", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Контроль расходования сметных и плановых лимитов материально-технических и финансовых ресурсов при производстве работ на участке строительства", Img = "/img/services/smeta3.jpg", Price = "от 500", FullDesc1 = "* Подготовка и проверка экономических статей договоров подряда на строительство, на выполнение отдельных видов и комплексов строительных работ", FullDesc2 = "* Подготовка экономических статей договоров поставки материально-технических ресурсов и оказания услуг по их использованию", FullDesc3 = "* Контроль закупочных цен на материально-технические ресурсы и стоимости услуг по производству отдельных видов и комплексов строительно-монтажных работ", FullDesc4 = "* Периодический контроль себестоимости при производстве строительно-монтажных работ", FullDesc5 = "* Разработка и установление системы материального стимулирования работников за экономию материально-технических и трудовых ресурсов", FullDesc6 = "* Контроль соответствия освоенного объема строительно-монтажных работ, затрат материально-технических и финансовых ресурсов установленным плановым показателям и сметным лимитам", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Определение стоимости материально-технических ресурсов, используемых при производстве строительно-монтажных работ", Img = "/img/services/smeta4.jpg", Price = "от 500", FullDesc1 = "* Составление калькуляций себестоимости работ с учетом затрат на используемые материально-технические ресурсы", FullDesc2 = "* Расчет затрат на материально-технические ресурсы для производства строительных работ", FullDesc3 = "* Расчет затрат на эксплуатацию строительных машин и механизмов", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Контроль расходования сметных и плановых лимитов материально-технических и финансовых ресурсов в процессе строительного производства", Img = "/img/services/smeta5.jpg", Price = "от 500", FullDesc1 = "* Регистрировать договоры с подрядчиками и поставщиками ресурсов, учитывать оказанные услуги и выполненные поставки", FullDesc2 = "* Выявлять и анализировать причины отклонений от плановых и сметных лимитов", FullDesc3 = " ", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Руководство работниками, осуществляющими планово-экономическое обеспечение строительного производства", Img = "/img/services/smeta6.jpg", Price = "от 500", FullDesc1 = "* Осуществлять расчет требуемой численности работников с учетом профессиональных и квалификационных требований", FullDesc2 = "* Производить оптимальное распределение работников с учетом содержания и объемов производственных заданий", FullDesc3 = " ", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Проведение вспомогательных работ при определении стоимостей строительства", Img = "/img/services/smeta7.jpg", Price = "от 500", FullDesc1 = "* Сбор первичной информации и подготовка исходных данных для выполнения расчетов стоимости строительства, в том числе осмотр, фото- и видеосъемка объектов, выбор исходных данных из технической документации, нормативных и методических источников согласно выданному руководителем заданию ( визуальные и инструментальные осмотры объектов, измерения с помощью специализированных инструментов и приборов, расчет объемов работ, чтение технической документации, выбор из нее необходимые сведения и их обработка, оформление результата работ в установленных формах)", FullDesc2 = "* Выполнение вычислений и расчетов для определения объемов работ и подготовки расчетов стоимости строительства", FullDesc3 = "* Обработка, систематизация и анализ собранной и/или полученной от заказчика информации", FullDesc4 = "* Оформление результатов выполненной работы в установленной форме (согласно выданному руководителем заданию)", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Определение сметной стоимости строительства", Img = "/img/services/smeta8.jpg", Price = "от 500", FullDesc1 = "* Планирование необходимых действий и определение объема необходимых © СРО НП «Национальное объединение специалистов стоимостного инжиниринга» 12 данных для выполнения работ", FullDesc2 = "* Подготовка ведомости объемов работ", FullDesc3 = "* Подготовка исходных данных путем проведения осмотров объектов, выбора сведений об объемах работ, технологиях и условиях их производства из технической документации, самостоятельного сбора объемов работ на основании предоставленной технической документации", FullDesc4 = "* Составление перечня работ с учетом их технологической последовательности ", FullDesc5 = "* Подбор измерителей работ, ресурсов, оборудования на основании технической документации", FullDesc6 = "* Выполнение расчетов по приведению объемов работ, расхода ресурсов и оборудования, установленных в технической документации, к необходимым для разработки сметных расчетов измерителям", FullDesc7 = "* Оформление ведомостей объемов работ в установленном порядке", FullDesc8 = " ", }, new Service { Name = "", Desc = "Определение элементов сметной стоимости строительства", Img = "/img/services/smeta9.jpg", Price = "от 500", FullDesc1 = "* Изучение технической документации на предмет определения способов и условий формирования стоимости элементов затрат, характеристик применяемых ресурсов и прочих условий, влияющих на стоимость строительства", FullDesc2 = "* Выбор оптимальных методов определения стоимости элементов затрат", FullDesc3 = "* Расчет стоимости элементов затрат", FullDesc4 = "* Оформление расчетов стоимости элементов затрат в установленном порядке с необходимыми обоснованиями", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Разработка сметной документации", Img = "/img/services/smeta10.jpg", FullDesc1 = "* Анализ технического задания на разработку сметной документации, полноты и достаточности исходных данных для ее составления", FullDesc2 = "* Уточнение и детализация исходных данных (при необходимости)", FullDesc3 = "* Подбор элементных и укрупненных сметных норм для определения сметной стоимости", FullDesc4 = "* Учет условий производства работ", FullDesc5 = "* Выбор и применение методов определения сметной стоимости в соответствии с техническим заданием на разработку сметной документации", FullDesc6 = "* Разработка расчетов стоимости элементов затрат", FullDesc7 = "* Разработка сметных расчетов", FullDesc8 = "* Подготовка и оформление в установленном порядке сметной документации в составе сметных расчетов и пояснительной записки", }, new Service { Name = "", Desc = "Определение контрактной стоимости строительства", Img = "/img/services/smeta11.jpg", Price = "от 500", FullDesc1 = "* Анализ и подготовка исходных данных для определения начальной цены контракта", FullDesc2 = "* Подготовка документации о закупке работ по строительству объектов капитального строительства в части установления ценовых показателей", FullDesc3 = "* Расчет в установленном порядке начальной цены контракта на выполнение работ по строительству с учетом периода его исполнения", FullDesc4 = "* Оформление расчета начальной цены контракта в установленном порядке", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Определение цены контракта", Img = "/img/services/smeta12.jpg", Price = "от 500", FullDesc1 = "* Подготовка и оформление сметы к контракту", FullDesc2 = " ", FullDesc3 = " ", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Формирование фактической стоимости строительства", Img = "/img/services/smeta13.jpg", Price = "от 500", FullDesc1 = "* Подготовка и оформление в установленном порядке первичной учетной документации по выполненным работам и затратам", FullDesc2 = "* Организация и ведение расчетов за выполненные работы в соответствии с принятой на предприятии учетной политикой и условиями контрактных отношений", FullDesc3 = "* Подготовка и оформление отчетной документации", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Формирование фактических затрат при осуществлении строительства", Img = "/img/services/smeta14.jpg", Price = "от 500", FullDesc1 = "* Сбор фактических затрат", FullDesc2 = "* Анализ и сопоставление первичной учетной, сметной и контрактной документации", FullDesc3 = "* Сбор и документальное оформление фактических затрат по строительству", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Определение инвестиционной стоимости строительства", Img = "/img/services/smeta15.jpg", Price = "от 500", FullDesc1 = "* Подготовка исходных данных для формирования стоимости строительства на этапе планирования капитальных вложений", FullDesc2 = "* Анализ и выбор стоимостных показателей (нормативных, объектованалогов), используемых для расчета инвестиционной (предельной) стоимости", FullDesc3 = "* Расчет инвестиционной (предельной) стоимости по строительству объектов капитального строительства с учетом прогнозного периода реализации проекта, в том числе для включения ее в техническое задание на разработку проектной документации, правовые акты о принятии решения о строительстве", FullDesc4 = "* Выполнение вспомогательных и промежуточных расчетов (в т.ч. распределение стоимости по периодам осуществления строительства, расчет индексов-дефляторов)", FullDesc5 = "* Оформление результатов расчетов в установленном порядке", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Подготовка участка для производства строительных работ", Img = "/img/services/smeta16.jpg", Price = "от 500", FullDesc1 = "* Согласование объемов производственных заданий производства работ", FullDesc2 = "* Согласование календарных планов производства работ", FullDesc3 = "* Подготовка участка производства работ и рабочих мест в соответствии с требованиями охраны труда, пожарной безопасности и охраны окружающей среды", FullDesc4 = "* Оборудование участка производства однотипных строительных работ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Материально-техническое обеспечение производства работ", Img = "/img/services/smeta17.jpg", Price = "от 500", FullDesc1 = "* Определение потребности производства работ в материально-технических ресурсах", FullDesc2 = "* Заявка, приемка, распределение, учет и хранение материально-технических ресурсов для производства работ", FullDesc3 = " ", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Управление производством работ", Img = "/img/services/smeta18.jpg", Price = "от 500", FullDesc1 = "* Планирование и контроль выполнения работ", FullDesc2 = "* Распределение производственных заданий между бригадами, звеньями и отдельными работниками", FullDesc3 = "* Контроль соблюдения технологии производства работ", FullDesc4 = "* Разработка, планирование и контроль выполнения оперативных мер, направленных на исправление дефектов результатов работ", FullDesc5 = "* Ведение текущей и исполнительной документации по выполняемым видам работ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Руководство работниками участка производства работ", Img = "/img/services/smeta19.jpg", Price = "от 500", FullDesc1 = "* Определение потребности производства однотипных строительных работ в трудовых ресурсах", FullDesc2 = "* Расстановка работников участка производства однотипных строительных работ по рабочим местам, формирование бригад и звеньев", FullDesc3 = "* Распределение и контроль выполнения работниками производственных заданий и отдельных работ", FullDesc4 = "* Контроль соблюдения работниками участка производства работ правил внутреннего трудового распорядка", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Организация производства строительных работ на объекте строительства", Img = "/img/services/smeta20.jpg", Price = "от 500", FullDesc1 = "* Контроль проектной документации по объекту капитального строительства", FullDesc2 = "* Оформление разрешений и допусков для производства строительных работ на объекте капитального строительства", FullDesc3 = "* Разработка и согласование календарных планов производства строительных работ на объекте капитального строительства", FullDesc4 = "* Подготовка строительной площадки, участков производства строительных работ и рабочих мест в соответствие с требованиями охраны труда, пожарной безопасности и охраны окружающей среды", FullDesc5 = "* Планирование и контроль выполнения и документального оформления инструктажа работников в соответствии с требованиями охраны труда и пожарной безопасности", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Подготовка результатов выполненных строительных работ на объекте строительства к сдаче заказчику", Img = "/img/services/smeta21.jpg", Price = "от 500", FullDesc1 = "* Контроль выполнения мероприятий по обеспечению соответствия результатов строительных работ требованиям нормативных технических документов и условиям договора строительного подряда", FullDesc2 = "* Подготовка исполнительно-технической документации, подлежащей предоставлению приемочным комиссиям", FullDesc3 = "* Представление результатов строительных работ и исполнительно-технической документации приемочным комиссиям", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", }, new Service { Name = "", Desc = "Сдача заказчику результатов строительных работ", Img = "/img/services/smeta22.jpg", Price = "от 500", FullDesc1 = "* Планирование и контроль выполнения работ и мероприятий по подготовке к сдаче заказчику результатов строительных работ (законченных объектов капитального строительства, этапов (комплексов) работ, консервации незавершенных объектов капитального строительства)", FullDesc2 = "* Подготовка исполнительно-технической документации, подлежащей предоставлению приемочным комиссиям", FullDesc3 = "* Представление результатов строительных работ приемочным комиссиям", FullDesc4 = "* Подписание акта приемки объекта строительства", FullDesc5 = "* Подписание документа, подтверждающего соответствие построенного, реконструированного объекта строительства требованиям технических регламентов", FullDesc6 = "* Подписание документа, подтверждающего соответствие параметров построенного, реконструированного объекта капитального строительства проектной документации, в том числе требованиям энергетической эффективности и требованиям оснащенности объекта капитального строительства приборами учета используемых энергетических ресурсов", FullDesc7 = "* Подписание документа, подтверждающего соответствие построенного, реконструированного объекта капитального строительства техническим условиям подключения (технологического присоединения) к сетям инженерно-технического обеспечения (при их наличии)", FullDesc8 = " ", }, new Service { Name = "", Desc = " Составление смет на дополнительные строительно-монтажные работы", Img = "/img/services/smeta23.jpg", Price = "от 500", FullDesc1 = "* Анализ условий контракта на предмет необходимости проведения дополнительных строительно-монтажных работ и возможности их оплат", FullDesc2 = "* Составление калькуляций сметных затрат на используемые трудовые и материально-технические ресурсы в соответствии с обусловленной контрактами системой ценообразования", FullDesc3 = "* Подготовка материалов для проведения переговоров с представителями заказчика о выполнении дополнительных работ и услуг", FullDesc4 = " ", FullDesc5 = " ", FullDesc6 = " ", FullDesc7 = " ", FullDesc8 = " ", } ); if (!content.Personal.Any()) content.AddRange ( new Personal { Name = "Наталья", LastName = "Зуйкова", SurName = "Михайловна", Age = "48", Login = "AdminNat", Passwrord = "AdminNat", Admin = true, Email = "Z.N.Vest@mail.ru", Phone = "????", } ); content.SaveChanges(); } } }
Markdown
UTF-8
2,384
2.671875
3
[ "MIT" ]
permissive
DB2CRUD ========= tools of node.js for crud on db2 ## Installation `npm install db2crud` ## Usage Firstly, you need init db2 connection before usage. var db2crud = require('db2crud'); //db:variable for opening connection db2crud.init({db:db2,dbname:'TEST'}); // select * from db2crudtest where ID=2 and STR='str3'; var tbObj = { ID : 2, STR : "str3" }; db2crud.get("db2crudtest", tbObj).then(function(rdata) { console.log("retdata=" + JSON.stringify(rdata)); }) // delete from db2crudtest where ID=2 and STR='str3' var tbObj = { ID : 2, STR : "str3" }; db2crud.remove("db2crudtest", tbObj).then(function(rdata) { console.log("retdata=" + JSON.stringify(rdata)); }) // update db2crudtest set STR='str3' where ID=2 var tbObj = { ID : 2, STR : "str3" }; db2crud.update("db2crudtest", tbObj).then(function(rdata) { console.log("retdata=" + JSON.stringify(rdata)); }) // insert db2crudtest(ID,STR) VALUES (2,"str2") tbObj = { ID : 2, STR : "str2" }; db2crud.insert("db2crudtest", tbObj).then(function(rdata) { console.log("retdata=" + JSON.stringify(rdata)); }) // insert db2crudtest(ID,STR) VALUES (3,"str3") // insert db2crudtest(ID,STR) VALUES (4,"str4") tbObj = [{ID:3,STR:"str3"},{ID:4,STR:"str4"}]; dbutils.insert("db2crudtest",tbObj).then(function(rdata){ console.log("retdata=" + JSON.stringify(rdata)); }); ## Error Check //retdata= [ { "field":"DATEFIELD", "value":"abc", "errMsg":"format of DATEFIELD[abc] is invalid " }, { "field":"STR", "value":"123456", "errMsg":"length of STR[123456] must be less than 5" } ] tbObj = [{NUM:"2",STR:"2",DATEFIELD:"2017-09-03 05:25:00"} ,{NUM:3,STR:3,DATEFIELD:"2017-09-03 05:25:00"} ,{NUM:3,STR:3,DATEFIELD:"abc"} ,{NUM:3,STR:"123456",DATEFIELD:"2017-09-03 05:25:00"}]; dbutils.insert("db2crudtest",tbObj).then(function(rdata){ console.log("retdata=" + JSON.stringify(rdata)); }); You can refer test.js for further detail! ## Tests node test ## Contributing Email:sword_zhang@163.com QQ:974566030 ## License Copyright(c) 2017 Jian Zhang MIT Licensed
C
UTF-8
606
2.921875
3
[ "MIT" ]
permissive
#include "param.h" #include "types.h" #include "stat.h" #include "user.h" #include "fs.h" #include "fcntl.h" #include "syscall.h" #include "traps.h" #include "memlayout.h" int main(int argc, char *argv[]){ int sleepAmount = 0; char* usageString = "Usage: sleep ticks_to_sleep\n"; // Asserting correct number of arguments if(argc != 2){ printf(2, usageString); exit(); } // Retrieving amount to sleep sleepAmount = atoi(argv[1]); printf(1,"Sleep starting sleep !!!\n"); sleep(sleepAmount); printf(1,"Sleep exiting !!!\n"); exit(); }
Java
UTF-8
3,989
1.96875
2
[]
no_license
package com.creatio.imm; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.creatio.imm.Adapters.ADBusiness; import com.creatio.imm.Objects.OBusiness; import com.ethanhua.skeleton.Skeleton; import com.ethanhua.skeleton.SkeletonScreen; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by gerardo on 18/06/18. */ public class FRReservations extends Fragment { private SharedPreferences prefs; private Context context; private ListView lvBusiness; private ArrayList<OBusiness> data_business = new ArrayList<>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fr_view_reservations, container, false); context = getActivity(); prefs = PreferenceManager.getDefaultSharedPreferences(context); lvBusiness = view.findViewById(R.id.lvBus); ReadAllBusiness(""); return view; } public void ReadAllBusiness(String category) { final ADBusiness adapter = new ADBusiness(context, data_business); final SkeletonScreen skeletonScreen = Skeleton.bind(lvBusiness) .load(R.layout.item_skeleton) .show(); data_business.clear(); AndroidNetworking.post(getResources().getString(R.string.apiurl) + "ReadAllBusiness") .addBodyParameter("apikey", getResources().getString(R.string.apikey)) .addBodyParameter("category", category) .setPriority(Priority.IMMEDIATE) .build().getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { String success = response.getString("success"); if (success.equalsIgnoreCase("true")) { JSONArray arr = response.getJSONArray("data"); for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String ID = obj.optString("ID"); String name = obj.optString("name"); String description = obj.optString("description"); String create_date = obj.optString("create_date"); String image = obj.optString("image"); String can_reserve = obj.optString("can_reserve"); if (can_reserve.equalsIgnoreCase("1")) { data_business.add(new OBusiness(ID, name, description, create_date, image, can_reserve)); } } if (data_business.size() == 0) { lvBusiness.setVisibility(View.GONE); } else { lvBusiness.setVisibility(View.VISIBLE); } lvBusiness.setAdapter(adapter); skeletonScreen.hide(); } else { } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(ANError anError) { } }); } }
Java
UTF-8
184
1.554688
2
[]
no_license
package com.loy.e.core.data; /** * * @author Loy Fu qq群 540553957 * @since 1.7 * @version 1.0.0 * */ public interface Operator { void setOperator(String operatorId); }
C#
GB18030
3,126
2.6875
3
[]
no_license
using System; using System.Linq; using Xunit; namespace EventBus.Tests { /// <summary> /// ڴ涩Ĺ /// </summary> public class InMemory_SubscriptionManager_Tests { //ʼĹ󣬶ϢӦΪա [Fact] public void After_Creation_Should_be_Empty() { var manager = new InMemoryEventBusSubscriptionsManager(); Assert.True(manager.IsEmpty); } //һ¼󣬶ĹӦð¼ [Fact] public void After_One_Event_Subscription_Should_Contain_The_Event() { var manager = new InMemoryEventBusSubscriptionsManager(); manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); Assert.True(manager.HasSubscriptionsForEvent<TestIntegrationEvent>()); manager.AddDynamicSubscription<TestDynamicIntegrationEventHandler>(nameof(TestIntegrationEvent)); Assert.True(manager.HasSubscriptionsForEvent(nameof(TestIntegrationEvent))); } //ƳеĶϢ󣬶Ϣ¼Ӧòڡ [Fact] public void After_One_Subscription_Are_Removed_Event_Shoule_No_Longer_Exists() { var manager = new InMemoryEventBusSubscriptionsManager(); manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); manager.RemoveSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); Assert.False(manager.HasSubscriptionsForEvent<TestIntegrationEvent>()); manager.AddDynamicSubscription<TestDynamicIntegrationEventHandler>(nameof(TestIntegrationEvent)); manager.RemoveDynamicSubscription<TestDynamicIntegrationEventHandler>(nameof(TestIntegrationEvent)); Assert.False(manager.HasSubscriptionsForEvent(nameof(TestIntegrationEvent))); } //ɾһϢӦɾ¼ [Fact] public void After_Deleting_Last_Subscription_Should_Raise_OnEventRemoved() { var manager = new InMemoryEventBusSubscriptionsManager(); var raised = false; manager.OnEventRemoved += (sender, eventArgs) => raised = true; manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); manager.RemoveSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); Assert.True(raised); } //õ¼Ӧ÷д [Fact] public void Get_Handlers_For_Event_Should_Return_All_Handlers() { var manager = new InMemoryEventBusSubscriptionsManager(); manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(); manager.AddDynamicSubscription<TestDynamicIntegrationEventHandler>(nameof(TestIntegrationEvent)); var handlers = manager.GetHandlersForEvent<TestIntegrationEvent>(); Assert.Equal(2, handlers.Count()); } } }
C++
UTF-8
1,085
2.90625
3
[]
no_license
#pragma once #include "../Resources/ResourcesInclude.h" namespace Systems { template <typename ResourceType> class ResourceMap { public: using Ptr = std::shared_ptr<ResourceType>; using Map = std::unordered_map<Resource::Handle, Ptr>; void Add(Ptr resource) { Container.insert(std::pair<Resource::Handle, Ptr>(resource->getName(), resource)); } bool Remove(const Resource::Handle& handle) { if (!Container.count(handle)) return false; // Note. Does not call delete on the pointers. Container.erase(handle); return true; } bool Has(const Resource::Handle&) { if (!Container.count(handle)) return false; return true; } Ptr Find(const Resource::Handle& handle) { if (!Container.count(handle)) return nullptr; return Container.at(handle); } const Map& All() { return Container; } private: Map Container; }; struct ResourceMaps { ResourceMap<Resources::SpriteSource> SpriteSource; ResourceMap<Resources::Level> Level; }; }
TypeScript
UTF-8
581
2.609375
3
[]
no_license
import {Pipe, PipeTransform} from '@angular/core'; import {EmployeeDto} from "../../dto/employee.dto"; @Pipe({ name: 'dateOfBirthFilter' }) export class DateOfBirthFilterPipe implements PipeTransform { transform(employeeList: EmployeeDto[], searchName: string): any { if (!employeeList) { return []; } if (!searchName) { return employeeList; } employeeList = employeeList .filter(employee => employee.dob != null) .filter(employee => { return employee.dob.includes(searchName); }); return employeeList; } }
Java
UTF-8
5,777
3.03125
3
[ "Apache-2.0" ]
permissive
package cuda.gp; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import ec.EvolutionState; import ec.gp.ERC; import ec.gp.GPIndividual; import ec.gp.GPNode; import ec.util.DecodeReturn; import ec.util.Parameter; /** * Basically the exact same code from ec.gp.ERC class Except that this class * inhertis from CudaNode rather than GPNode * * @author Mehran Maghoumi * */ public abstract class CudaERC extends CudaNode { /** * Returns the lowercase "name" of this ERC function class, some simple, * short name which distinguishes this class from other ERC function classes * you're using. If you have more than one ERC function, you need to * distinguish them here. By default the value is "ERC", which works fine * for a single ERC function in the function set. Whatever the name is, it * should generally only have letters, numbers, or hyphens or underscores in * it. No whitespace or other characters. */ public String name() { return "ERC"; } /** * Usually ERCs don't have children, and this default implementation makes * certain of it. But if you want to override this, you're welcome to. */ public void checkConstraints(final EvolutionState state, final int tree, final GPIndividual typicalIndividual, final Parameter individualBase) { super.checkConstraints(state, tree, typicalIndividual, individualBase); // make sure we don't have any children. This is the typical situation for an ERC. if (children.length != 0) state.output.error("Incorrect number of children for the node " + toStringForError() + " (should be 0)"); } /** * Remember to override this to randomize your ERC after it has been cloned. * The prototype will not ever receive this method call. */ public abstract void resetNode(final EvolutionState state, int thread); /** Implement this to do ERC-to-ERC comparisons. */ public abstract boolean nodeEquals(final GPNode node); /** * Implement this to hash ERCs, along with other nodes, in such a way that * two "equal" ERCs will usually hash to the same value. The default value, * which may not be very good, is a combination of the class hash code and * the hash code of the string returned by encode(). You might make a better * hash value. */ public int nodeHashCode() { return super.nodeHashCode() ^ encode().hashCode(); } /** * You might want to override this to return a special human-readable * version of the erc value; otherwise this defaults to toString(); This * should be something that resembles a LISP atom. If a simple number or * other object won't suffice, you might use something that begins with * name() + [ + ... + ] */ public String toStringForHumans() { return toString(); } /** * This defaults to simply name() + "[" + encode() + "]". You probably * shouldn't deviate from this. */ public String toString() { return name() + "[" + encode() + "]"; } /** Encodes data from the ERC, using ec.util.Code. */ public abstract String encode(); /** * Decodes data into the ERC from dret. Return true if you sucessfully * decoded, false if you didn't. Don't increment dret.pos's value beyond * exactly what was needed to decode your ERC. If you fail to decode, you * should make sure that the position and data in the dret are exactly as * they were originally. */ public boolean decode(final DecodeReturn dret) { return false; } /** * Mutates the node's "value". This is called by mutating operators which * specifically <i>mutate</i> the "value" of ERCs, as opposed to replacing * them with whole new ERCs. The default form of this function simply calls * resetNode(state,thread), but you might want to modify this to do a * specialized form of mutation, applying gaussian noise for example. */ public void mutateERC(final EvolutionState state, final int thread) { resetNode(state, thread); } /** * To successfully write to a DataOutput, you must override this to write * your specific ERC data out. The default implementation issues a fatal * error. */ public void writeNode(final EvolutionState state, final DataOutput dataOutput) throws IOException { state.output.fatal("writeNode(EvolutionState,DataInput) not implemented in " + getClass().getName()); } /** * To successfully read from a DataOutput, you must override this to read * your specific ERC data in. The default implementation issues a fatal * error. */ public void readNode(final EvolutionState state, final DataInput dataInput) throws IOException { state.output.fatal("readNode(EvolutionState,DataInput) not implemented in " + getClass().getName()); } public GPNode readNode(final DecodeReturn dret) { int len = dret.data.length(); int originalPos = dret.pos; // get my name String str2 = name() + "["; int len2 = str2.length(); if (dret.pos + len2 >= len) // uh oh, not enough space return null; // check it out for (int x = 0; x < len2; x++) if (dret.data.charAt(dret.pos + x) != str2.charAt(x)) return null; // looks good! try to load this sucker. dret.pos += len2; ERC node = (ERC) lightClone(); if (!node.decode(dret)) { dret.pos = originalPos; return null; } // couldn't decode it // the next item should be a "]" if (dret.pos >= len) { dret.pos = originalPos; return null; } if (dret.data.charAt(dret.pos) != ']') { dret.pos = originalPos; return null; } // Check to make sure that the ERC's all there is if (dret.data.length() > dret.pos + 1) { char c = dret.data.charAt(dret.pos + 1); if (!Character.isWhitespace(c) && c != ')' && c != '(') // uh oh { dret.pos = originalPos; return null; } } dret.pos++; return node; } }
Markdown
UTF-8
749
4.28125
4
[]
no_license
# Fibonacci Write a recursive function called `fib` which accepts a number and returns the nth number in the Fibonacci sequence. Recall that the Fibonacci sequence is the sequence of whole numbers 1, 1, 2, 3, 5, 8, ... which starts with 1 and 1, and where every number thereafter is equal to the sum of the previous two numbers. Examples: * `fib(4) // 3` * `fib(10) // 55` * `fib(28) // 317811` * `fib(35) // 9227465` --- ### Solution ```js function fib(num){ if(num <= 2) return 1; return fib(num - 1) + fib(num - 2); } ``` ### 🔥 Hotshot One-liner ```js const fib = num => num <= 2 ? 1 : fib(num - 1) + fib(num - 2); ``` ### 🔥🔥🔥 wtf even is this 🔥🔥🔥 ```js const fib = num => num > 2 ? fib(--num) + fib(--num) : 1; ```
Markdown
UTF-8
3,878
2.90625
3
[]
no_license
--- version: 0.0.1 author: xuld <xuld@vip.qq.com> import: - typo/reset - typo/grid - typo/util - typo/icon keyword: - 输入框 - 输入域 - input --- # 文本框 文本框也叫输入框,文本框可用于让用户输入信息。 ## 基本用法 ```jsx demo import { VNode, render } from "ui/control"; import TextBox from "ui/textBox"; render( __root__, <TextBox placeholder="请输入内容..."></TextBox> ); ``` ## 事件 每次输入时都会触发 `onInput` 事件,内容改变后会触发 `onChange` 事件。 ```jsx demo import { VNode, render } from "ui/control"; import TextBox from "ui/textBox"; render( __root__, <TextBox onChange={(e, s) => alert("值 = " + s.value)}></TextBox> ); ``` ## 表单验证 ```jsx demo import { VNode, render } from "ui/control"; import TextBox from "ui/textBox"; render( __root__, <TextBox minLength={3} pattern={/^\d+$/} onChange={(e, s) => alert("验证结果 = " + s.checkValidity().valid)}></TextBox> ); ``` 更多验证功能请参考[[ui/input]]。 ## 样式 <style> .doc .x-textbox { margin-bottom: .5rem; } </style> ### 基本样式 ```html demo 姓名:<input type="text" class="x-textbox" placeholder="请输入内容..." /> <br /> 生日:<input type="date" class="x-textbox" placeholder="请输入内容..." /> <br /> 年龄:<select class="x-textbox"><option>已成年</option><option>未成年</option></select> <br /> 自我介绍: <textarea class="x-textbox" placeholder="请输入内容..." rows="7"></textarea> ``` ### 状态 ```html demo 正常:<input type="text" class="x-textbox" placeholder="请输入内容..." /><br /> 信息:<input type="text" class="x-textbox x-textbox-info" placeholder="请输入内容..." /><br /> 成功:<input type="text" class="x-textbox x-textbox-success" placeholder="请输入内容..." /><br /> 警告:<input type="text" class="x-textbox x-textbox-warning" placeholder="请输入内容..." /><br /> 错误:<input type="text" class="x-textbox x-textbox-error" placeholder="请输入内容..." /><br /> 只读:<input type="text" class="x-textbox" readonly="readonly" value="内容" /><br /> 禁用:<input type="text" class="x-textbox" disabled="disabled" value="内容" /><br /> ``` ### 尺寸 ```html demo 更大:<input type="text" class="x-textbox x-textbox-large" /><br /> 更小:<input type="text" class="x-textbox x-textbox-small" /> ``` 使用[[typo/grid]]提供的 `.x-col-*` 设置宽度。 ```html demo 更宽:<input type="text" class="x-textbox x-col-12" /><br /> 更窄:<input type="text" class="x-textbox x-col-4" /> ``` 使用[[typo/util]]提供的`.x-block` 可占满整行。 ```html demo <input type="text" class="x-textbox x-block" placeholder="任意内容..." /> ``` ### 选择框 ```html demo 选择: <select class="x-textbox"> <option>A: B 没有说谎</option> <option>B: C 说谎了</option> <option>C: 我没有说谎</option> <option>D: 只一人说谎</option> </select> <select class="x-textbox x-textbox-warning"> <option>A: B 没有说谎</option> <option>B: C 说谎了</option> <option>C: 我没有说谎</option> <option>D: 只一人说谎</option> </select> <select class="x-textbox x-textbox-error"> <option>A: B 没有说谎</option> <option>B: C 说谎了</option> <option>C: 我没有说谎</option> <option>D: 只一人说谎</option> </select> <select class="x-textbox x-textbox-success"> <option>A: B 没有说谎</option> <option>B: C 说谎了</option> <option>C: 我没有说谎</option> <option>D: 只一人说谎</option> </select> ``` ### 列表框 ```html demo 选择: <select multiple class="x-textbox"> <option>A: B 没有说谎</option> <option>B: C 说谎了</option> <option>C: 我没有说谎</option> <option>D: 只一人说谎</option> </select> ```
Java
UTF-8
1,198
2.875
3
[]
no_license
package com.projects.stickies.models; import android.os.Parcel; import android.os.Parcelable; /** * Created by admin on 21/07/14. */ public class Stickies implements Parcelable { private String text; private long time; public Stickies(long timeInMillis) { setTime(timeInMillis); } public String getText() { return text; } public void setText(String text) { this.text = text; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int i) { out.writeString(text); out.writeLong(time); } public static final Parcelable.Creator<Stickies> CREATOR = new Parcelable.Creator<Stickies>() { public Stickies createFromParcel(Parcel in) { return new Stickies(in); } public Stickies[] newArray(int size) { return new Stickies[size]; } }; private Stickies(Parcel in) { text = in.readString(); time = in.readLong(); } }
Go
UTF-8
7,183
2.890625
3
[]
no_license
package scoutingUtilities import "encoding/json" //Structs.go simply holds all the structs that are being used //Start scoutingUtilities structs //Team is the struct that represents a team type Team struct { Force bool `json:"force"` Number int `json:"team_number"` Name string `json:"nickname"` //Will need to be changed to it's own struct Reviews []string `json:"reviews"` //Will need to be changed to it's own struct Matches []int `json:"matches"` //Will/Should be corrected soon Photos []byte `json:"photos"` } //While still using a python server wrappers are needed type pythonTeamWrapper struct { Force *bool `json:"force"` Number *int `json:"number"` Name *string `json:"name"` //Will need to be changed to it's own struct Reviews *[]string `json:"reviews"` //Will need to be changed to it's own struct Matches *[]int `json:"matches"` //Will/Should be corrected soon Photos *[]byte `json:"photos"` } //Current Representation of what TBA sends back. //Wholly unnecessary but allows me to see what I'm working with type teamResponse struct { Name string `json:"name"` Locality string `json:"locality"` Number int `json:"team_number"` Region string `json:"region"` Key string `json:"key"` Country string `json:"country_name"` Website string `json:"website"` Nickname string `json:"nickname"` Events []string `json:"events"` } //Current Representation of what TBA sends back. type eventResponse struct { //Comments go Description <TAB> Example Alliances []finalAlliance `json:"alliances"` //If we have alliance selection data for this event, this contains a JSON array of the alliances. The captain is the first team, followed by their picks, in order. Key string `json:"key"` //TBA event key with the format yyyy[EVENT_CODE], where yyyy is the year, and EVENT_CODE is the event code of the event. 2010sc Name string `json:"name"` //Official name of event on record either provided by FIRST or organizers of offseason event. Palmetto Regional ShortName string `json:"short_name"` //name but doesn't include event specifiers, such as 'Regional' or 'District'. Palmetto EventCode string `json:"event_code"` //Event short code. SC EventTypeString string `json:"event_type_string"` //A human readable string that defines the event type. 'Regional', 'District', 'District Championships', 'District Championship','Championship Division', 'Championship Finals', 'Offseason','Preseason', '--' EventType int `json:"event_type"` //An integer that represents the event type as a constant. List of constants to event type EventDistrictString string `json:"event_district_string"` //A human readable string that defines the event's district. 'Michigan', 'Mid Atlantic', null (if regional) EventDistrict int `json:"event_district"` //An integer that represents the event district as a constant. List of constants to event district Year int `json:"year"` //Year the event data is for. 2010 Location string `json:"location"` //Long form address that includes city, and state provided by FIRST Clemson, SC VenueAddress string `json:"venue_address"` //Address of the event's venue, if available. Line breaks included. Long Beach Arena\n300 East Ocean Blvd\nLong Beach, CA 90802\nUSA Website string `json:"website"` //The event's website, if any. http://www.firstsv.org Official bool `json:"official"` //Whether this is a FIRST official event, or an offseaon event. true Teams []teamResponse `json:"teams"` //List of team models that attended the event Webcast []json.RawMessage `json:"webcast"` //If the event has webcast data associated with it, this contains JSON data of the streams EndDate string `json:"end_date"` //Day the event ends in string format "2014-03-29" StartDate string `json:"start_date"` //Day the event starts in string format "2014-03-27" //facebook_eid null } type finalAlliance struct { Declines []string `json:"declines"` Picks []string `json:"picks"` } type matchResponse struct { Key string `json:"key"` //TBA event key with the format yyyy[EVENT_CODE]_[COMP_LEVEL]m[MATCH_NUMBER], where yyyy is the year, and EVENT_CODE is the event code of the event, COMP_LEVEL is (qm, ef, qf, sf, f), and MATCH_NUMBER is the match number in the competition level. A set number may append the competition level if more than one match in required per set . 2010sc_qm10, 2011nc_qf1m2 CompLevel string `json:"comp_level"` //The competition level the match was played at. qm, ef, qf, sf, f SetNumber int `json:"set_number"` //The set number in a series of matches where more than one match is required in the match series. 2010sc_qf1m2, would be match 2 in quarter finals 1. MatchNumber int `json:"match_number"` //The match number of the match in the competition level. 2010sc_qm20 Alliances matchAlliances `json:"alliances"` //A list of alliances, the teams on the alliances, and their score. EventKey string `json:"event_key"` //Event key of the event the match was played at. 2011sc Videos []videoLink `json:"videos"` //JSON array of videos associated with this match and corresponding information "videos": [{"key": "xswGjxzNEoY", "type": "youtube"}, {"key": "http://videos.thebluealliance.net/2010cmp/2010cmp_f1m1.mp4", "type": "tba"}] TimeString string `json:"time_string"` //Time string for this match, as published on the official schedule. Of course, this may or may not be accurate, as events often run ahead or behind schedule 11:15 AM Time string `json:"time"` //UNIX timestamp of match time, as taken from the published schedule 1394904600 } type videoLink struct { Type string `json:"type"` Key string `json:"key"` } type matchAlliances struct { Red alliance `json:"red"` Blue alliance `json:"blue"` } type alliance struct { Score int `json:"score"` Teams []string `json:"teams"` } //The Match struct is how a match is represented type Match struct { Number int `json:"number"` Type string `json:"type"` Red []string `json:"red"` //These might be ints Blue []string `json:"blue"` //These might be ints RedScore int `json:"rScore"` BlueScore int `json:"bScore"` Winner string `json:"winner"` } //Regional How the python server takes regional type Regional struct { Location string `json:"location"` Matches []Match `json:"matches"` WinnerArray map[string][3]int `json:"winnerCount"` Year int `json:"year"` } //end scoutingUtilities Struct
Rust
UTF-8
188
3.15625
3
[]
no_license
fn main() { let vec: Vec<i32> = vec![1]; let closure = move | x: i32 | { println!("x: {:?}, vec: {:?}", x, vec); }; closure(1); println!("vec: {:?}", vec); }
JavaScript
UTF-8
3,445
2.609375
3
[]
no_license
// config baseSpeed = 0.05; notchWidth = 0.25; colors = { green: { container: "hsl(168, 75%, 42%)", lock: "hsl(210, 61%, 18%)" }, violet: { container: "hsl(267, 35%, 39%)", lock: "hsl(220, 86%, 11%)" }, orange: { container: "hsl(24, 62%, 53%)", lock: "hsl(35, 20%, 12%)" }, blue: { container: "hsl(186, 85%, 37%)", lock: "hsl(32, 67%, 8%)" }, olive: { container: "hsl(55, 16%, 41%)", lock: "hsl(0, 0%, 0%)" } }; //end config function setColor(color) { $("#container").css({"background": colors[color].container}); $("#shackle, #lock").css({"border-color": colors[color].lock}); } function newNotch() { notchPosition = (((Math.random() * 0.75 * Math.PI) + 0.25 * Math.PI) * ((clockwise * 2) - 1)) + linePosition; $("#notch-dial").css({"-webkit-transform": "rotate(" + notchPosition + "rad)"}); $("#notch-dial").css({"-moz-transform": "rotate(" + notchPosition + "rad)"}); $("#notch-dial").css({"transform": "rotate(" + notchPosition + "rad)"}); $("#notch").show(); $("#notch").toggleClass("appear-b"); } function setStatus(newStatus) { status = newStatus; switch (newStatus) { case "start": if (level < 10) setColor("green"); else if (level < 20) setColor("violet"); else if (level < 30) setColor("orange"); else if (level < 40) setColor("blue"); else setColor("olive"); setCount(level); linePosition = 0; clockwise = true; newNotch(); $("#container").removeClass("fail"); break; case "move": break; case "fail": $("#notch").hide(); $("#container").addClass("fail"); break; case "win": $("#notch").hide(); $("#container").addClass("next"); $("#shackle").addClass("unlock"); setTimeout(function() { setLevel(level + 1); setStatus("start"); $("#shackle").removeClass("unlock"); }, 1000); setTimeout(function() { $("#container").removeClass("next"); }, 2000); break; } } function setCount(newCount) { count = newCount; $("#lock").text(count); } function setLevel(newLevel) { level = newLevel; $("#level").text(level); window.localStorage.setItem("level", level); } function click() { switch (status) { case "start": setStatus("move") break; case "move": if (Math.abs(Math.atan2(Math.sin(linePosition - notchPosition), Math.cos(linePosition - notchPosition))) < notchWidth) { setCount(count - 1); if (count == 0) { setStatus("win"); } else { clockwise = !clockwise; newNotch(); } } else { setStatus("fail"); } break; case "fail": setStatus("start"); break; case "win": setStatus("start"); break; } } function step() { if (status == "move") linePosition += baseSpeed * (clockwise * 2 - 1); $("#line-dial").css({"-webkit-transform": "rotate(" + linePosition + "rad)"}); $("#line-dial").css({"-moz-transform": "rotate(" + linePosition + "rad)"}); $("#line-dial").css({"transform": "rotate(" + linePosition + "rad)"}); if ((Math.atan2(Math.sin(linePosition - notchPosition), Math.cos(linePosition - notchPosition))) * (clockwise * 2 - 1) > notchWidth) setStatus("fail"); window.requestAnimationFrame(step); } window.requestAnimationFrame(step); window.addEventListener("mousedown", click); window.addEventListener("touchstart", function(event) { event.preventDefault(); click(); }); window.addEventListener("keydown", click); setLevel(parseInt(window.localStorage.getItem("level")) || 1); setStatus("start");
C#
UTF-8
935
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MovieCheckout.Models { public class Movie { public int ID { get; set; } public string MovieTitle { get; set; } public string Genre { get; set; } public DateTime Year { get; set; } public string Actors { get; set; } public string Directors { get; set; } public int RunTime { get; set; } public double Cost { get; set; } public Movie() { } public Movie(int id, string movietitle, string genre, DateTime year, string actors, string directors, int runTime, double cost) { ID = id; MovieTitle = movietitle; Genre = genre; Year = year; Actors = actors; Directors = directors; RunTime = runTime; Cost = cost; } } }
C#
UTF-8
605
3.53125
4
[ "MIT" ]
permissive
public class Solution { public bool IsIsomorphic(string s, string t) { var map = new Dictionary<char,char>(); var taken = new Dictionary<char,char>(); var n = s.Length; for(int i = 0; i < n; i++){ var from = s[i]; var to = t[i]; if(map.ContainsKey(from) && to != map[from]) return false; if(taken.ContainsKey(to) && from != taken[to]) return false; map[from] = to; taken[to] = from; } return true; } }
JavaScript
UTF-8
15,264
3.1875
3
[]
no_license
// ---------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------- // __ __ __ || || _ ___ _ __ _ _ __ ____ // || )) || \\ // \\ || || (( \ || || \\ // || \\ // \\ || | || | // ||=) ||_// (( )) \\ /\ // \\ ||== ||_// (( ||_// ||=|| ||== || // ||_)) || \\ \\_// \V/\V/ \_)) ||___ || \\ \\__ || \\ || || || || // ---------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------- // ---------------------------------------------- Declarations ---------------------------------------------- // Define Map and Constants let playingArea = document.getElementById("playingArea"); const frames = 8; const numberOfPlayers = 2; const startingGold = 300; const startingWood = 0; var selectedElements = playingArea.getElementsByClassName("selected"); var unitsAndBuildings = []; var units = []; var environmentObjects = []; var players = []; // Create Map var map = new Map(); map.intialize(); const mapComposition = map.getMapComposition(); const buttonQ = document.getElementById("q"); const buttonW = document.getElementById("w"); const buttonE = document.getElementById("e"); buttonQ.style.visibility = "hidden"; buttonW.style.visibility = "hidden"; buttonE.style.visibility = "hidden"; // Event listeners buttonQ.addEventListener("click", qClicked); buttonW.addEventListener("click", wClicked); buttonE.addEventListener("click", eClicked); playingArea.addEventListener("contextmenu", setTargetOfSelectedUnit); playingArea.addEventListener('click', selectElement); for (var i = 0; i < numberOfPlayers; i++) { if (i === 0) { players.push(new Player(i, startingGold, startingWood, true)); } else { players.push(new Player(i, startingGold, startingWood, false)); } } for (var i = 0; i < mapComposition.length; i++) { for (var j = 0; j < mapComposition[i].length; j++) { const pos_x = j*(map.width / mapComposition[i].length); const pos_y = i*(map.height / mapComposition[i].length); if (mapComposition[i].charAt(j) === "T") { createEnvironmentObject("Tree", pos_x, pos_y); } if (mapComposition[i].charAt(j) === "Z") { createEnvironmentObject("WillowYellow", pos_x, pos_y); } if (mapComposition[i].charAt(j) === "1") { createUnit(players[0].color, "Townhall", pos_x, pos_y); } if (mapComposition[i].charAt(j) === "2") { createUnit(players[1].color, "Townhall", pos_x, pos_y); } if (mapComposition[i].charAt(j) === "3") { createUnit(players[3].color, "Townhall", pos_x, pos_y); } if (mapComposition[i].charAt(j) === "4") { createUnit(players[4].color, "Townhall", pos_x, pos_y); } } } createUnit(players[1].color, "Footman", 200, 400); // ---------------------------------------------- Game Loop ---------------------------------------------- setInterval(gameLoop, frames); function gameLoop () { if (selectedElements.length > 0) { document.getElementById("unitDetails").style.visibility = "visible"; document.getElementById("unitIcon").style.visibility = "visible"; document.getElementById("unitNameAndNumbers").style.visibility = "visible"; checkActiveButtons(); showUnitDetails(getUnitOfDomElement(selectedElements[0])); } else { document.getElementById("unitDetails").style.visibility = "hidden"; document.getElementById("unitIcon").style.visibility = "hidden"; document.getElementById("unitNameAndNumbers").style.visibility = "hidden"; buttonQ.style.visibility = "hidden"; buttonW.style.visibility = "hidden"; buttonE.style.visibility = "hidden"; } var collisionObjects = unitsAndBuildings.concat(environmentObjects); for (var i=0; i<units.length; i++) { var didMoveThisFrame = false; var didAttackThisFrame = false; for (var j=0; j<collisionObjects.length; j++) { if (i!==j) { /* // Attacking if (units[i].canAttack && (units[i].player !== collisionObjects[j].player) && !units[i].isAttacking && units[i].isAlive && collisionObjects[j].isAlive && !collisionObjects[j].isEnvironmentObejct && (units[i].checkRange(collisionObjects[j]) <= units[i].attackRange)) { // clearInterval(unitsAndBuildings[i].attackInterval); // unitsAndBuildings[i].attackInterval = 0; units[i].attackInterval = setInterval (attackLoop, frames, units[i], collisionObjects[j]); didAttackThisFrame = true; } */ // Movement v2 if (!(units[i].doesCollide(collisionObjects[j].domElement))) { if (!didMoveThisFrame && !didAttackThisFrame && units[i].canMove) { // console.log(unitsAndBuildings[i].player + " " + unitsAndBuildings[i].name + " coll with " + collisionObjects[j].player + " " + collisionObjects[j].name); if (parseInt(units[i].target_pos_x) !== parseInt(units[i].domElement.style.left) || parseInt(units[i].target_pos_y) !== parseInt(units[i].domElement.style.top)) { units[i].isMoving = true; units[i].move(); units[i].isMoving = false; didMoveThisFrame = true; // console.log(unitsAndBuildings[i].player + " " + unitsAndBuildings[i].name + " moved"); } } } else { units[i].didCollideWithObject(); } /*if ((units[i].doesCollide(collisionObjects[j].domElement))) { units[i].didCollideWithObject(); } else { if (parseInt(unitsAndBuildings[i].target_pos_x) !== parseInt(unitsAndBuildings[i].domElement.style.left) || parseInt(unitsAndBuildings[i].target_pos_y) !== parseInt(unitsAndBuildings[i].domElement.style.top)) { units[i].isMoving = true; units[i].move(); didMoveThisFrame = true; } else { units[i].isMoving = false; } }*/ /* // Movement if (!(unitsAndBuildings[i].doesCollide(collisionObjects[j].domElement))) { if (!didMoveThisFrame && unitsAndBuildings[i].canMove) { // console.log(unitsAndBuildings[i].player + " " + unitsAndBuildings[i].name + " coll with " + collisionObjects[j].player + " " + collisionObjects[j].name); if (parseInt(unitsAndBuildings[i].target_pos_x) !== parseInt(unitsAndBuildings[i].domElement.style.left) || parseInt(unitsAndBuildings[i].target_pos_y) !== parseInt(unitsAndBuildings[i].domElement.style.top)) { unitsAndBuildings[i].move(); didMoveThisFrame = true; // console.log(unitsAndBuildings[i].player + " " + unitsAndBuildings[i].name + " moved"); } } } else if (unitsAndBuildings[i].isAlive && collisionObjects[j].isAlive) { // console.log(units[i].player + " " + unitsAndBuildings[i].name + " did coll with " + collisionObjects[j].player + " " + collisionObjects[j].name); unitsAndBuildings[i].didCollideWithObject(); } */ } } } } function attackLoop (attackingUnit, targetUnit) { if (!attackingUnit.isMoving && attackingUnit.checkRange(targetUnit) <= attackingUnit.attackRange && attackingUnit.isAlive && targetUnit.isAlive) { attackingUnit.isAttacking = true; attackingUnit.attackUnit(targetUnit); } else { attackingUnit.isAttacking = false; attackingUnit.attackInterval = 0; clearInterval(attackingUnit.attackInterval); } } // ---------------------------------------------- Game Functions ---------------------------------------------- function checkActiveButtons () { switch (getUnitOfDomElement(selectedElements[0]).name) { case "Townhall": { buttonQ.innerHTML = "Create Footman"; buttonQ.style.visibility = "visible"; buttonW.innerHTML = "Create Peasant"; buttonW.style.visibility = "visible"; break; } default: { buttonQ.style.visibility = "hidden"; buttonW.style.visibility = "hidden"; buttonE.style.visibility = "hidden"; break; } } } function qClicked () { selectedUnit = getUnitOfDomElement(selectedElements[0]); switch (selectedUnit.name) { case "Townhall": { createUnit(selectedUnit.player, "Footman", getPosition(selectedUnit.domElement)[0], getPosition(selectedUnit.domElement)[1] + selectedUnit.height); } } } function wClicked () { selectedUnit = getUnitOfDomElement(selectedElements[0]); switch (selectedUnit.name) { case "Townhall": { createUnit(selectedUnit.player, "Peasant", getPosition(selectedUnit.domElement)[0], getPosition(selectedUnit.domElement)[1] + selectedUnit.height); } } } function eClicked () { selectedUnit = getUnitOfDomElement(selectedElements[0]); switch (selectedUnit.name) {} } function createUnit (player, unit, opt_pos_x, opt_pos_y) { var createdUnit; switch (unit) { case "Footman": { createdUnit = new Footman(player, document.createElement(unit)); break; } case "Peasant": { createdUnit = new Peasant(player, document.createElement(unit)); break; } case "Townhall": { createdUnit = new Townhall(player, document.createElement(unit)); break; } default: { console.log("Unit type unknown. Unable to create unit."); break; } } createdUnit.domElement.setAttribute("class", player + " unit"); playingArea.appendChild(createdUnit.domElement); if (createdUnit.isUnit) { units.push(createdUnit); } unitsAndBuildings.push(createdUnit); spawnElement (createdUnit.domElement, opt_pos_x, opt_pos_y); } function createEnvironmentObject (objectName, opt_pos_x, opt_pos_y) { var createdObject; switch (objectName) { case "Tree": { createdObject = new Tree (document.createElement(objectName)); break; } case "WillowYellow": { createdObject = new WillowYellow (document.createElement(objectName)); break; } default: { console.log("EnvironmentObject type unknown. Unable to create."); break; } } createdObject.domElement.setAttribute("class", createdObject.player + " envObject"); playingArea.appendChild(createdObject.domElement); environmentObjects.push(createdObject); createdObject.domElement.style.left = opt_pos_x + "px"; createdObject.domElement.style.top = opt_pos_y + "px"; } // Generic game functions function getPosition (element) { var el2 = element; var curtop = 0; var curleft = 0; if (document.getElementById || document.all) { do { curleft += element.offsetLeft-element.scrollLeft; curtop += element.offsetTop-element.scrollTop; element = element.offsetParent; el2 = el2.parentNode; while (el2 != element) { curleft -= el2.scrollLeft; curtop -= el2.scrollTop; el2 = el2.parentNode; } } while (element.offsetParent); } else if (document.layers) { curtop += element.y; curleft += element.x; } return [curtop, curleft]; }; function spawnElement (element, x_pos, y_pos) { var x = x_pos; var y = y_pos; // Create a dummy element for testing available space var dummy = document.createElement("dummy"); playingArea.appendChild(dummy); dummy.style.position = "absolute"; dummy.style.left = x + "px"; dummy.style.top = y + "px"; // Test if space to move is available const collisionObjects = unitsAndBuildings.concat(environmentObjects); var hasSpace = true; for (var j=0; j<collisionObjects.length; j++) { if (collisionObjects[j].doesCollide(dummy)) { hasSpace = false; } } dummy.remove(); if (hasSpace) { // Move Element element.style.position = "absolute"; element.style.left = x + "px"; element.style.top = y + "px"; getUnitOfDomElement(element).target_pos_x = x; getUnitOfDomElement(element).target_pos_y = y; } else { // Recursively try again to find space spawnElement (element, x_pos + getUnitOfDomElement(element).width, y_pos); } } function selectElement (e) { var target = e.target; // if selected a unit or building if (target.classList.contains(players[0].color) && (target.classList.contains("unit") || target.classList.contains("building"))) { target.classList.toggle("selected"); } else { // clicked somewhere else (target is no unit or building) deselectAllElements(); } } // recursively removes "selected" from elements function deselectAllElements() { if (selectedElements.length > 0) { selectedElements[0].classList.remove('selected') if (selectedElements[0]) deselectAllElements() } } function setTargetOfSelectedUnit (e) { for (var i=0;i<selectedElements.length;i++) { var element = document.getElementsByClassName("selected")[i]; getUnitOfDomElement(selectedElements[i]).isMoving = true; if (element.classList.contains("unit")) { getUnitOfDomElement(element).target_pos_x = event.clientX - playingArea.getBoundingClientRect().left - (element.clientWidth / 2) - (i*50); getUnitOfDomElement(element).target_pos_y = event.clientY - playingArea.getBoundingClientRect().top - (element.clientHeight / 2) - (i*50); } } } function getUnitOfDomElement (domElement) { for (var i=0; i<unitsAndBuildings.length; i++) { if (unitsAndBuildings[i].domElement === domElement) { return unitsAndBuildings[i]; } } } function showUnitDetails (unit) { var showHp = document.getElementById("hp"); var showHpBar = document.getElementById("hpBar"); var showAttack = document.getElementById("attack"); var showDefense = document.getElementById("defense"); var showUnitName = document.getElementById("unitName"); var showNumberOfSelectedUnits = document.getElementById("numberOfUnits"); showHp.innerHTML = unit.currentHp + " / " + unit.hp; showHpBar.style.width = (unit.currentHp / unit.hp) * 300 + "px"; showHpBar.style.backgroundColor = "hsl(" + (unit.currentHp/unit.hp)*100 + ",100%,30%)"; showDefense.innerHTML = "Defense: " + unit.defense; if (selectedElements.length > 1) { showNumberOfSelectedUnits.innerHTML = "(" + selectedElements.length + ")"; } else { showNumberOfSelectedUnits.innerHTML = ""; } document.getElementById("unitIcon").style.backgroundImage = "url('res/icons_units/" + unit.name.toLowerCase() + ".png')"; showUnitName.innerHTML = unit.name; if (unit.canAttack) { showAttack.innerHTML = "Attack: " + unit.attack; } else { showAttack.innerHTML = ""; } } function isVictory () { } // Hotkeys window.onkeydown = function (e) { var code = e.keyCode ? e.keyCode : e.which; if (code === 81 && buttonQ.style.visibility !== 'hidden') { // Q qClicked(); } else if (code === 87 && buttonW.style.visibility !== 'hidden') { // W wClicked(); } else if (code === 69 && buttonE.style.visibility !== 'hidden') { // E eClicked(); } };
C#
UTF-8
754
2.953125
3
[]
no_license
 namespace Evo20.Utils { public enum ConnectionStatus { Connected, Disconnected, Pause, Error } public static class ConnectionStateOperations { public static string ToText(this ConnectionStatus state) { switch (state) { case (ConnectionStatus.Connected): return "Соединен"; case (ConnectionStatus.Disconnected): return "Разьединен"; case (ConnectionStatus.Pause): return "Пауза"; case (ConnectionStatus.Error): return "Ошибка"; } return null; } } }
Python
UTF-8
2,172
3.703125
4
[ "MIT" ]
permissive
#Advent of Code December 14 #Written by C Shi - icydoge AT gmail dot com def reindeer_fly(reindeer, time): #Give the distance the reindeer covered until that time cycles = time / (reindeer[2] + reindeer[3]) remainder = time % (reindeer[2] + reindeer[3]) distance = cycles * reindeer[1] * reindeer[2] #Distance travelled in full fly-break cycles #Distance travelled in the remainder time if remainder <= reindeer[2]: distance += remainder * reindeer[1] else: distance += reindeer[2] * reindeer[1] return distance def look_up_reindeer(name, reindeers): #Return the index for the reindeer with that name for reindeer in reindeers: if reindeer[0] == name: return reindeers.index(reindeer) with open('inputs/reindeer.txt') as f: content = f.read().splitlines() reindeers = [] for reindeer in content: line = reindeer.split(' ') reindeers.append([line[0], int(line[3]), int(line[6]), int(line[13])]) #Part One fly_time = 2503 best_distance = -1 for reindeer in reindeers: if reindeer_fly(reindeer, fly_time) > best_distance: best_distance = reindeer_fly(reindeer, fly_time) part_one_answer = best_distance print "Distance the winning reindeer travelled (Part One):", part_one_answer #Part Two for reindeer in reindeers: reindeer.append(0) #points for t in range(1, fly_time+1): best_distance = -1 best_reindeers = [] for reindeer in reindeers: flying = reindeer_fly(reindeer, t) if flying > best_distance: #Only one reindeer in the lead best_distance = flying best_reindeers = [reindeer[0]] elif flying == best_distance: #multiple reindeers in the lead best_reindeers.append(reindeer[0]) for i in best_reindeers: reindeers[look_up_reindeer(i,reindeers)][4] += 1 #Add point to reindeer(s) in the lead. #Find the reindeer with the highest point highest_point = -1 for reindeer in reindeers: if reindeer[4] > highest_point: highest_point = reindeer[4] part_two_answer = highest_point print "Points of the winning reindeer (Part Two):", part_two_answer
C#
UTF-8
2,390
2.921875
3
[]
no_license
using UnityEngine; using AdelicSystem.RuleAI; ///<summary> /// Build-In <see cref="Action"/> composite. Used to sequence multiple action-elements. //</summary> namespace AdelicSystems.RuleAI { [CreateAssetMenu(fileName = "new SequenceAction", menuName = "RuleSystem/Actions/Composites/Sequence")] public class SequenceAction : Action { public Action[] ActionElements; // Acts out Action. Runs every updateloop. public override void Execute(RuleController controller) { // Execute Current Index int index = controller.GetSequenceIndex(this); ActionElements[index].Execute(controller); // Increment Index if Action-Element is complete if (ActionElements[index].IsComplete(controller)) controller.IncrementSequence(this); } // Evaluates if this Action can be done together with active(other) actions. public override bool CanDoBoth(Rule[] others) { // Sequence can be done both if ALL Action-Elements can do both for (int i = 0; i < ActionElements.Length; i++) { if (!ActionElements[i].CanDoBoth(others)) return false; } return true; } // Evaluates if this action can interupt the active actions. public override bool CanInterupt() { // A sequence interups if the first element can interupt. return ActionElements[0].CanInterupt(); } // Evaluates, once action is active, if the action is completed. public override bool IsComplete(RuleController controller) { // Completes Sequence if The sequence index is bigger than the amount of elements in sequence return controller.GetSequenceIndex(this) >= ActionElements.Length; } // Runs once, when action is activated. public override void OnEnterAction(RuleController controller) { //Subscribe this Sequence to controller controller.SubscribeSequence(this); } // Runs once, when action is deactivated. public override void OnExitAction(RuleController controller) { // Unsubscribe this sequence from controller controller.UnsubScribeSequence(this); } } }
JavaScript
UTF-8
1,274
2.53125
3
[]
no_license
import React, { Component } from 'react' import NewBoxForm from './NewBoxForm' import Box from './Box' export default class BoxList extends Component { constructor(props) { super(props) this.state = { boxes: [] } this.addBox = this.addBox.bind(this) this.removeBox = this.removeBox.bind(this) } addBox(box) { this.setState(state => ({ boxes: [...state.boxes, box] })); } removeBox(id) { this.setState({ boxes: this.state.boxes.filter(box => box.id !== id) }); } renderBoxes() { return ( <ul> {this.state.boxes.map(box => ( <Box key = {box.id} id = {box.id} width = {box.width} height = {box.height} color = {box.color} removeBox = {() => this.removeBox(box.id)} /> ))} </ul> ); } render() { return ( <div> <NewBoxForm createBox={this.addBox} removeBox={this.removeBox} /> {this.renderBoxes()} </div> ) } }
PHP
UTF-8
4,965
2.671875
3
[]
no_license
<?php namespace App\Service; use App\Entity\MultimediaRequest\MultimediaRequestStatusNote; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Persistence\ManagerRegistry; use JetBrains\PhpStorm\ArrayShape; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; use Symfony\Component\Validator\ConstraintViolationList; use Doctrine\ORM\PersistentCollection; use App\Entity\MultimediaRequest\MultimediaRequest; use Symfony\Component\Validator\Validator\ValidatorInterface; class MultimediaRequestService { private AuthorizationCheckerInterface $authorizationChecker; private ManagerRegistry $doctrine; private ValidatorInterface $validator; private EntityManagerInterface $em; public function __construct(AuthorizationCheckerInterface $authorizationChecker, ManagerRegistry $doctrine, ValidatorInterface $validator, EntityManagerInterface $em) { $this->authorizationChecker = $authorizationChecker; $this->doctrine = $doctrine; $this->validator = $validator; $this->em = $em; } /** * Use the Symfony container's validator to validate fields for an assignee * @param mixed $item * @return ConstraintViolationList $errors */ public function validate(mixed $item): ConstraintViolationList { return $this->validator->validate($item); } /** * Compare and delete any status notes not in the updated array. Add any status notes not in the existing array. * * @param PersistentCollection $currentCollection * @param array $updatedArray * @return void */ public function statusNoteCollectionCompare(PersistentCollection $currentCollection, array $updatedArray): void { $current_ids = array(); foreach ($currentCollection as $item) { $current_ids[] = $item->getId(); } $updated_ids = array(); foreach ($updatedArray as $item) { // new bathrooms will NOT have an id if (isset($item['id'])) { $updated_ids[] = $item['id']; } } $itemsToDelete = array_diff($current_ids, $updated_ids); // result is the items that do NOT appear in the updated IDs // Find and remove any items that do NOT appear in the updated IDs foreach ($itemsToDelete as $itemToDelete) { $item = $this->doctrine->getRepository(MultimediaRequestStatusNote::class)->find($itemToDelete); $this->deleteStatusNote($item); } } /** * Fetch the user's permissions for managing photo requests * @return array $multimediaRequestPermissions */ #[ArrayShape(['create' => "bool", 'edit' => "bool", 'delete' => "bool", 'admin' => "bool", 'email' => "bool"])] public function getUserMultimediaRequestPermissions(): array { $multimediaRequestPermissions = array( 'create' => false, 'edit' => false, 'delete' => false, 'admin' => false ); if ($this->authorizationChecker->isGranted('ROLE_MULTIMEDIA_ADMIN') || $this->authorizationChecker->isGranted('ROLE_GLOBAL_ADMIN')) { $multimediaRequestPermissions['create'] = true; $multimediaRequestPermissions['edit'] = true; $multimediaRequestPermissions['delete'] = true; $multimediaRequestPermissions['email'] = true; $multimediaRequestPermissions['admin'] = true; } if ($this->authorizationChecker->isGranted('ROLE_MULTIMEDIA_EMAIL')) { $multimediaRequestPermissions['email'] = true; $multimediaRequestPermissions['edit'] = true; } if ($this->authorizationChecker->isGranted('ROLE_MULTIMEDIA_DELETE')) { $multimediaRequestPermissions['delete'] = true; $multimediaRequestPermissions['edit'] = true; } if ($this->authorizationChecker->isGranted('ROLE_MULTIMEDIA_EDIT')) { $multimediaRequestPermissions['create'] = true; $multimediaRequestPermissions['edit'] = true; } if ($this->authorizationChecker->isGranted('ROLE_MULTIMEDIA_CREATE')) { $multimediaRequestPermissions['create'] = true; } return $multimediaRequestPermissions; } /** * Remove a multimedia request from the database * @param MultimediaRequest $multimediaRequest * @return void */ protected function deleteMultimediaRequest(MultimediaRequest $multimediaRequest): void { $this->em->remove($multimediaRequest); $this->em->flush(); } /** * Remove a status note from the database * @param MultimediaRequestStatusNote $note * @return void */ protected function deleteStatusNote(MultimediaRequestStatusNote $note): void { $this->em->remove($note); $this->em->flush(); } }
Java
UTF-8
848
3.25
3
[]
no_license
package com.ds.practice; public class ReverseInteger { public int reverse(int num) { boolean negativeFlag = false; if (num < 0) { negativeFlag = true; num = ~num ; } int prev_rev_num = 0, rev_num = 0; while (num != 0) { int curr_digit = num%10; rev_num = (rev_num*10) + curr_digit; if ((rev_num - curr_digit)/10 != prev_rev_num) { return 0; } prev_rev_num = rev_num; num = num/10; } return (negativeFlag == true)? -rev_num : rev_num; } public static void main(String[] args) { ReverseInteger ri = new ReverseInteger(); ri.reverse(-1234567891); } }
Java
UTF-8
7,046
3.390625
3
[]
no_license
package boundary; import control.CourseManager; import control.StudentManager; import entity.Course; import entity.Index; import entity.Student; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; /** * UI for the user to manage the courses in the STARS system. * * @author Tony * */ public class StudentUI { /** * Runs a student UI based on the username of the student obtained from logging in. * @param username the current student that is in the system */ public static void mainStudentUI(String username) { StudentManager stmngr = new StudentManager(username); String userinput = null; int choice = 0; String courseID,indexID; Scanner sc = new Scanner(System.in); int valid=0; do { System.out.println(); System.out.println("Welcome Student\nPlease Select one of functions:"); System.out.println("1. Add Course"); System.out.println("2. Drop Course"); System.out.println("3. Check/Print Courses Registered"); System.out.println("4. Check Vacancies Available"); System.out.println("5. Change Index Number of Course"); System.out.println("6. Swop Index Number with Another Student"); System.out.println("7. Print Timetable"); System.out.println("8. Exit"); do { try { userinput = sc.nextLine(); choice = Integer.parseInt(userinput); valid=1; } catch (Exception ex) { System.out.println("Please only enter the choices shown"); } }while(valid!=1); switch (choice) { case 1: System.out.println("Enter Course ID to add: "); courseID = sc.nextLine().toUpperCase(); System.out.println("Enter Index ID to add: "); indexID = sc.nextLine(); stmngr.addCourse(courseID, indexID); break; case 2: System.out.println("Enter Course ID to drop: "); courseID = sc.nextLine().toUpperCase(); stmngr.dropCourse(courseID); break; case 3: System.out.println("Printing Registered Courses!"); stmngr.printCourseRegistered(); break; case 4: System.out.println("Enter Course ID to check: "); courseID = sc.nextLine().toUpperCase(); System.out.println("Enter Index ID to check: "); indexID = sc.nextLine(); stmngr.printVacanciesAvaliable(courseID, indexID); System.out.println(); break; case 5: Student currentStudent = stmngr.findCurrentStudent(); System.out.println("Printing list of course available for index change"); for(int i1 = 0; i1 < currentStudent.getCourseEnrolled().size();i1++) { System.out.println(currentStudent.getCourseEnrolled().get(i1).getCourseID()+ "\n"); } System.out.println("Enter the course that you want to change index:"); String changeCourseID = sc.nextLine().toUpperCase(); //check if course entered is valid boolean checkCourseEntered = false; for(int i2 = 0; i2 < currentStudent.getCourseEnrolled().size();i2++ ) { if(changeCourseID.equals(currentStudent.getCourseEnrolled().get(i2).getCourseID())) { checkCourseEntered = true; break; } else { checkCourseEntered = false; } } if(checkCourseEntered == false) { System.out.println("Invalid Course Entered!"); break; } //course entered is valid, now we get index available for change ArrayList<Course> courseList = new ArrayList<Course>(); ArrayList<Index> indexList = new ArrayList<Index>(); courseList = CourseManager.getListOfCourses(); for(Course course: courseList) { if(changeCourseID.equals(course.getCourseID())) { indexList = course.getIndex(); } } System.out.println("Printing list of index available for the course" + "\n"); for(Index index: indexList) { System.out.println(index.getIndexID() + "\n"); } // // System.out.println(indexList.size()); // for (int i4 = 0; i4 < indexList.size(); i4++) // { // // System.out.println(indexList.get(i4).getIndexID() + "\n"); // // } System.out.println("Enter the index that you want to change to: "); String indexToChange = sc.nextLine(); boolean checkChangeSuccess = stmngr.changeIndex(changeCourseID, indexToChange); if(checkChangeSuccess == false) { System.out.println("Clash in timetable, change is not possible"); } else { System.out.println("Index has been changed"); } break; case 6: Student currentStudentSwap = stmngr.findCurrentStudent(); System.out.println("Printing list of course available for index swap"); for(int j1 = 0; j1< currentStudentSwap.getCourseEnrolled().size();j1++) { System.out.println(currentStudentSwap.getCourseEnrolled().get(j1).getCourseID()+ "\n"); } System.out.println("Enter the course that you want to swap index:"); String swapCourseID = sc.nextLine().toUpperCase(); //check if course entered is valid boolean checkCourseEnteredSwap = false; for(int j2 = 0; j2 < currentStudentSwap.getCourseEnrolled().size();j2++ ) { if(swapCourseID.equals(currentStudentSwap.getCourseEnrolled().get(j2).getCourseID())) { checkCourseEnteredSwap = true; break; } else { checkCourseEnteredSwap = false; } } if(checkCourseEnteredSwap == false) { System.out.println("Invalid Course Entered!"); break; } //ask who does he want to swap with ArrayList<Student> listOfStudents = StudentManager.getListOfStudents(); System.out.println("Printing list of students for index swap"); for(int j5 = 0; j5 < listOfStudents.size();j5++) { if(!currentStudentSwap.getName().equals(listOfStudents.get(j5).getName())) { System.out.println(listOfStudents.get(j5).getName()+ "\n"); } } System.out.println("Enter name of student that you want to swap with: " + "\n"); String studentNameSwap = sc.nextLine(); boolean checkSwapSuccess = stmngr.swapIndex(swapCourseID, studentNameSwap); if(checkSwapSuccess == true) { System.out.println("Index swapped"); } else { System.out.println("Index was not swapped"); } break; case 7: stmngr.printSchedule(); break; case 8: break; default: break; } } while (choice != 8); System.out.println("STARS Exiting.."); } }
PHP
UTF-8
3,196
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Repository; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\NoResultException; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; use Doctrine\ORM\QueryBuilder; use App\Entity\BaseEntityInterface; use App\Filter\FilterInterface; /** * Class Repository * @package App\Repository */ abstract class Repository extends ServiceEntityRepository implements RepositoryInterface { /** * @param BaseEntityInterface $entity * @param bool $andFlush * * @throws ORMException */ public function update(BaseEntityInterface $entity,$andFlush = true) { $this->getEntityManager()->persist($entity); if ($andFlush) { $this->flush(); } } /** * @param FilterInterface $filter * @param QueryBuilder $builder * * @return QueryBuilder */ public function applyFilter(FilterInterface $filter, $builder) { return $builder; } /** * @param BaseEntityInterface $entity * * @throws ORMException */ public function delete(BaseEntityInterface $entity) { $this->getEntityManager()->remove($entity); $this->flush(); } /** * @param null|BaseEntityInterface|array $entity * * @throws ORMException * @throws OptimisticLockException */ public function flush($entity = null) { $this->getEntityManager()->flush($entity); } /** * @param FilterInterface $filter * @param int $limit * * @return array */ public function findByFilter(FilterInterface $filter, $limit = 0) { $builder = $this->getQB($filter); if ($limit > 0) { $builder->setMaxResults($limit); } return $builder->getQuery()->getResult(); } /** * @param FilterInterface $filter * * @return int * @throws NoResultException * @throws NonUniqueResultException */ public function countByFilter(FilterInterface $filter) { $builder = $this->getEntityManager()->createQueryBuilder(); $builder ->select('count(t.id)') ->from($this->getClassName(), 't'); $this->applyFilter($filter, $builder); return $builder->getQuery()->getSingleScalarResult(); } /** * Start MySql transaction */ public function beginTransaction() { $this->getEntityManager()->beginTransaction(); } /** * Commit transaction */ public function commitTransaction() { $this->getEntityManager()->commit(); } /** * rollBack transaction */ public function rollBackTransaction() { $this->getEntityManager()->rollback(); } /** * @param string $entity * @param $id * * @return object|null */ public function getReference($entity, $id) { try { return $this->getEntityManager()->getReference($entity, $id); } catch (ORMException $ormException) { return null; } } }
Python
UTF-8
161
2.75
3
[]
no_license
import matplotlib.pyplot as plt import os def plot_cost(cost, ax1): ax1.set_xlabel('Iterations') ax1.set_ylabel('Cost') ax1.plot(cost)
Java
UTF-8
209
2.046875
2
[]
no_license
public class Vault { int secretCode = 21000; public boolean tryCode(int code) { if (code == secretCode) { return true; } else { return false; } } public static void main(String[] args) { } }
Java
UTF-8
1,159
1.984375
2
[ "Apache-2.0" ]
permissive
package com.c4_soft.springaddons.starter.webclient; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import reactor.netty.transport.ProxyProvider; @SpringBootTest @ActiveProfiles("host-port") class HostPortTest { @Autowired C4ProxySettings settings; @Autowired C4WebClientBuilderFactoryService service; @Test void testSettings() { assertEquals(10000, settings.getConnectTimeoutMillis()); assertNull(settings.getEnabled()); assertEquals("mini-proxy", settings.getHostname()); assertNull(settings.getNoProxy()); assertNull(settings.getPassword()); assertEquals(7080, settings.getPort()); assertEquals(ProxyProvider.Proxy.HTTP, settings.getType()); assertNull(settings.getUsername()); } @Test void testService() { final var actual = service.get(); assertNotNull(actual); } }
Java
UTF-8
60
2.265625
2
[ "ECL-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
public interface InterfaceJumping { public void jump(); }
Python
UTF-8
1,864
4.125
4
[]
no_license
from collections import Counter def min_window(s, t): """ Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" """ if not t or not s: return "" #Dictionary to keep a count of all unique characters in t. dict_t = Counter(t) # Number of unique characters in t, which needs to be present in the desired window. required = len(dict_t) #left pointer, right, pointer initialization left = 0 right = 0 # Now, we need a way to keep track of if we have a successful window or not. # we will use formed to do this. formed = 0 current_window = {} output = float("inf"), None, None #Now we will begin the sliding window approach. while right < len(s): print(right) character = s[right] print(character) if character in current_window: current_window[character] += 1 else: current_window[character] = 1 if character in dict_t and current_window[character] == dict_t[character]: formed += 1 # IF WE HAVE A WINDOW THAT WORKS while (left <= right and formed == required): character = s[left] #store this current solution if it is better than the old solution if right - left + 1 < output[0]: length = right - left + 1 left_index = left right_index = right output = (length, left_index, right_index) #now we see if we can contract the window. We move the left pointer up by one. current_window[character] -= 1 if character in dict_t and current_window[character] < dict_t[character]: formed -= 1 left += 1 # look for a new window. #increment right once we have contracted current window as much as possible. right += 1 if output[0] == float("inf"): return "" else: solution = s[output[1]:output[2] + 1] #remember indexing in python isn't inclusive on the right side. return solution S = "ADOBECODEBANC" T = "ABC" solution = min_window(S, T) print(solution)
Markdown
UTF-8
5,162
2.734375
3
[ "MIT" ]
permissive
# cordova-plugin-speech [![npm](https://img.shields.io/npm/v/cordova-plugin-speech.svg)](https://www.npmjs.com/package/cordova-plugin-speech) ![Platform](https://img.shields.io/badge/platform-android%20%7C%20ios-lightgrey.svg) This is cordova plugin for Speech Recognition and Text to Speech. ## Installation ``` cordova plugin add cordova-plugin-speech ``` ## Supported Platforms - Android - iOS ## Usage This plugin works with internet connection and without internet if language package available on device. ### supportedLanguages ```js Speech.supportedLanguages ``` `[]String` - Returns list of supported Speech to Text language models. ### getSupportedVoices() ```js Speech.getSupportedVoices(Function successCallback, Function errorCallback) ``` Result of success callback is an Array of supported voices. ### defaultLanguage ```js Speech.supportedLanguages ``` `String` - Returns systems default Speech to Text language model. ### speakOut() ```js let options = { Number pitchRate, Number speechRate, String language } Speech.speakOut(String message, Function successCallback, Function errorCallback, Object options) ``` `message` - {String} message for speaking. Result of success callback is an `String` of TTS states as below: - `tts-start` States that TTS started. - `tts-end` States that TTS ended. This method has an options parameter with the following optional values: - `pitchRate` {Number} used for TTS pitch rate. 1. `iOS` - The default pitch is 1.0. Allowed values are in the range from 0.5 (for lower pitch) to 2.0 (for higher pitch). 1. `Android` - The default pitch is 1.0, lower values lower the tone of the synthesized voice, greater values increase it. - `speechRate` {Number} used for TTS speech rate. 1. `iOS` - The default speech rate is 0.5. Lower values correspond to slower speech, and vice versa. 1. `Android` - The default speech rate is 1.0. Lower values correspond to slower speech, and vice versa. - `language` {String} used for TTS speech voice. 1. `iOS` - Use `Speech.getSupportedVoices()` to get voices and use `selectedVoice.language` as input. 1. `Android` - Use `Speech.getSupportedVoices()` to get voices and use `selectedVoice.name` as input. ### initRecognition() ```js let options = { String language } Speech.initRecognition( Function successCallback, Function errorCallback, Object options) ``` Result of success callback is an `Object` of recognition features as below: - `offlineRecognitionAvailable` {Boolean} states that offline speech recognition is available or not. For Android it's values is always true. This method has an options parameter with the following optional values: - `language` {String} used language for recognition (default is systems default lanuguage model). ### startRecognition() ```js let options = { Boolean partialResultRequired, Boolean offlineRecognitionRequired } Speech.startRecognition( Function successCallback, Function errorCallback, Object options) ``` Result of success callback is an `Object` of recognized terms: - `isFinal` {Boolean} In case of partial result it is `false` otherwise it's `true`. - `text` {String} Recognized text. This method has an options parameter with the following optional values: - `partialResultRequired` {Boolean} Allow partial results to be returned (default `false`) - `offlineRecognitionRequired` {Boolean} Enables offline speech recognition if language model available (default `false`) There is a difference between Android and iOS platforms. On Android speech recognition stops when the speaker finishes speaking (at end of sentence). On iOS the user has to stop manually the recognition process by calling stopRecognition() method. ### stopRecognition() ```js Speech.stopRecognition( Function successCallback, Function errorCallback) ``` Stop the recognition process. Returns `true`. ## Android Quirks ### Requirements - cordova-android v5.0.0 - Android API level 14 - [RECORD_AUDIO](https://developer.android.com/reference/android/Manifest.permission.html#RECORD_AUDIO) permission ### Further readings - https://developer.android.com/reference/android/speech/package-summary.html - https://developer.android.com/reference/android/speech/SpeechRecognizer.html ## iOS Quirks ### Requirements - XCode 8.0 (requires 10.12+ macOS Sierra or 10.11.5+ OS X El Capitan) - iOS 10 - [NSMicrophoneUsageDescription](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW25) permission - [NSSpeechRecognitionUsageDescription](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW52) permission ### Further readings - https://developer.apple.com/reference/speech?language=swift - https://developer.apple.com/reference/speech/sfspeechrecognizer?language=swift ## Author ### Pravinkumar Putta - https://github.com/pravinkumarputta ## LICENSE **cordova-plugin-speech** is licensed under the MIT Open Source license. For more information, see the LICENSE file in this repository.
Swift
UTF-8
418
2.984375
3
[]
no_license
// import SwiftUI struct ContentView: View { @State private var selection: Int = 0 private let items: [String] = ["M", "T", "W", "T", "F", "M", "T", "W", "T", "F"] var body: some View { SegmentedPicker(items: items, selection: $selection) .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
PHP
UTF-8
1,100
2.671875
3
[]
no_license
<?php namespace App\Http\Requests\Checkout; use Illuminate\Foundation\Http\FormRequest; class CheckoutRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'email'=>'required|email', 'name'=>'required', 'address'=>'required', 'phone'=>'required|numeric' ]; } public function messages(){ return [ 'email.required'=>'Email không được trống!', 'email.email'=>'Email không đúng định dạng!', 'name.required'=>'Tên không được trống!', 'address.required'=>'Địa chỉ không được trống!', 'phone.required'=>'điện thoại không được trống!', 'phone.numeric'=>'điện thoại nhập bằng số', ]; } }
C
UTF-8
139
2.96875
3
[]
no_license
void ft_putchar(char c); void ft_putstr(char *str) { int c; c = 0; while (*(str + c)) { ft_putchar(*(str + c)); c = c + 1; } }
Python
UTF-8
6,659
2.515625
3
[]
no_license
import MySQLdb import os def clean_all_table(connection,table): sql_clean="truncate %s;" % (table) try: cursor=connection.cursor() cursor.execute(sql_clean) return True except: connection.rollback() return False def clean_by_condition(connection,table,field,value): if type(value)==int: sql_clean="delete from %s where %s==%d;" % (table,field,value) elif type(value)==float: sql_clean="delete from %s where %s==%f;" % (table,field,value) elif type(value)==str: sql_clean="delete from %s where %s=='%s';" % (table,field,value) try: cursor=connection.cursor() cursor.excute(sql_clean) return True except: connection.rollback() return False def create_conn_db(host,username,password,db): conn=MySQLdb.connect(host,username,password,db) return conn def sql2fasta(connection,table,target_field_list,field,value,outfile): taget_field=','.join(target_field_list) fopen=open(outfile,'w') if type(value)==int: sql_sequence="select %s from %s where %s==%d;" % (taget_field,table,field,value) elif type(value)==float: sql_sequence="select %s from %s where %s==%f;" % (taget_field,table,field,value) elif type(value)==str: sql_sequence="select %s from %s where %s=='%s';" % (taget_field,table,field,value) try: cursor=connection.cursor() cursor.excute(sql_clean) for seq_id,name,sequence in cursor.fetchall(): fopen.write(seq_id+'_'+name+'\n') fopen.write(sequence+'\n') return True except: connection.rollback() return False def allsequence2fasta(connection,table,target_field_list,outfile): taget_field=','.join(target_field_list) fopen=open(outfile,'w') sql_sequence="select %s from %s;" % (taget_field,table) try: cursor=connection.cursor() cursor.execute(sql_sequence) for seq_id,sequence in cursor.fetchall(): fopen.write('>'+str(seq_id)+'\n') fopen.write(sequence+'\n') outputfile_path=os.path.abspath(outfile) return outputfile_path except: connection.rollback() return False def bed_2_mysql(connection,table,field_list,values): target_field=','.join(field_list) sql_insert="insert into %s (%s) value %s;" %(table,target_field,values) cursor=connection.cursor() cursor.execute(sql_insert) connection.commit() def archieve_cds_seq2fasta(connection,outputfile): sql_transcript_seq="select transcript_id,transcript_seq from main_table;" cursor=connection.cursor() cursor_cds=connection.cursor() cursor.execute(sql_transcript_seq) transcript_sequence={} for seq_id,sequence in cursor.fetchall(): transcript_sequence[int(seq_id)]=sequence sql_cds_seq="select annotation_id,transcript_id,cds_start,cds_end,strand from orf_find;" cursor_cds.execute(sql_cds_seq) cds_info=cursor_cds.fetchall() fout=open(outputfile,'w') complementation={'A':'T','C':'G','T':'A','G':'C','N':'N'} for anno_id,trans_id,start,end,strand in cds_info: m_seq=transcript_sequence.get(int(trans_id),None) if strand=='+': cds_seq=m_seq[int(start):int(end)].upper() elif strand=='-': cds_seq_r=m_seq[int(start):int(end)].upper() cds_seq="".join(map(lambda x:complementation[x],cds_seq_r))[::-1] else: print 'error!' fout.write('>'+str(anno_id)+'_'+str(trans_id)+'\n') fout.write(cds_seq+'\n') fout.close() return outputfile def output_cds_seq2fasta(connection,outputfile): sql_transcript_seq="select transcript_id,transcript_seq,transcript_name from main_table;" cursor=connection.cursor() cursor_cds=connection.cursor() cursor.execute(sql_transcript_seq) transcript_sequence={} id_name_dict={} for seq_id,sequence,transcript_name in cursor.fetchall(): transcript_sequence[int(seq_id)]=sequence id_name_dict[int(seq_id)]=transcript_name sql_cds_seq="select annotation_id,transcript_id,cds_start,cds_end,strand from orf_find;" cursor_cds.execute(sql_cds_seq) cds_info=cursor_cds.fetchall() fout=open(outputfile,'w') complementation={'A':'T','C':'G','T':'A','G':'C','N':'N'} for anno_id,trans_id,start,end,strand in cds_info: m_seq=transcript_sequence.get(int(trans_id),None) m_name=id_name_dict[int(trans_id)] if strand=='+': cds_seq=m_seq[int(start):int(end)].upper() elif strand=='-': cds_seq_r=m_seq[int(start):int(end)].upper() cds_seq="".join(map(lambda x:complementation[x],cds_seq_r))[::-1] else: print 'error!' fout.write('>'+m_name+'.cds\n') fout.write(cds_seq+'\n') fout.close() return outputfile def cds_final(connection,outputfile,out_ident,out_cov): sql_transcript_seq="select transcript_id,transcript_seq,transcript_name from main_table;" cursor=connection.cursor() cursor_cds=connection.cursor() cursor.execute(sql_transcript_seq) transcript_sequence={} id_name_dict={} for seq_id,sequence,transcript_name in cursor.fetchall(): transcript_sequence[int(seq_id)]=sequence id_name_dict[int(seq_id)]=transcript_name sql_cds_seq="select annotation_id,transcript_id,cds_start,cds_end,strand from orf_find;" cursor_cds.execute(sql_cds_seq) cds_info=cursor_cds.fetchall() sql_homo_id="select annotation_id,indent,coverage from usearch;" cursor_id=connection.cursor() cursor_id.execute(sql_homo_id) anno_list_usearch=[] for anno_id,indent,coverage in cursor_id.fetchall(): if float(indent)>=float(out_ident*100) and float(coverage)>=float(out_cov*100): anno_list_usearch.append(int(anno_id)) anno_set=set(anno_list_usearch) fout=open(outputfile,'w') complementation={'A':'T','C':'G','T':'A','G':'C','N':'N'} for anno_id,trans_id,start,end,strand in cds_info: if int(anno_id) in anno_set: pass else: continue m_seq=transcript_sequence.get(int(trans_id),None) m_name=id_name_dict[int(trans_id)] if strand=='+': cds_seq=m_seq[int(start):int(end)].upper() elif strand=='-': cds_seq_r=m_seq[int(start):int(end)].upper() cds_seq="".join(map(lambda x:complementation[x],cds_seq_r))[::-1] else: print 'error!' fout.write('>'+m_name+'.cds\n') fout.write(cds_seq+'\n') fout.close() return outputfile
Java
UTF-8
559
1.96875
2
[ "MIT" ]
permissive
package com.weatherforecast.api.business; import java.io.IOException; import com.weatherforecast.api.exception.DataNotFoundException; import com.weatherforecast.api.exception.UnauthorisedException; import com.weatherforecast.api.exception.WeatherForecastException; import com.weatherforecast.api.model.WeatherForecastResp; public interface IWeathrForecstBusiness { public WeatherForecastResp getWeatherStats(final String city,final String cntry) throws DataNotFoundException, IOException, UnauthorisedException, WeatherForecastException; }
Go
UTF-8
1,915
2.890625
3
[ "Apache-2.0" ]
permissive
/* Copyright 2015 All rights reserved. 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 server import ( "fmt" _ "os" "net/http" _ "errors" "log" "github.com/gorilla/mux" "api" ) type Route struct { Path string HandleFn func(http.ResponseWriter, *http.Request) Methods []string } type Server struct { Port string Routes []Route } func NewServer() (*Server, error) { s := Server{ Port: "80", Routes: make([]Route, 0, 6), } s.Routes = append(s.Routes, Route{"/v2/catalog", api.HandleCatalog, []string{"GET"}}) s.Routes = append(s.Routes, Route{`/v2/service_instances/{colon_instance_id}`, api.HandleServiceInstance, []string{"PUT", "PATCH", "DELETE"}}) s.Routes = append(s.Routes, Route{`/v2/service_instances/{colon_instance_id}/service_bindings/{colon_binding_id}`, api.HandleBinding, []string{"PUT", "DELETE"}}) s.Routes = append(s.Routes, Route{"/sayhello", func (w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, "hello world") }, []string{"GET"}}) return &s, nil } func (s *Server) Start() { router := mux.NewRouter() for _, r := range s.Routes { router.HandleFunc(r.Path, r.HandleFn).Methods(r.Methods...) } http.Handle("/", router) fmt.Printf("Listening on port %s\n", s.Port) log.Fatal(http.ListenAndServe(":" + s.Port, nil)) }
Markdown
UTF-8
3,017
2.640625
3
[]
no_license
# scribe-redux This repo contains a barebones skeleton of the Scribe3 application that provides a reference framework for rapid feature development. ## Running in a VM Running inside a virtualized environment is strongly encouraged. To this end, a Vagrantfile is included. Run with vagrant up and the provisioning script will take care of setting up the environment for you. The VM is set up to share the folder in /vagrant, so your changes are immediately reflected. From the VM GUI, you can thus run with: cd /vagrant python scribe.py ## Setting up from scratch Install the dependencies you'll need to compile Cython, plus pip and git if you don't already have them sudo apt-get install build-essential python-dev python-pip git Install pygame as follows sudo apt-get build-dep python-pygame sudo apt-get install python-pygame Install *Cython 0.20.1* and *numpy* : sudo pip install numpy sudo pip install Cython==0.20.1 It's very important that you install this specific Cython version and that you do so before running pip install -r requirements.txt which will install kivy 1.8.0. No other version is allowed. You are now ready to launch with python scribe.py ### Note about virtualenv If you wish to run this program in a virtualenv, you have to decide how many of the previous dependencies do you want to incorporate. You have to consider that *Cython 0.20.1* is an hard requirement for this software to execute and must be installed system-wide. It is however possible to install *kivy* inside virtualenv. Instructions refer to those [provided by kivy](http://kivy.org/docs/installation/installation-linux.html#installation-in-a-virtual-environment-with-system-site-packages). # Initialize virtualenv virtualenv -p python2.7 --system-site-packages venv Note on ***pygame***: Please note that *Pygame* is more easily installed from apt and not included in the *pip*requirements file. This is because there seem to be some [issues](https://bitbucket.org/pygame/pygame/issue/140/pip-install-pygame-fails-on-ubuntu-1204) and hurdles with installing *pygame* within a virtualenv. Should you want to install it with *pip*, you should note that the package is not present in *pypy* and you need to install it from [bitbucket](https://bitbucket.org/pygame/pygame)) by following [these instructions](http://askubuntu.com/questions/299950/how-do-i-install-pygame-in-virtualenv/299965#299965) or use [this script](https://gist.github.com/brousch/6395214#file-install_pygame-sh-L4). Activate your virtualenv before running as above: source venv/bin/activate ## Guidelines - Changes are to be made in folders, one per feature. "dowewantit" contains the skeleton for the feature that consumes our Do We Want It API. - KV files must be used. - The main widget structure that mimics the real Scribe3 application should not be touched, and changes should be self-contained to new widgets.
Java
UTF-8
3,404
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.connectors.kudu.connector.convertor; import org.apache.flink.table.data.*; import org.apache.kudu.Schema; import org.apache.kudu.Type; import org.apache.kudu.client.RowResult; import java.math.BigDecimal; import java.util.Objects; /** * Transform the Kudu RowResult object into a Flink RowData object */ public class RowResultRowDataConvertor implements RowResultConvertor<RowData> { @Override public RowData convertor(RowResult row) { Schema schema = row.getColumnProjection(); GenericRowData values = new GenericRowData(schema.getColumnCount()); schema.getColumns().forEach(column -> { String name = column.getName(); Type type = column.getType(); int pos = schema.getColumnIndex(name); if (Objects.isNull(type)) { throw new IllegalArgumentException("columnName:" + name); } if (row.isNull(name)){ return; } switch (type) { case DECIMAL: BigDecimal decimal = row.getDecimal(name); values.setField(pos, DecimalData.fromBigDecimal(decimal, decimal.precision(), decimal.scale())); break; case UNIXTIME_MICROS: values.setField(pos, TimestampData.fromTimestamp(row.getTimestamp(name))); break; case DOUBLE: values.setField(pos, row.getDouble(name)); break; case STRING: Object value = row.getObject(name); values.setField(pos, StringData.fromString(Objects.nonNull(value) ? value.toString() : "")); break; case BINARY: values.setField(pos, row.getBinary(name)); break; case FLOAT: values.setField(pos, row.getFloat(name)); break; case INT64: values.setField(pos, row.getLong(name)); break; case INT32: case INT16: case INT8: values.setField(pos, row.getInt(name)); break; case BOOL: values.setField(pos, row.getBoolean(name)); break; default: throw new IllegalArgumentException("columnName:" + name + ",type:" + type.getName() + "not support!"); } }); return values; } }
TypeScript
UTF-8
584
2.546875
3
[]
no_license
import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: "upcomingToLatest" }) export class OrderByUpcomingToLatestPipe implements PipeTransform { transform(value: any): any { let newVal = value?.sort((a: any, b: any) => { let date1 = new Date(a.dates.valueDate); let date2 = new Date(b.dates.valueDate); if (date1 <date2) { return 1; } else if (date1 > date2) { return -1; } else { return 0; } }); return newVal; } }
PHP
UTF-8
1,519
2.71875
3
[]
no_license
<?php namespace App\Controllers; use App\Models\Plot; use Core\App; class MatlabController { public function index() { return view('matlab'); } public function execute() { if (redirectIfNotAuthenticated()) { $matlabFile = $_POST['matlabFile']; if (method_exists($this, $matlabFile)) { return $this->$matlabFile($_POST); } } App::get('session')->flash('errors', ['Доступно только авторизованным пользователям.']); return redirect('login'); } private function graf1($data) { extract($data); $image = 'plots/' . str_rand() . '.png'; if (($radius > 0) && ($period > 0) && ($index > 0) && ($radius < 8) && ($period < 8) && ($period > 2 * $radius)) { $command = "matlab -r graf1(" . "'$image'," . "$radius,$period,$index)"; exec($command); (new Plot)->create([ 'user_id' => App::get('session')->get('user_id'), 'image' => $image, 'radius' => $radius, 'period' => $period, 'refrIndex' => $index ]); return redirect('gallery'); } App::get('session')->flash('errors',['Все параметры должны быть положительными, радиус и период < 8, период больше двух радиусов']); return redirect('work'); } }
JavaScript
UTF-8
489
3.328125
3
[ "MIT" ]
permissive
function isEqual(str1,str2){ let isEqual = false; let indexFound = null; let comparingIndex = 0; debugger; if(str2.length <= str1.length){ for(let i = 0;i<str1.length && str2[comparingIndex]!==undefined;i++,comparingIndex++){ if(str2[comparingIndex] === str1[i]){ indexFound = i; isEqual = true }else if(comparingIndex>0){ isEqual = false ; comparingIndex = 0; } } } return isEqual; }
Java
UTF-8
588
2.25
2
[]
no_license
package edu.wpi.grip.core.events; import edu.wpi.grip.core.settings.CodeGenerationSettings; import static com.google.common.base.Preconditions.checkNotNull; /** * An event fired when code generation settings are changed. */ public class CodeGenerationSettingsChangedEvent implements DirtiesSaveEvent { private final CodeGenerationSettings settings; public CodeGenerationSettingsChangedEvent(CodeGenerationSettings settings) { this.settings = checkNotNull(settings, "settings"); } public CodeGenerationSettings getCodeGenerationSettings() { return settings; } }
C++
UTF-8
705
3.71875
4
[]
no_license
//修剪二叉搜索树 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* trimBST(TreeNode* root, int L, int R) { if(root==nullptr) return nullptr; TreeNode* new_root=root; if(root->val<L) new_root=trimBST(root->right,L,R); else if(root->val>R) new_root=trimBST(root->left,L,R); else { new_root->left=trimBST(root->left,L,R); new_root->right=trimBST(root->right,L,R); } return new_root; } };
PHP
UTF-8
1,906
2.625
3
[]
no_license
<?php session_start(); if (!isset($_SESSION['login'])) { $_SESSION['login']="incorreto"; } if($_SESSION['login']=="correto"&& isset($_SESSION['login'])){ //conteúdo if ($_SERVER['REQUEST_METHOD']=="GET") { if (isset($_GET['festa'])&& is_numeric($_GET['festa'])) { $idFesta=$_GET['festa']; $con=new mysqli("localhost","root","","festa"); if ($con->connect_errno!=0) { echo "<h1>Ocorreu um erro no acesso a base de dados.<br>".$connect_error."</h1>"; exit(); } $sql="Select * from festivais where id=?"; $stm=$con->prepare($sql); if ($stm!=false) { $stm->bind_param("i",$idFesta); $stm->execute(); $res=$stm->get_result(); $festa=$res->fetch_assoc(); $stm->close(); } ?> <!DOCTYPE html> <html> <head> <title>Editar Festivais</title> </head> <body> <h1>Editar Festivais</h1> <form action="festa_update.php"method="post"> <label>id</label><input type="text" name="id" required value="<?php echo $festa['id'];?>"><br> <label>Festivais</label><input type="text" name="Festivais" required value="<?php echo $festa['festival'];?>"><br> <input type="hidden" name="id" value="<?php echo $festa['id'];?>"><br> <input type="hidden" name="id_festa" required value="<?php echo $festa['id'];?>"> <input type="submit" name="enviar"><br> </form> </body> </html> <?php } else{ echo ("<h1>houve um erro ao precessar o seu pedido.<br> Dentro de segundos sera reencaminhado!</h1>"); header("refresh:5; url=index.php"); } } } else{ echo "Para entrar nesta página necessita de efetuar <a href='login.php'>login</a>"; header('refresh:2;url=login.php'); } ?>
Java
UTF-8
328
1.890625
2
[]
no_license
package com.hlf.ssm.dao; import java.util.List; import com.hlf.ssm.model.Goods; import com.hlf.ssm.model.GoodsType; public interface GoodsTypeMapper { int insert(GoodsType goodsType); int deleteById(int id); int updateById(int id); GoodsType selectById(int id); List<GoodsType> findAll(); }
Python
UTF-8
1,846
3.65625
4
[ "MIT" ]
permissive
#! usr/bin/python # Quick check to make sure we're getting all of our links before we move on # Let's look at the URL string # What we really care about are the numbers at the end of the link; that's # how the whole setup for the website works. We feed it an ID, it generates # a page. # We only need the number at the end; we can split the URL and grab it # Just as a test, let's look at the first one to see what we're dealing with. # Two tables on each page, both are functionally identical to BeautifulSoup, # so we just grab both and take the second. # The names are coming from a db that's dynamically combining them; we can use that. # All the components are inside of label tags. If we try to extract the text, we're # met with a mess of unicode junk (non-breaking spaces, in this case) meant to # glue the title, first name, middle initial and last name together. # Pull the name and clean it up with split(), which by default will work on # whitespace. .join and .split together can be handy for cleaning. # Depending on how we need the name to be parsed, it might be better for us # to chop it up into components. # Now that we see how this works, we can write a full run. We'll feed # requests.get a page, parse it with BeautifulSoup, and write it to CSV. # We can use the 'with' syntax here to open the file # We can basically use what we've done above to zero in on the table # Another for loop to move inside each row (except the header) # If it's a vacancy, let's not go through the trouble of splitting. # Slot the different components here # Last name is currently including suffixes like Jr, Sr, III, etc. # We can look for a comma that denotes the suffix.
JavaScript
UTF-8
1,521
2.96875
3
[]
no_license
import { sprintf } from 'sprintf-js'; class Helpers { static formatTime(seconds) { let timeFormats = [[0, '< 1 sec'], [2, '1 sec'], [59, 'secs', 1], [60, '1 min'], [3600, 'mins', 60], [5400, '1 hr'], [86400, 'hrs', 3600], [129600, '1 day'], [604800, 'days', 86400] ]; for (let format of timeFormats) { if (seconds >= format[0]) { continue; } if (2 == format.length) { return format[1]; } return Math.ceil(seconds / format[2]) + ' ' + format[1]; } } static formatMemory(memory) { if (memory >= 1024 * 1024 * 1024) { return sprintf('%.1f GiB', memory / 1024 / 1024 / 1024); } if (memory >= 1024 * 1024) { return sprintf('%.1f MiB', memory / 1024 / 1024); } if (memory >= 1024) { return sprintf('%d KiB', memory / 1024); } return sprintf('%d B', memory); } static strlenWithoutDecoration(string) { var pattern = /\033\[[^m]*m/g; return string.replace(pattern, "\n").length; } static encode(xs) { let bytes = (s) => { if (typeof s === 'string') { return s.split('').map(this.ord); } else if (Array.isArray(s)) { return s.reduce(function (acc, c) { return acc.concat(bytes(c)); }, []); } } console.log(bytes(xs)); return new Buffer([ 0x1b ].concat(bytes(xs))); } static ord (c) { return c.charCodeAt(0) } } export default Helpers;
JavaScript
UTF-8
725
2.765625
3
[]
no_license
function deleteAlbumField() { $("#inputAlbumId").val(""); } function deletePlaylistField() { $("#inputPlaylistId").val(""); } function getTokenFromForm() { return $("#inputTokenId").val(); } function getAlbumIdFromForm() { return $("#inputAlbumId").val(); } function getPlaylistIdFromForm() { return $("#inputPlaylistId").val(); } function xor(A, B) { var a = !isBlank(A); var b = !isBlank(B); return (a || b) && !(a && b); } function isBlank(str) { return (!str || /^\s*$/.test(str)); } function getRaccolta() { albumId = getAlbumIdFromForm(); playlistId = getPlaylistIdFromForm(); if (!isBlank(albumId)) { return [albumId, true]; } else if (!isBlank(playlistId)) { return [playlistId, false]; } }
C#
UTF-8
3,630
3.21875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Assignment2_2 { public partial class Form1 : Form { int[] frequency = new int[6]; int[] percent = new int[6]; int[] timesguessed = new int[6]; int timesplayed = 0; int timeswon = 0; int timeslost = 0; public Form1() { InitializeComponent(); richTextBox1.Text = "FACE\t FREQUENCY\t PERCENT\tTIMES GUESSED\n" + "1\t\t0\t\t0%\t\t0\n" + "2\t\t0\t\t0%\t\t0\n" + "3\t\t0\t\t0%\t\t0\n" + "4\t\t0\t\t0%\t\t0\n" + "5\t\t0\t\t0%\t\t0\n" + "6\t\t0\t\t0%\t\t0\n"; } private void Button1_Click(object sender, EventArgs e) { int value; if (int.TryParse(textBox1.Text, out value) && value >= 1 && value <= 6) { //add to the number of times played timesplayed+=1; //add increment value to the number of times guessed int faceguessed = value - 1; timesguessed[faceguessed] += 1; Random random = new Random(); int dice =0; for (int i = 1; i < 7; i++) { dice = random.Next(1, 7); //show image's of dice roll pictureBox1.Image = (Image)(Properties.Resources.ResourceManager.GetObject($"die{dice}")); pictureBox1.Refresh(); Thread.Sleep(300); } //Check if won or lost if (value == dice) { timeswon += 1; } else { timeslost += 1; } //increment dice value to the frequency array int face = dice - 1; frequency[face] += 1; label6.Text = $"your last guess:{value}"; printValues(); } else { label6.Text = "Invalid input please type a number between 1-6, try again."; } } void resetValue() { frequency = new int[6]; timesguessed = new int[6]; percent = new int[6]; timesplayed = 0; timeswon = 0; timeslost = 0; textBox1.Text = ""; } void printValues() { label2.Text = $"Number of Times Played: {timesplayed}"; label3.Text = $"Number of Times Won: {timeswon}"; label4.Text = $"Number of Time Lost: {timeslost}"; richTextBox1.Text = "FACE\t FREQUENCY\t PERCENT\tTIMES GUESSED\n"; for (int i = 0; i <= 5; i++) { double percentage = (double) frequency[i] / (timesplayed ); richTextBox1.Text += $"{i + 1}\t\t{frequency[i]}\t\t{percentage*100:f3}%\t\t{timesguessed[i]}\n"; } } private void Button2_Click(object sender, EventArgs e) { resetValue(); printValues(); } } }
C++
UTF-8
1,384
3.03125
3
[]
no_license
// Modified Room database. // In charge of actually storing the rooms, and then for saving and loading them to and from file. #ifndef SIMPLEMUDROOMDATABASE_H #define SIMPLEMUDROOMDATABASE_H #include <cmath> #include <string> #include <unordered_map> #include <set> #include <stdexcept> #include <memory> #include "EntityDatabase.h" #include "Room.h" #include "DatabasePointer.h" namespace SimpleMUD { // No longer a child of EntityDatabase. Want to be able to use a Vector2 as a key. // Probably going to be the only case of this so will just do it once here. // Ronan. class RoomDatabase { protected: static std::unordered_map<BasicLib::vector2, std::shared_ptr<Room>> m_rooms; public: // They need to know the particular way of saving and loading data for these. // Should be similar to other room model, but just doing a bit of it manually void Load(); static void LoadTemplates(); static void LoadData(); static void SaveData(); // Adding a room. // Adding a new room that it was given. static void AddRoom(BasicLib::vector2 p_coords, std::shared_ptr<Room> p_room); // Does a room at coord X exist? // Using map.count(Key) to see if the thing is there static bool RoomExists(BasicLib::vector2 p_coords); static std::shared_ptr<Room>& GetRoom(BasicLib::vector2 p_coords); }; // end class RoomDatabase } // end namespace SimpleMUD #endif
Java
UTF-8
452
3.125
3
[]
no_license
import java.util.Arrays; public class BinaryGenerator{ private byte aux[]; public void generate(int N){ aux = new byte[N]; gen(N); } private void gen(int N){ if(N < 1){ System.out.println(Arrays.toString(aux)); }else{ aux[N-1]=0; gen(N-1); aux[N-1]=1; gen(N-1); } } public static void main(String[] args){ BinaryGenerator bg = new BinaryGenerator(); bg.generate(3); } }
Java
UTF-8
2,109
2.09375
2
[]
no_license
/* * Powered By zbjdl-code-generator * Web Site: http://www.zbjdl.com * Since 2018 - 2022 */ package com.zbjdl.oa.model; /** * TargetInfo * @author code-generator * */ public class TargetInfo { private java.lang.Long id; private java.lang.Long userId; private com.zbjdl.common.amount.Amount targetAmount; private java.lang.String targetMonth; private java.lang.String assignId; private java.util.Date createTime; private java.util.Date lastUpdateTime; /** * @param id */ public void setId(Long id) { this.id = id; } /** * @return */ public Long getId() { return this.id; } /** * 员工id * @param userId */ public void setUserId(java.lang.Long userId) { this.userId = userId; } /** * 员工id * @return */ public java.lang.Long getUserId() { return this.userId; } /** * 销售目标 * @param targetAmount */ public void setTargetAmount(com.zbjdl.common.amount.Amount targetAmount) { this.targetAmount = targetAmount; } /** * 销售目标 * @return */ public com.zbjdl.common.amount.Amount getTargetAmount() { return this.targetAmount; } /** * 目标月份 * @param targetMonth */ public void setTargetMonth(java.lang.String targetMonth) { this.targetMonth = targetMonth; } /** * 目标月份 * @return */ public java.lang.String getTargetMonth() { return this.targetMonth; } /** * 委派人id * @param assignId */ public void setAssignId(java.lang.String assignId) { this.assignId = assignId; } /** * 委派人id * @return */ public java.lang.String getAssignId() { return this.assignId; } /** * * @param createTime */ public void setCreateTime(java.util.Date createTime) { this.createTime = createTime; } /** * * @return */ public java.util.Date getCreateTime() { return this.createTime; } /** * * @param lastUpdateTime */ public void setLastUpdateTime(java.util.Date lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } /** * * @return */ public java.util.Date getLastUpdateTime() { return this.lastUpdateTime; } }
Java
UTF-8
1,045
3.171875
3
[]
no_license
package france.alsace.fl.fileencryptor; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; /** * A observable counter * @author Florent */ public class Counter { private IntegerProperty cnt = new SimpleIntegerProperty(); /** * Default constructor */ public Counter() { this.cnt.set(0); } /** * Constructor with parameter * @param init the initial value of the counter */ public Counter(int init) { this.cnt.set(init); } /** * Increment the counter (synchronized function) */ public synchronized void increment() { cnt.set(cnt.getValue()+1); } /** * Return the counter value (property) * @return the counter value (property) */ public IntegerProperty getCounter() { return cnt; } /** * Return the counter value (int) * @return the counter value (int) */ public int getValue() { return cnt.get(); } }
Python
UTF-8
706
3.46875
3
[]
no_license
from graph import Graph from collections import deque def bfs(g: Graph, v: int): if not g.has_vertex(v): raise ValueError(f"Vertex {v} not found in graph {g}.") queue = deque() queue.append(v) visited = set() while queue: current_vertex = queue.popleft() if current_vertex not in visited: print(f"Processing vertex {current_vertex}") queue.extend(g.get_adjacent_vertices(current_vertex)) visited.add(current_vertex) print("Finished processing") if __name__ == "__main__": g = Graph(list(range(4)), []) g.add_edge((0, 1)) g.add_edge((0, 2)) g.add_edge((1, 3)) g.add_edge((2, 3)) bfs(g, 0)
PHP
UTF-8
395
2.890625
3
[ "MIT" ]
permissive
<?php use Pazuzu156\Gravatar\Gravatar; if (!function_exists('g_const')) { /** * Uses Gravatar's _const function to get the value of supplied constant. * * @param string $constant - The constant you need to get the value of * * @return string */ function g_const($constant) { $g = new Gravatar(); return $g->_const($constant); } }