language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
955
2.703125
3
[]
no_license
package raceinggame; import game.engine.*; //import raceinggame.RacingLayer; public class Racing extends GameEngine { private static final int SCREEN_WIDTH = 1024; private static final int SCREEN_HEIGHT = 768; public Racing() { gameStart( SCREEN_WIDTH, SCREEN_HEIGHT, 32 ); } @Override public boolean buildAssetManager() { //assetManager.loadAssetsFromFile(this.getClass().getResource("images/RacingAssets.txt")); assetManager.addImageAsset("Track",getClass().getResource("images/Track.png")); assetManager.addImageAsset("TrackHitRegions",getClass().getResource("images/TrackHitRegions.png")); assetManager.addImageAsset("Car",getClass().getResource("images/Car.png")); return true; } @Override protected boolean buildInitialGameLayers() { RacingLayer racingLayer = new RacingLayer( this ); addGameLayer( racingLayer ); return true; } public static void main(String[] args) { Racing instance = new Racing(); } }
Markdown
UTF-8
2,641
3.234375
3
[]
no_license
# ReinforcementNavigation # Project 1: Navigation # by Peerajak Witoonchart as a project for Udacity deep reinforcement learning nano degree. Suppose you are to build an automatic banana eating monkey robot, how could you do?. Suppose there are two kinds of banana, the yellow bananas which taste good, and the dark blue bananas which taste bad. How could you program the monkey robot in such a way that it selects only yellow bananas? To solve this problem, let us start with a human controllable handjoy and control the monkey robot manually. We have - **`0`** - move forward. - **`1`** - move backward. - **`2`** - turn left. - **`3`** - turn right. , where the **'n'** is the nth botton of handjoy. In this project, we will show how to write a program, called an agent, to build an automatic banana eating monkey robot for a virtual continuous environment containing both yellow and dark blue bananas. The goal of the robot is to collect as much as possible yello bananas while avoid collecting dark blue bananas. The game ends episodically. ### Introduction To solve this problem, we apply Deep Q network. In Navigation.ipynb, the Deep Q network algorithm is implemented. ### Getting Started You need Python3 and some dependencies. An anaconda environment is recommended. Please follow https://github.com/udacity/deep-reinforcement-learning on dependencies topic to have your enviroment and dependencies installed After the above is done, you can start with 1. Clone the repository to your local machine >git clone https://github.com/peerajak/ReinforcementNavigation.git 2. Change directory to the cloned directory. Download the Unity Environment Linux: https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/Banana_Linux.zip and unzip to the cloned directory 3. Make sure that your kernel is the installed dependencies, in this case, dlnd enviroment. >python -m jupyter notebook Navigation.ipynb The ipython file should be automatically shown on your web browser. 4. Save your model >agent.save_model(< your file Path here >) Check the saved file at your file path. 5. Initiate new empty model and reload the saved model >agent2 = Agent(brain.vector_observation_space_size, brain.vector_action_space_size, seed=0) >agent2.load_model(< your file Path here >) 6. Environment solved. This is shown in the last two cells at the end of the Navigation.ipynb, where random agent are test against the trained agent. Clearly, the train agents, with avg score of ~14, triumps over random agent. ### Understanding the Algorithm Please read Report.pdf to understand the implementation of deep Q network and their parameters.
C#
UTF-8
4,815
2.5625
3
[]
no_license
#region PRE_SCRIPT using System.Collections.Generic; using Sandbox.ModAPI.Ingame; using Sandbox.ModAPI.Interfaces; public class TurretEvader : MyGridProgram { #endregion PRE_SCRIPT //auto turret evasion script // // if you travel too fast towards the turret, it will catch your predictable vector. List <IMyTerminalBlock> thrusters = new List <IMyTerminalBlock>(); List <IMyTerminalBlock> left = new List <IMyTerminalBlock>(); List <IMyTerminalBlock> up = new List <IMyTerminalBlock>(); List <IMyTerminalBlock> right = new List <IMyTerminalBlock>(); List <IMyTerminalBlock> down = new List <IMyTerminalBlock>(); IMyTerminalBlock timer; bool first_time = true; bool end_program = true; int state = 0; const float maxOverride = 500000.0f; const float gravityFactor = 1000.0f; bool isAtmospheric = false; void Main (string argument) { if (first_time) { first_time = false; Initialize (); } if (argument == "run") { end_program = false; isAtmospheric = false; } else if(argument == "run atmo") { end_program = false; isAtmospheric = true; } else if (argument == "stop") { StopVessel (); } if (end_program == false) { ApplyState (); timer.ApplyAction ("Start"); } } //this function will fetch objects from terminal only once in order to save performance. void Initialize() { GridTerminalSystem.GetBlocksOfType <IMyThrust> (thrusters); timer = GridTerminalSystem.GetBlockWithName ("script timer"); state = 1; for (int a = 0; a < thrusters.Count; a++) { thrusters[a].ApplyAction ("OnOff_On"); string blocksOrientation = thrusters[a].Orientation.ToString(); string[] refinedResult = blocksOrientation.Split (','); refinedResult = refinedResult[0].Split (':'); switch (refinedResult[1]) { case "Up": up.Add (thrusters[a]); break; case "Down": down.Add (thrusters[a]); break; case "Left": left.Add (thrusters[a]); break; case "Right": right.Add (thrusters[a]); break; } } } //this function cycles through four states which thrust the decoy in a circle, while in the atmosphere. void ApplyState() { switch (state) { case 1: state = 2; ChangeOverride (left, true); ChangeOverride (down, false); Echo ("left"); break; case 2: state = 3; ChangeOverride (up, true, true); ChangeOverride (left, false); Echo ("up"); break; case 3: state = 4; ChangeOverride (right, true); ChangeOverride (up, false); Echo ("right"); break; case 4: state = 1; ChangeOverride (down, true); ChangeOverride (right, false); Echo ("down"); break; } } //this function will change thrust override based on argument inputs. void ChangeOverride (List <IMyTerminalBlock> thruster_face, bool isOn, bool goingDown = false) { for (int a = 0; a < thruster_face.Count; a++) { if (isOn) { if (isAtmospheric && goingDown) { float reducedOverride = maxOverride / gravityFactor; thruster_face[a].SetValueFloat("Override", reducedOverride); } else { thruster_face[a].SetValueFloat("Override", maxOverride); } } else { thruster_face[a].SetValueFloat("Override", 0.0F); } } } //this function resets the ship to its normal state if the user inputs a certain string. void StopVessel() { end_program = true; for (int a = 0; a < thrusters.Count; a++) { thrusters[a].SetValueFloat ("Override", 0.0f); thrusters[a].ApplyAction ("OnOff_On"); } timer.ApplyAction("Stop"); } #region POST_SCRIPT } #endregion POST_SCRIPT
Java
UTF-8
2,826
2.71875
3
[]
no_license
package rosa.archive.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Columns: * Standard Name, Alternate Name 1, Alternate Name 2, Alternate Name 3, Alternate Name 4, Alternate Name 5, Bibl. Information: author, Bibl. Information: full title, USTC, EEBO, Digitale Sammlungen, Perseus, Other */ public final class BookReferenceSheet extends ReferenceSheet implements HasId, Serializable { private static final long serialVersionUID = 1L; public enum Link { USTC(8, "USTC"), EEBO(9, "EEBO"), DIGITALE_SAMMLUNGEN(10, "Digitale Sammlungen"), PERSEUS(11, "Perseus"), OTHER(12, "Other"); public final String label; public final int index; Link(int index, String label) { this.index = index; this.label = label; } public static Link getFromIndex(int i) { for (Link l : Link.values()) { if (i == l.index) { return l; } } return null; } } @Override public List<String> getAlternates(String key) { if (!hasAlternates(key)) { return null; } List<String> result = new ArrayList<>(); int len = getLine(key).size(); for (int i = 1; i < len; i++) { if (i >= 6) { continue; } String val = getCell(key, i); if (val != null && !val.isEmpty()) { result.add(val); } } return result; } public List<String> getAuthors(String key) { String authors = getCell(key, 6); if (authors == null || authors.isEmpty()) { return null; } return Arrays.asList(authors.split(",")); } public String getFullTitle(String key) { String title = getCell(key, 7); if (title == null || title.isEmpty()) { return null; } return title; } /** * Get external links related to a book that has been referenced from the AOR corpus. * Map: label -> URI * * @param key standard book name * @return map */ public Map<String, String> getExternalLinks(String key) { if (!containsKey(key)) { return null; } List<String> line = getLine(key); Map<String, String> map = new HashMap<>(); for (int i = 8; i < line.size(); i++) { Link l = Link.getFromIndex(i); String val = line.get(i); if (l != null && (val != null && !val.isEmpty())) { map.put(l.label, line.get(i)); } } return map; } }
Rust
UTF-8
5,383
3.234375
3
[ "Unlicense" ]
permissive
//! Definition of the WAM. use functor::Functor; use self::mem::{Cell, Memory, Pointer, Slot, Register}; pub mod mem; #[cfg(test)] mod test; #[derive(Debug)] pub struct Machine { mem: Memory, mode: Mode, } #[derive(Debug)] enum Mode { Read(Slot), Write, } pub type Fallible = Result<(),()>; pub trait MachineOps { fn put_structure(&mut self, f: Functor, r: Register); fn set_variable(&mut self, r: Register); fn set_value(&mut self, r: Register); fn get_structure(&mut self, f: Functor, r: Register) -> Fallible; fn unify_variable(&mut self, r: Register); fn unify_value(&mut self, r: Register) -> Fallible; } impl Machine { pub fn new(num_registers: usize) -> Machine { Machine { mem: Memory::new(num_registers), mode: Mode::Write } } pub fn mgu<'m,P:mem::Pointer>(&'m self, addr: P) -> mem::MGU<'m> { mem::MGU::new(&self.mem, addr.to_address()) } pub fn dump<'m>(&'m mut self) -> DumpMachine<'m> { DumpMachine { machine: self } } } impl MachineOps for Machine { /// from tutorial figure 2.2 fn put_structure(&mut self, f: Functor, r: Register) { let ptr = self.mem.next_slot(); let cell = Cell::Structure(ptr + 1); self.mem.push(cell); self.mem.push(Cell::Functor(f)); self.mem.store(r, cell); } /// from tutorial figure 2.2 fn set_variable(&mut self, r: Register) { let ptr = self.mem.next_slot(); let cell = Cell::Ref(ptr); self.mem.push(cell); self.mem.store(r, cell); } /// from tutorial figure 2.2 fn set_value(&mut self, r: Register) { let cell = self.mem.load(r); self.mem.push(cell); } fn get_structure(&mut self, f: Functor, r: Register) -> Fallible { let addr = self.mem.deref(r.to_address()); match self.mem.load(addr) { Cell::Ref(_) => { let slot = self.mem.next_slot(); self.mem.push(Cell::Structure(slot + 1)); self.mem.push(Cell::Functor(f)); self.mem.bind(addr, slot.to_address()); self.mode = Mode::Write; Ok(()) } Cell::Structure(slot) => { if self.mem.load(slot) == Cell::Functor(f) { let next = slot + 1; self.mode = Mode::Read(next); Ok(()) } else { // if the pointer doesn't reference a functor, heap is inconsistent debug_assert!(match self.mem.load(slot) { Cell::Functor(_) => true, _ => false, }); Err(()) } } Cell::Functor(_) => { Err(()) } Cell::Uninitialized => { panic!("Load from uninitialized cell at {:?}", addr) } } } fn unify_variable(&mut self, reg: Register) { match self.mode { Mode::Read(ref mut next) => { let cell = self.mem.load(*next); self.mem.store(reg, cell); next.bump(); } Mode::Write => { let ptr = self.mem.next_slot(); let cell = Cell::Ref(ptr); self.mem.push(cell); self.mem.store(reg, cell); } } } fn unify_value(&mut self, reg: Register) -> Fallible { match self.mode { Mode::Read(ref mut next) => { try!(self.mem.unify(reg.to_address(), next.to_address())); next.bump(); Ok(()) } Mode::Write => { let cell = self.mem.load(reg); self.mem.push(cell); Ok(()) } } } } pub struct DumpMachine<'m> { machine: &'m mut Machine } impl<'m> MachineOps for DumpMachine<'m> { fn put_structure(&mut self, f: Functor, r: Register) { let result = self.machine.put_structure(f, r); println!("put_structure({:?}, {:?}) = {:?}", f, r, result); println!("{:#?}", self.machine); result } fn set_variable(&mut self, r: Register) { let result = self.machine.set_variable(r); println!("set_variable({:?}) = {:?}", r, result); println!("{:#?}", self.machine); result } fn set_value(&mut self, r: Register) { let result = self.machine.set_value(r); println!("set_value({:?}) = {:?}", r, result); println!("{:#?}", self.machine); result } fn get_structure(&mut self, f: Functor, r: Register) -> Fallible { let result = self.machine.get_structure(f, r); println!("get_structure({:?}, {:?}) = {:?}", f, r, result); println!("{:#?}", self.machine); result } fn unify_variable(&mut self, r: Register) { let result = self.machine.unify_variable(r); println!("unify_variable({:?}) = {:?}", r, result); println!("{:#?}", self.machine); result } fn unify_value(&mut self, r: Register) -> Fallible { let result = self.machine.unify_value(r); println!("unify_variable({:?}) = {:?}", r, result); println!("{:#?}", self.machine); result } }
C
UTF-8
2,511
3.21875
3
[ "MIT" ]
permissive
/* logical words */ void andfunc() { if (data_stack_ptr < 2) { printf("'and' needs two elements on the stack!\n"); return; } push((DCLANG_INT) dclang_pop() & (DCLANG_INT) dclang_pop()); } void orfunc() { if (data_stack_ptr < 2) { printf("'or' needs two elements on the stack!\n"); return; } push((DCLANG_INT) dclang_pop() | (DCLANG_INT) dclang_pop()); } void xorfunc() { if (data_stack_ptr < 2) { printf("'xor' needs two elements on the stack!\n"); return; } push((DCLANG_INT) dclang_pop() ^ (DCLANG_INT) dclang_pop()); } void notfunc() { if (data_stack_ptr < 1) { printf("'not' needs an element on the stack!\n"); return; } push(~(DCLANG_INT) dclang_pop()); } /* comparison booleans */ void eqfunc() { if (data_stack_ptr < 2) { printf("'=' needs two elements on the stack!\n"); return; } push(((DCLANG_FLT) dclang_pop() == (DCLANG_FLT) dclang_pop()) * -1); } void noteqfunc() { if (data_stack_ptr < 2) { printf("'!=' needs two elements on the stack!\n"); return; } push(((DCLANG_FLT) dclang_pop() != (DCLANG_FLT) dclang_pop()) * -1); } void gtfunc() { if (data_stack_ptr < 2) { printf("'>' needs two elements on the stack!\n"); return; } push(((DCLANG_FLT) dclang_pop() < (DCLANG_FLT) dclang_pop()) * -1); } void ltfunc() { if (data_stack_ptr < 2) { printf("'<' needs two elements on the stack!\n"); return; } push(((DCLANG_FLT) dclang_pop() > (DCLANG_FLT) dclang_pop()) * -1); } void gtefunc() { if (data_stack_ptr < 2) { printf("'>=' needs two elements on the stack!\n"); return; } push(((DCLANG_FLT) dclang_pop() <= (DCLANG_FLT) dclang_pop()) * -1); } void ltefunc() { if (data_stack_ptr < 2) { printf("'<=' needs two elements on the stack!\n"); return; } push(((DCLANG_FLT) dclang_pop() >= (DCLANG_FLT) dclang_pop()) * -1); } // assertions void assertfunc() { if (data_stack_ptr < 1) { printf("'assert' needs an element on the stack!\n"); return; } DCLANG_INT truth = dclang_pop(); if (truth == 0) { printf("ASSERT FAIL!\n"); } } // true/false syntactic sugar void truefunc() { push(-1); } void falsefunc() { push(0); } // null (synonymous with 0) void nullfunc() { void *ptr = NULL; push((DCLANG_INT)ptr); }
C++
UTF-8
4,295
2.65625
3
[]
no_license
#include <windows.h> #include <stdlib.h> #include <iostream> using namespace std; HANDLE OpenComPort(char* PortName) { HANDLE hCom = CreateFileA(PortName, //port name GENERIC_READ | GENERIC_WRITE, //Read/Write 0, // No Sharing NULL, // No Security OPEN_EXISTING,// Open existing port only 0, // Non Overlapped I/O NULL); if (hCom == INVALID_HANDLE_VALUE) { cout << "Error in opening serial port"; return INVALID_HANDLE_VALUE; } cout << "Opening serial port successful"; return hCom; } bool CloseComPort(HANDLE ComPort) { if(CloseHandle(ComPort)) return true; return false; } bool SetComPortParams(HANDLE ComPort, DCB** ConfSP) { DCB* conf = new DCB[1]; //*conf = 0; conf->DCBlength = sizeof(*conf); if(GetCommState(ComPort, conf)) { conf->BaudRate = CBR_9600; // Setting BaudRate = 9600 conf->ByteSize = 8; // Setting ByteSize = 8 conf->StopBits = ONESTOPBIT;// Setting StopBits = 1 conf->Parity = NOPARITY; // Setting Parity = None *ConfSP = conf; return true; } return false; } bool ConfigureComPort(HANDLE ComPort, DCB* Params) { if(SetCommState(ComPort, Params)) return true; return false; } int SizeOf(const char* dat) { int size = 0; while(*dat != '\0') { size += sizeof(*dat); dat++; } return ++size; } bool WriteComPort(HANDLE ComPort, const char data) { DWORD dNoOFBytestoWrite = sizeof(data); // No of bytes to write into the port DWORD dNoOfBytesWritten = 0; // No of bytes written to the port bool Status = WriteFile(ComPort, // Handle to the Serial port &data, // Data to be written to the port dNoOFBytestoWrite, //No of bytes to write &dNoOfBytesWritten, //Bytes written NULL); return Status; } void ReadComPort(HANDLE ComPort) { DWORD dwEventMask; bool Status = SetCommMask(ComPort, EV_RXCHAR); Status = WaitCommEvent(ComPort, &dwEventMask, NULL); char TempChar; //Temporary character used for reading char SerialBuffer[256];//Buffer for storing Rxed Data DWORD NoBytesRead; int i = 0; do { ReadFile(ComPort, //Handle of the Serial port &TempChar, //Temporary character sizeof(TempChar),//Size of TempChar &NoBytesRead, //Number of bytes read NULL); SerialBuffer[i] = TempChar;// Store Tempchar into buffer i++; } while (NoBytesRead > 0); } HANDLE InitComPort(char* PortName) { HANDLE RetVal = INVALID_HANDLE_VALUE; HANDLE ComPort = OpenComPort(PortName); if(ComPort == RetVal) return RetVal; DCB* ConfSP; if(!SetComPortParams(ComPort, &ConfSP)) return RetVal; if(!ConfigureComPort(ComPort, ConfSP)) return RetVal; if(!WriteComPort(ComPort, 0x50)) return RetVal; Sleep(300); if(!WriteComPort(ComPort, 0x51)) return RetVal; Sleep(100); return ComPort; } HANDLE halOpenRelay(char* PortName) { if(!PortName) { PortName = getenv("RELAY_COMPORT"); } HANDLE ComPort = InitComPort(PortName); //setenv(RELAY_STATE); if(ComPort == INVALID_HANDLE_VALUE) return ComPort; CloseComPort(ComPort); return ComPort; } BOOL halResetRelay(char* PortName, int relay, int delay) { if(!PortName) { PortName = getenv("RELAY_COMPORT"); } //char* state=getenv("RELAY_STATE"); //int state=atoi(state); BOOL RetVal;// = INVALID_HANDLE_VALUE; HANDLE ComPort = OpenComPort(PortName); if(ComPort == INVALID_HANDLE_VALUE) return 1; DCB* ConfSP; if(!SetComPortParams(ComPort, &ConfSP)) return 1; if(!ConfigureComPort(ComPort, ConfSP)) return 1; if(!(RetVal=WriteComPort(ComPort, 1<<relay))) return 1; Sleep(delay); if(!(RetVal=WriteComPort(ComPort, 0 ))) return 1; Sleep(delay); CloseComPort(ComPort); return 0; }
Python
UTF-8
488
2.5625
3
[]
no_license
import re def get_res(): res = {} re_for_extracting_number_of_results = re.compile('[0-9]+') re_for_extracting_number_of_views_and_replies = re_for_extracting_number_of_results re_for_extracting_search_id = re.compile('searchid=[0-9]+') res['extracting_number_of_results'] = re_for_extracting_number_of_results res['extracting_number_of_views_and_replies'] = re_for_extracting_number_of_views_and_replies res['extracting_search_id'] = re_for_extracting_search_id return res
Markdown
UTF-8
443
2.625
3
[]
no_license
# Daily-reading-assistant “Daily reading assistant”technical support Books are the ladder of human progress, and opening a book is useful, such as reading useful famous sayings. Daily reading assistant can help you record your reading situation, by setting an alarm clock, remind yourself to read daily, and develop a good habit of reading. For any comments and suggestions, please contact us:“Daily reading assistant” official email:
Java
UTF-8
934
2.5625
3
[]
no_license
package org.usfirst.frc.team7634.robot.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc.team7634.robot.Robot; import org.usfirst.frc.team7634.robot.RobotMap; import org.usfirst.frc.team7634.robot.RobotSettings; public class CubeLowerCommand extends Command { public static double currentPos = 0.0; public CubeLowerCommand() { requires(Robot.cubeLifter); } protected void initialize() { currentPos = Robot.cubeLifter.liftPos; //grabs position from last command } @Override protected void execute() { Robot.cubeLifter.lower(); } @Override protected boolean isFinished() { return false; } @Override protected void end() { Robot.cubeLifter.liftPos = currentPos; //saves position for next command Robot.cubeLifter.stop(); } @Override protected void interrupted() { end(); } }
C++
UTF-8
1,534
3.265625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define dump(x) cerr << #x << " = " << (x) << endl; static const int INF = 999; int N = 4; struct Edge { int from, to, cost; Edge(int f, int t, int c) : from(f), to(t), cost(c) {} }; int main() { vector<Edge> edges; // 0,1,2,3の順に並ぶ制約を表現する辺 edges.push_back(Edge(1, 0, 0)); edges.push_back(Edge(2, 1, 0)); edges.push_back(Edge(3, 2, 0)); // 仲の良い牛の制約を表現する辺 edges.push_back(Edge(0, 2, 10)); edges.push_back(Edge(1, 3, 20)); // 仲が悪い牛の制約を表現する辺 edges.push_back(Edge(2, 1, -3)); // 求めたいのは、d[N-1] - d[0]の最大値 // つまり、0からN-1への最短経路 // このグラフの0からN-1への最短経路を求めると、 // その最短経路が全ての制約を満たすもののうち距離が最大になる。 // 負の辺を含むのでBellman-Fordを使う vector<int> d(N, INF); d[0] = 0; for (int i = 0; i < N; i++) { bool update = false; for (int j = 0; j < edges.size(); j++) { Edge& e = edges[j]; if (d[e.from] != INF && d[e.to] > d[e.from] + e.cost) { d[e.to] = d[e.from] + e.cost; update = true; } } if (!update) break; } for (int i = 0; i < N; i++) cout << d[i] << " "; }
Java
UTF-8
670
3.015625
3
[]
no_license
package jaspreet; import java.util.Scanner; public class int2roman { public static void main(String[] args) { // TODO Auto-generated method stub String ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"}; String tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; String hun[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; String t[] = {"","M","MM","MMM"}; Scanner sc= new Scanner(System.in); //System.in is a standard input stream. System.out.print("Enter first number(less than 4000)- "); int a= sc.nextInt(); System.out.println(t[(a/1000)]+hun[(a%1000)/100]+tens[(a&100)/10]+ones[(a%10)]); } }
Java
UTF-8
747
2.453125
2
[]
no_license
package com.example.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.*; @RestController public class SwaggerAPIController { @RequestMapping( value = "/products", method = RequestMethod.GET) public List<String> getProducts() { List<String> prodList = new ArrayList<>(); prodList.add("Smart"); prodList.add("Bit"); prodList.add("Pixel"); return prodList; } @RequestMapping ( value = "/products", method = RequestMethod.POST) public String createProduct() { return "Product created successfully"; } }
Markdown
UTF-8
5,301
3.0625
3
[ "Apache-2.0" ]
permissive
# Baggage API **Status**: [Feature-freeze](../document-status.md). <details> <summary> Table of Contents </summary> - [Overview](#overview) - [Baggage](#baggage) - [Get baggages](#get-all) - [Get baggage](#get-baggage) - [Set baggage](#set-baggage) - [Remove baggage](#remove-baggage) - [Clear](#clear) - [Baggage Propagation](#baggage-propagation) - [Conflict Resolution](#conflict-resolution) </details> ## Overview The Baggage API consists of: - the `Baggage` - functions to interact with the `Baggage` in a `Context` The functions described here are one way to approach interacting with the Baggage purely via the Context. Depending on language idioms, a language API MAY implement these functions by providing a struct or immutable object that represents the entire Baggage contents. This construct could then be added or removed from the Context with a single operation. For example, the [Clear](#clear) function could be implemented by having the user set an empty Baggage object/struct into the context. The [Get all](#get-all) function could be implemented by returning the Baggage object as a whole from the function call. If an idiom like this is implemented, the Baggage object/struct MUST be immutable, so that the containing Context also remains immutable. The Baggage API MUST be fully functional in the absence of an installed SDK. This is required in order to enable transparent cross-process Baggage propagation. If a Baggage propagator is installed into the API, it will work with or without an installed SDK. ### Baggage `Baggage` is used to annotate telemetry, adding context and information to metrics, traces, and logs. It is an abstract data type represented by a set of name/value pairs describing user-defined properties. Each name in `Baggage` MUST be associated with exactly one value. ### Get all Returns the name/value pairs in the `Baggage`. The order of name/value pairs MUST NOT be significant. Based on the language specification, the returned value can be either an immutable collection or an immutable iterator to the collection of name/value pairs in the `Baggage`. OPTIONAL parameters: `Context` the context containing the `Baggage` from which to get the baggages. ### Get baggage To access the value for a name/value pair by a prior event, the Baggage API MUST provide a function that takes a context and a name as input, and returns a value. Returns the value associated with the given name, or null if the given name is not present. REQUIRED parameters: `Name` the name to return the value for. OPTIONAL parameters: `Context` the context containing the `Baggage` from which to get the baggage entry. ### Set baggage To record the value for a name/value pair, the Baggage API MUST provide a function which takes a context, a name, and a value as input. Returns a new `Context` which contains a `Baggage` with the new value. REQUIRED parameters: `Name` The name for which to set the value, of type string. `Value` The value to set, of type string. OPTIONAL parameters: `Metadata` Optional metadata associated with the name-value pair. This should be an opaque wrapper for a string with no semantic meaning. Left opaque to allow for future functionality. `Context` The context containing the `Baggage` in which to set the baggage entry. ### Remove baggage To delete a name/value pair, the Baggage API MUST provide a function which takes a context and a name as input. Returns a new `Context` which no longer contains the selected name. REQUIRED parameters: `Name` the name to remove. OPTIONAL parameters: `Context` the context containing the `Baggage` from which to remove the baggage entry. ### Clear To avoid sending any name/value pairs to an untrusted process, the Baggage API MUST provide a function to remove all baggage entries from a context. Returns a new `Context` with no `Baggage`. OPTIONAL parameters: `Context` the context containing the `Baggage` from which to remove all baggage entries. ## Baggage Propagation `Baggage` MAY be propagated across process boundaries or across any arbitrary boundaries (process, $OTHER_BOUNDARY1, $OTHER_BOUNDARY2, etc) for various reasons. The API layer or an extension package MUST include the following `Propagator`s: * A `TextMapPropagator` implementing the [W3C Baggage Specification](https://w3c.github.io/baggage). See [Propagators Distribution](../context/api-propagators.md#propagators-distribution) for how propagators are to be distributed. Note: The W3C baggage specification does not currently assign semantic meaning to the optional metadata. On `extract`, the propagator should store all metadata as a single metadata instance per entry. On `inject`, the propagator should append the metadata per the W3C specification format. Notes: If the propagator is unable to parse the `baggage` header, `extract` MUST return a Context with no baggage entries in it. If the `baggage` header is present, but contains no entries, `extract` MUST return a Context with no baggage entries in it. ## Conflict Resolution If a new name/value pair is added and its name is the same as an existing name, than the new pair MUST take precedence. The value is replaced with the added value (regardless if it is locally generated or received from a remote peer).
C
UTF-8
763
2.9375
3
[]
no_license
#include "test_utils/test_utils.h" #include "../include/WAM.h" #define TEST "WAM" void TEST_WAM_1() { matrix* mat; vector* v; vector* tmp; int n = 7; int m = 9; int i, j; mat = matrix_init(n, 0); v = vector_init_zero(n); for (i=0; i<n; i++) { v->values[i] = i; } for (i=0; i<m; i++) { tmp = vector_copy(v); matrix_add_row(mat, v); v = tmp; assertf(mat->rows[i] != NULL, "new row is NULL"); } mat = WAM(mat); for (i=0; i<m; i++) { for (j=0; j<n; j++) { if (i == j) { assertf(mat->rows[i]->values[j] == 0, "wrong value on diagonal"); } else { assertf(mat->rows[i]->values[j] == 1, "wrong value"); } } } vector_free(tmp); matrix_free(mat); } int main() { start_test(TEST); TEST_WAM_1(); end_test(TEST); }
C++
UTF-8
925
3.21875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS /*The define above is very important. Without it,strcat and strcpy will crash. */ #include<iostream> #include<vector> #include<string> #include<initializer_list>// new operations! #include <system_error> // std::error_code, std::generic_category // std::error_condition #include<cstdlib> using std::cin; using std::cout; using std::endl; using std::vector; using std::begin; using std::end; using std::string; using std::initializer_list; //void print(const string&) //{ //return(string.empty()); //} void foodBar(int ival) { bool read = false;//new scope: hides the outer declaration of read //string s = read(); } void print(double t) { cout <<t<<endl; } void print(int t) { auto t1 = static_cast<int>(t); cout << t1; } int main() { double v1 = 3.14; void print(int);//new scope, hides the outer declration print(v1);//the result is 3. }
Java
UTF-8
3,036
2.3125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.socialNetwork.socialNetwork.Entity; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.socialNetwork.socialNetwork.Jackson.Serializer.TopicSerializer; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** * * @author user */ @JsonSerialize(using = TopicSerializer.class) @Validated @Table(name = "topic") @Entity(name = "topic") public class Topic implements Serializable{ private Long id; @NotBlank private String text; @NotNull private Profile profile; @NotNull private List<Comment> comments=new ArrayList<>(); public Topic() { } public Topic(String text) { this.text = text; } public Topic(Long id, String text, Profile profile) { this.id = id; this.text = text; this.profile = profile; } public void addComment(Comment comment){ comments.add(comment); comment.setTopic(this); } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="profile_id") public Profile getProfile() { return profile; } /** * @param profile the profile to set */ public void setProfile(Profile profile) { this.profile = profile; } @org.springframework.data.annotation.Id @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "text") public String getText() { return text; } public void setText(String text) { this.text = text; } @OneToMany(mappedBy = "topic", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.LAZY) public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public boolean contain(Comment currentComment){ for (Comment comment:getComments()) { if (comment.getId()==currentComment.getId()) return true; } return false; } }
Java
UTF-8
709
3.625
4
[]
no_license
package swtich_case; import java.util.Scanner; public class Test02 { public static void main(String[] args) { // 사용자에게 월을 정수로 입력받아서 해당하는 월의 날짜수를 화면에 출력 Scanner sc = new Scanner(System.in); System.out.println("월을 입력하세요."); int month = sc.nextInt(); sc.close(); //계산 : 만약에 2월이라면 30일까지 있습니다. int day; switch (month) { case 2: day = 28; break; case 1: case 4: case 6: case 9: case 11: day = 30; break; default : day = 31; break; } System.out.println(month+"월은 "+day+"일까지 있습니다."); } }
JavaScript
UTF-8
1,313
2.515625
3
[]
no_license
import React from 'react'; import get from 'lodash.get'; const StatTable = ({ statType, ranking, selectedStat, selectedAttribute }) => { const fighterStatPath = statType === 'official' ? `stats.official.${selectedStat}`: `stats.unofficial.${statType}.${selectedStat}`; return( <table className='ranking-table'> <thead> <tr> <th/> <th>Fighter</th> <th>Series</th> <th>{selectedAttribute}</th> </tr> </thead> <tbody> {ranking.map(fighter => { const fighterStat = get(fighter,fighterStatPath, 'Ah shit'); return( <tr> <td> <img className='ranking-item-picture' src={fighter.picture} alt={fighter.name} height={50} width={50} /> </td> <td><span className='ranking-item-name'>{fighter.name}</span></td> <td><img className='ranking-item-series' src={fighter.series.icon} alt={fighter.series.name} height={50} width={50}/></td> <td><span className='ranking-item-selected-stat'>{fighterStat}</span></td> </tr> ) })} </tbody> </table> ) }; export default StatTable;
PHP
UTF-8
969
2.625
3
[]
no_license
<?php /***************************************************************************************************** get our passed data. data can either be passed in xml via the apidata= parameter, or as a request variable. To pass arrays of data, either use field[] notation for request vars, or use the variable name twice in xml (i.e: <data><object_id>1</object_id><object_id>2</object_id></data>) All xml data must be encompassed in a root tag, like "<data>" in the above example ******************************************************************************************************/ require_once("apilib/apirequest.php"); //make sure magic quotes is disabled //try to pull from apidata. If nothing, default to request (for socket connections) if ($_REQUEST["apidata"]) $apidata = $_REQUEST["apidata"]; //init our class and process the data $ap = new APIREQUEST($apidata); //make available for other classes $GLOBALS["APIREQUEST"] = $ap; $ap->process();
Markdown
UTF-8
3,043
2.9375
3
[]
no_license
--- layout: page title: Artwork permalink: /artwork/ banner: /images/post-assets/oil-blur.jpg --- 1. [Microcosm](#microcosm) 2. [The Illustrated Man](#the-illustrated-man) 3. [Glitch Art](#glitch-art) ## Microcosm Tiny worlds surround us just out sight. I have always been fascinated with the small and unseen. Advancement in microscopy has removed the veil between the micro world and the visible, but the mystery of these tiny world remains. Using experimental photography, I have embraced the imagery of the small. <figure class="multiple"><a href="/images/artwork/microcosm-1.jpg" rel="lightbox"><img src="/images/artwork/microcosm-1.jpg"></a><a href="/images/artwork/microcosm-2.jpg" rel="lightbox"><img src="/images/artwork/microcosm-2.jpg"></a><a href="/images/artwork/microcosm-3.jpg" rel="lightbox"><img src="/images/artwork/microcosm-3.jpg"></a></figure> <figure class="multiple"><a href="/images/artwork/microcosm-4.jpg" rel="lightbox"><img src="/images/artwork/microcosm-4.jpg"></a><a href="/images/artwork/microcosm-5.jpg" rel="lightbox"><img src="/images/artwork/microcosm-5.jpg"></a><a href="/images/artwork/microcosm-6.jpg" rel="lightbox"><img src="/images/artwork/microcosm-6.jpg"></a><a href="/images/artwork/microcosm-7.jpg" rel="lightbox"><img src="/images/artwork/microcosm-7.jpg"></a></figure> <div class="spacer"></div> ## The Illustrated Man Ray Bradbury's Illustrated Man is one of my favorite sci-fi works. I really enjoy the bleak outlook on mankind contrasted with the raw beauty of nature. While these images are based on the short stories, they are not necessarily illustrations. They are my response to Bradbury. <figure class="multiple"><a href="/images/artwork/illustrated-1.jpg" rel="lightbox"><img src="/images/artwork/illustrated-1.jpg"></a><a href="/images/artwork/illustrated-2.jpg" rel="lightbox"><img src="/images/artwork/illustrated-2.jpg"></a><a href="/images/artwork/illustrated-3.jpg" rel="lightbox"><img src="/images/artwork/illustrated-3.jpg"></a></figure> <figure class="multiple"><a href="/images/artwork/illustrated-4.jpg" rel="lightbox"><img src="/images/artwork/illustrated-4.jpg"></a><a href="/images/artwork/illustrated-5.jpg" rel="lightbox"><img src="/images/artwork/illustrated-5.jpg"></a></figure> <div class="spacer"></div> ## Glitch Art These are a few of my experiments with glitches, pixelation, and digital distruction. <figure class="multiple"><a href="/images/artwork/glitch-1.jpg" rel="lightbox"><img src="/images/artwork/glitch-1.jpg"></a><a href="/images/artwork/glitch-2.jpg" rel="lightbox"><img src="/images/artwork/glitch-2.jpg"></a><a href="/images/artwork/glitch-3.jpg" rel="lightbox"><img src="/images/artwork/glitch-3.jpg"></a></figure> <figure class="multiple"><a href="/images/artwork/glitch-4.jpg" rel="lightbox"><img src="/images/artwork/glitch-4.jpg"></a><a href="/images/artwork/glitch-5.jpg" rel="lightbox"><img src="/images/artwork/glitch-5.jpg"></a><a href="/images/artwork/glitch-6.jpg" rel="lightbox"><img src="/images/artwork/glitch-6.jpg"></a></figure>
Java
UTF-8
1,885
1.65625
2
[]
no_license
package com.techsoft.client.service.struct; import java.util.List; import com.github.pagehelper.PageInfo; import com.techsoft.common.BaseClientService; import com.techsoft.common.BusinessException; import com.techsoft.common.SQLException; import com.techsoft.common.CommonParam; import com.techsoft.common.persistence.ResultMessage; import com.techsoft.entity.common.StructProdlineEquipFixture; import com.techsoft.entity.struct.StructProdlineEquipFixtureVo; import com.techsoft.entity.struct.StructProdlineEquipFixtureParamVo; public interface ClientStructProdlineEquipFixtureService extends BaseClientService<StructProdlineEquipFixture> { public StructProdlineEquipFixtureVo getVoByID(Long id, CommonParam commonParam) throws BusinessException, SQLException; public List<StructProdlineEquipFixtureVo> selectListVoByParamVo(StructProdlineEquipFixtureParamVo structProdlineEquipFixture, CommonParam commonParam) throws BusinessException, SQLException; public PageInfo<StructProdlineEquipFixtureVo> selectPageVoByParamVo(StructProdlineEquipFixtureParamVo structProdlineEquipFixture, CommonParam commonParam, int pageNo, int pageSize) throws BusinessException, SQLException; public StructProdlineEquipFixtureVo getExtendVoByID(Long id, CommonParam commonParam) throws BusinessException, SQLException; public List<StructProdlineEquipFixtureVo> selectListExtendVoByParamVo(StructProdlineEquipFixtureParamVo structProdlineEquipFixture, CommonParam commonParam) throws BusinessException, SQLException; public PageInfo<StructProdlineEquipFixtureVo> selectPageExtendVoByParamVo(StructProdlineEquipFixtureParamVo structProdlineEquipFixture, CommonParam commonParam, int pageNo, int pageSize) throws BusinessException, SQLException; public ResultMessage saveOrUpdate(StructProdlineEquipFixtureParamVo structProdlineEquipFixtureParamVo, CommonParam commonParam); }
Java
UTF-8
2,222
3.546875
4
[]
no_license
package hr.fer.zemris.java.hw17.jvdraw.geometry; import java.awt.Color; import java.awt.Point; import java.util.Objects; import hr.fer.zemris.java.hw17.jvdraw.geometry.editor.GeometricalObjectEditor; import hr.fer.zemris.java.hw17.jvdraw.geometry.editor.LineEditor; import hr.fer.zemris.java.hw17.jvdraw.geometry.visitor.GeometricalObjectVisitor; /** * Class models an geometric object representing a line with a start and end * point and with a drawing color. * * @author Frano Rajič */ public class Line extends GeometricalObject { /** * Where is the start of the line */ private Point startPoint; /** * Where is the end of the line */ private Point endPoint; /** * The color of the drawn line */ private Color color; /** * Create a line with given start and end points * * @param startPoint the start point * @param endPoint the end point * @param color the color of the line * @throws NullPointerException thrown if any reference is null */ public Line(Point startPoint, Point endPoint, Color color) { this.startPoint = Objects.requireNonNull(startPoint); this.endPoint = Objects.requireNonNull(endPoint); this.color = Objects.requireNonNull(color); } /** * @return the startPoint */ public Point getStartPoint() { return startPoint; } /** * @param startPoint the startPoint to set */ public void setStartPoint(Point startPoint) { fireAll(); this.startPoint = startPoint; } /** * @return the endPoint */ public Point getEndPoint() { return endPoint; } /** * @param endPoint the endPoint to set */ public void setEndPoint(Point endPoint) { fireAll(); this.endPoint = endPoint; } @Override public GeometricalObjectEditor createGeometricalObjectEditor() { return new LineEditor(this); } @Override public void accept(GeometricalObjectVisitor v) { v.visit(this); } @Override public String toString() { return String.format("Line (%d,%d)-(%d,%d)", startPoint.x, startPoint.y, endPoint.x, endPoint.y); } /** * @return the color */ public Color getColor() { return color; } /** * @param color the color to set */ public void setColor(Color color) { fireAll(); this.color = color; } }
Python
UTF-8
1,927
3.171875
3
[]
no_license
x = input().split() a, b, c, d = x a = int(a) // hora inicial b = int(b) // minuto inicial c = int(c) // hora final d = int(d) // minuto final if c < 12 and a < 12 and d != b and c - a >= 2: horas = c - a if d < b: minutos = (d - b) + 60 print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') else: minutos = d - b print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') if c < 12 and a > 12 and c - a >= 2: c = c + 24 horas = c - a if d < b: minutos = (d - b) + 60 print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') if d == b or d > b: minutos = d - b print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') if a < 12 and c > 12: horas = c - a if d < b: minutos = (d - b) + 60 print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') if d == b or d > b: minutos = d - b print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') if c - a <= 1 and d < b: horas = 0 minutos = (d - b) + 60 print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') if a == b == c == d: horas = 0 minutos = 0 print(f'O JOGO DUROU {horas} HORA(S) E {minutos} MINUTO(S)') '''Outra forma x = input().split() hi, mi, hf, mf = x hi = int(x[0]) mi = int(x[1]) hf = int(x[2]) mf = int(x[3]) if hi < hf: h = hf - hi if mi < mf: m = mf - mi if mi > mf: h = h - 1 m = (60 - mi) + mf if mi == mf: m = 0 if hi > hf: h = (24 - hi) + hf if mi < mf: m = mf - mi if mi > mf: h = h - 1 m = (60 - mi) + mf if mi == mf: m = 0 if hi == hf: if mi < mf: m = mf - mi h = 0 if mi > mf: m = (60 - mi) + mf h = 23 if mi == mf: h = 24 m = 0 print('O JOGO DUROU {} HORA(S) E {} MINUTO(S)'.format(h, m)) '''
SQL
UTF-8
1,438
3.8125
4
[]
no_license
1) Customers of particular city select c_name,date,amount from (customer as c join customer_transaction as ct ON (c.cid=ct.cid) ) where c_city='udaipur'; 2)customers who buy paricular product select c_name from( (customer as c join billing as b ON(c.cid=b.cid)) as r0 join product_info as p1 ON(r0.bill_id=p1.bill_id))as r1 join product p2 ON(r1.pid=p2.pid) where name=' '; //3) whose bill is remaining select c_name from customer where cid IN(select distinct cid from customer_transaction Except select distinct cid from customer_transaction where remaining=0); 4)bill paid at first time select distinct c_name,bill_id,cphone_no from billing as b natural join customer as c where (payable-(cash+silver_return+gold_return))=0; 5)gold sold at particular date select sum(p2.weight) as gold_sold , sum(price_total) as price_of_gold from (product_info as p1 join product as p2 ON(p1.pid=p2.pid) natural join billing) where date='06/12/2016' and material='gold'; 6)total stock of gold select sum(weight)as Remaining_gold_in_shop from product where material='gold' Except (select sum(p2.weight) as gold_sold from (product_info as p1 join product as p2 ON(p1.pid=p2.pid) natural join billing) where material='gold'); 8) net profit of year select sum(net_profit) from billing where extract(year from date)=2016; 9) schemes of particular customer select count(sid) from customer_scheme where cid=21 group by sid; 10)
Java
UTF-8
4,547
2.640625
3
[]
no_license
package org.blep.poc.hcq; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.hibernate.transform.Transformers; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import javax.annotation.Nullable; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.Query; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.util.List; import static junit.framework.Assert.assertEquals; /** * @author blep * Date: 12/03/12 * Time: 07:10 */ public class HotelTest { @Rule public JunitTimer junitTimer = new JunitTimer(); private EntityManager em = Persistence.createEntityManagerFactory("HotelsPU").createEntityManager(); @Before public void setUp() throws Exception { em.getTransaction().begin(); } @After public void tearDown() throws Exception { em.getTransaction().rollback(); } /** * Basic test just for checking * @throws Exception */ @Test public void testName() throws Exception { List<Hotel> hotels = em.createQuery("select h from Hotel h", Hotel.class).getResultList(); assertEquals(100, hotels.size()); for (Hotel hotel : hotels) { // System.out.println("hotel.getName() = " + hotel.getName()); hotel.getName(); } } /** * Standard select with a constructor JPQL query ==> n+1 statements * @throws Exception */ @Test public void testConstructor100SqlWithJpql() throws Exception { TypedQuery<HotelDto> query = em.createQuery("select new org.blep.poc.hcq.HotelDto(h) from Hotel h", HotelDto.class); List<HotelDto> resultList = query.getResultList(); for (HotelDto dto : resultList) { dto.getName(); } } /** * Criteria select query with constructor ==> useless as Hibernate translates Criteria into JPQL ==> n+1 statements * @throws Exception */ @Test public void testConstructorCriteria100Sql() throws Exception { CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<HotelDto> cq = criteriaBuilder.createQuery(HotelDto.class); Root<Hotel> from = cq.from(Hotel.class); cq.select(criteriaBuilder.construct(HotelDto.class, from)); TypedQuery<HotelDto> query = em.createQuery(cq); for (HotelDto dto : (List<HotelDto>) query.getResultList()) { dto.getName(); } } /** * This is a workaround but it implies to reveal Hibernate API, so the code is not "only JPA" any longer... * * @throws Exception */ @Test public void testUnwrapHibernateQuery() throws Exception { long delay = System.currentTimeMillis(); @SuppressWarnings("JpaQlInspection") Query query = em.createQuery("select h as hotel from Hotel h"); org.hibernate.Query unwrapped = query.unwrap(org.hibernate.Query.class); unwrapped.setResultTransformer(Transformers.aliasToBean(HotelDto.class)); for (HotelDto dto : (List<HotelDto>) query.getResultList()) { //System.out.println("dto.getState() = " + dto.getState()); dto.getName(); } } /** * Using a collection implementation dedicated to the Dto usage. * * @throws Exception */ @Test public void testCollectionDelegate() throws Exception { HotelDtoCollection hotels = new HotelDtoCollection(em.createQuery("select h from Hotel h", Hotel.class).getResultList()); assertEquals(100, hotels.size()); for (HotelDto hotel : hotels) { // System.out.println("hotel.getName() = " + hotel.getName()); hotel.getName(); } } /** * Using Guava collection to translate the result list to another list. * @throws Exception */ @Test public void testGuavaStyle() throws Exception { List<Hotel> resultList = em.createQuery("select h from Hotel h", Hotel.class).getResultList(); List<HotelDto> dtos = Lists.transform(resultList, new Function<Hotel, HotelDto>() { public HotelDto apply(@Nullable Hotel input) { return new HotelDto(input); } }); for (HotelDto dto : dtos) { dto.getName(); } } }
SQL
UTF-8
1,782
3.671875
4
[]
no_license
/**************************************************** * Procudure to write the contents of the * new_transaction table into a delimited * text file. * Authors: Jocelyn Wegen & Matthew Lee * Date: December 3, 2019 ****************************************************/ CREATE OR REPLACE PROCEDURE WRITE_FILE_SP (p_directory_alias IN VARCHAR2, p_file IN VARCHAR2) AS --cursor to go through new_transaction table CURSOR cur_new_tran IS SELECT * FROM new_transactions; --utl_file variable file_handler UTL_FILE.FILE_TYPE; BEGIN --create and open the file to write to file_handler := UTL_FILE.FOPEN( p_directory_alias, p_file, 'w' ); --loop through the new_transaction table FOR rec_new_tran IN cur_new_tran LOOP --write all the columns into file, delimited with a comma UTL_FILE.PUT(file_handler, rec_new_tran.transaction_no); UTL_FILE.PUT(file_handler, ','); UTL_FILE.PUT(file_handler, rec_new_tran.transaction_date); UTL_FILE.PUT(file_handler, ','); UTL_FILE.PUT(file_handler, rec_new_tran.description); UTL_FILE.PUT(file_handler, ','); UTL_FILE.PUT(file_handler, rec_new_tran.account_no); UTL_FILE.PUT(file_handler, ','); UTL_FILE.PUT(file_handler, rec_new_tran.transaction_type); UTL_FILE.PUT(file_handler, ','); UTL_FILE.PUT(file_handler, rec_new_tran.transaction_amount); UTL_FILE.PUT_LINE(file_handler, ''); END LOOP; --close the file UTL_FILE.FCLOSE(file_handler); EXCEPTION WHEN OTHERS THEN --just in case an error occurs. DBMS_OUTPUT.PUT_LINE('Error Code: ' || SQLCODE); DBMS_OUTPUT.PUT_LINE('Error Message: ' || SQLERRM); END;
Python
UTF-8
2,766
2.703125
3
[]
no_license
from bots.black_bot import black_bot from bots.telegram_bot import telegram_bot import config from colors import * def update_grid(): # attempt to retrieve order history from matcher try: history = black_bot.wallet.getOrderHistory(black_bot.asset_pair) except: history = [] if history: # loop through all grid levels # first all ask levels from the lowest ask to the highest -> range(grid.index("") + 1, len(grid)) # then all bid levels from the highest to the lowest -> range(grid.index("") - 1, -1, -1) for n in list(range(0, black_bot.last_level)) + list(range(black_bot.last_level + 1, len(black_bot.grid))): # find the order with id == grid9*-+[n] in the history list order = [item for item in history if item['id'] == black_bot.grid[n]] status = order[0].get("status") if order else "" if status == "Filled": black_bot.wallet.deleteOrderHistory(black_bot.asset_pair) black_bot.grid[n] = "" black_bot.last_level = n filled_price = float(order[0].get("price")) / 10 ** (black_bot.asset_pair.asset2.decimals + ( black_bot.asset_pair.asset2.decimals - black_bot.asset_pair.asset1.decimals)) filled_type = order[0].get("type") black_bot.log("## [%03d] %s%-4s Filled %18.*f%s" % ( n, COLOR_BLUE, filled_type.upper(), black_bot.asset_pair.asset2.decimals, filled_price, COLOR_RESET)) telegram_bot.send_message( config.USER_ID, f'{filled_type.upper()} filled *{filled_price}*', parse_mode='Markdown', ) if filled_type == "buy": black_bot.sell(n + 1) telegram_bot.send_message( config.USER_ID, f'SELL order *{black_bot.get_level_price(n + 1)}*', parse_mode='Markdown', ) elif filled_type == "sell": black_bot.buy(n - 1) telegram_bot.send_message( config.USER_ID, f'BUY order *{black_bot.get_level_price(n - 1)}*', parse_mode='Markdown', ) # attempt to place again orders for empty grid levels or cancelled orders elif (status == "" or status == "Cancelled") and black_bot.grid[n] != "-": black_bot.grid[n] = "" if n > black_bot.last_level: black_bot.sell(n) elif n < black_bot.last_level: black_bot.buy(n)
Java
UTF-8
1,560
3.046875
3
[]
no_license
package com.atguigu.JUC; import java.util.concurrent.*; public class MyThreadPoolDemo_13 { public static void main(String[] args) { //线程池线程数配置 //cpu密集型 最大线程数 比cpu线程多1到2 io密集型 cpu线程数除阻塞系数 System.out.println(Runtime.getRuntime().availableProcessors()); ExecutorService threadPoll = new ThreadPoolExecutor(2,5,2L,TimeUnit.SECONDS, new LinkedBlockingQueue<>(3),Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy()); try{ for(int i = 1;i <= 10;i++){ threadPoll.execute(()->{ System.out.println(Thread.currentThread().getName()+"\t办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPoll.shutdown(); } } public static void initPool(){ //ExecutorService threadPool = Executors.newFixedThreadPool(5);//指定线程池容量 //ExecutorService threadPool = Executors.newSingleThreadExecutor();//线程池只有一个线程 ExecutorService threadPool = Executors.newCachedThreadPool();//可伸缩可扩容 try{ for(int i = 1;i <= 10;i++){ threadPool.execute(()->{ System.out.println(Thread.currentThread().getName()+"\t办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
Java
UTF-8
114
1.539063
2
[]
no_license
package com.kasun.kasun_demo_crud.services; public interface CountryServices { String findAllCountries(); }
C++
UTF-8
2,760
3.5625
4
[]
no_license
#ifndef LIB_OPTIONAL_HEADER #define LIB_OPTIONAL_HEADER /** \file * \brief Header for the \ref lib::sparse_optional "sparse_optional" template class */ namespace lib { /** \brief Similar to C++17's std::optional, but stores the data in * dynamic memory. * * sparse_optional is useful to save memory if it is expected * that the object is rarely set and the object's size is bigger than * a simple pointer. */ template<typename T> class sparse_optional final { public: sparse_optional(); explicit sparse_optional(T const& v); /// Takes ownership of pointer. explicit sparse_optional(T * v); sparse_optional(sparse_optional<T> const& v); sparse_optional(sparse_optional<T> && v) noexcept; ~sparse_optional(); void clear(); explicit operator bool() const { return v_ != 0; }; T& operator*() { return *v_; } T const& operator*() const { return *v_; } T* operator->() { return v_; } T const* operator->() const { return v_; } bool operator==(sparse_optional<T> const& cmp) const; inline bool operator!=(sparse_optional<T> const& cmp) const { return !(*this == cmp); } bool operator<(sparse_optional<T> const& cmp) const; sparse_optional<T>& operator=(sparse_optional<T> const& v); sparse_optional<T>& operator=(sparse_optional<T> && v) noexcept; private: T* v_; }; template<typename T> sparse_optional<T>::sparse_optional() : v_() { } template<typename T> sparse_optional<T>::sparse_optional(T const& v) : v_(new T(v)) { } template<typename T> sparse_optional<T>::sparse_optional(T * v) : v_(v) { } template<typename T> sparse_optional<T>::sparse_optional(sparse_optional<T> const& v) { if (v) { v_ = new T(*v); } else { v_ = 0; } } template<typename T> sparse_optional<T>::sparse_optional(sparse_optional<T> && v) noexcept { v_ = v.v_; v.v_ = 0; } template<typename T> sparse_optional<T>::~sparse_optional() { delete v_; } template<typename T> void sparse_optional<T>::clear() { delete v_; v_ = 0; } template<typename T> sparse_optional<T>& sparse_optional<T>::operator=(sparse_optional<T> const& v) { if (this != &v) { delete v_; if (v.v_) { v_ = new T(*v.v_); } else { v_ = 0; } } return *this; } template<typename T> sparse_optional<T>& sparse_optional<T>::operator=(sparse_optional<T> && v) noexcept { if (this != &v) { delete v_; v_ = v.v_; v.v_ = 0; } return *this; } template<typename T> bool sparse_optional<T>::operator==(sparse_optional<T> const& cmp) const { if (!v_ && !cmp.v_) { return true; } if (!v_ || !cmp.v_) { return false; } return *v_ == *cmp.v_; } template<typename T> bool sparse_optional<T>::operator<(sparse_optional<T> const& cmp) const { if (!v_ || !cmp.v_) { return cmp.v_ != 0; } return *v_ < *cmp.v_; } } #endif
Python
UTF-8
12,850
2.6875
3
[ "Apache-2.0" ]
permissive
# Copyright (c) 2020 Horizon Robotics and ALF Contributors. 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. import torch import torch.nn as nn from torch.nn.utils import spectral_norm import alf from alf.layers import FC from alf.networks import Network from alf.tensor_specs import TensorSpec from alf.utils.math_ops import identity @alf.configurable class SimpleFC(nn.Linear): """ A simple FC layer that record its output before activation. It is for used in the ReluMLP to enable explicit computation of diagonals of input-output Jacobian. """ def __init__(self, input_size, output_size, activation=identity): """ Initialize a SimpleFC layer. Args: input_size (int): input dimension. output_size (int): output dimension. activation (nn.functional): activation used for this layer. Default is math_ops.identity. """ super().__init__(input_size, output_size) self._activation = activation self._hidden_neurons = None @property def hidden_neurons(self): return self._hidden_neurons def forward(self, inputs): self._hidden_neurons = super().forward(inputs) return self._activation(self._hidden_neurons) @alf.configurable class ReluMLP(Network): """ A MLP with relu activations. Diagonals of input-output Jacobian can be computed directly without calling autograd. """ def __init__(self, input_tensor_spec, output_size=None, hidden_layers=(64, 64), name="ReluMLP"): """Create a ReluMLP. Args: input_tensor_spec (TensorSpec): output_size (int): output dimension. hidden_layers (tuple): size of hidden layers. name (str): """ assert len(input_tensor_spec.shape) == 1, \ ("The input shape {} should be a 1-d vector!".format( input_tensor_spec.shape )) super().__init__(input_tensor_spec, name=name) self._input_size = input_tensor_spec.shape[0] self._output_size = output_size if self._output_size is None: self._output_size = self._input_size self._hidden_layers = hidden_layers self._fc_layers = nn.ModuleList() input_size = self._input_size for size in hidden_layers: fc = SimpleFC(input_size, size, activation=torch.relu_) self._fc_layers.append(fc) input_size = size last_fc = SimpleFC(input_size, self._output_size, activation=identity) self._fc_layers.append(last_fc) def __getitem__(self, i): """Get i-th (zero-based) FC layer""" return self._fc_layers[i] def forward(self, inputs, state=(), requires_jac=False, requires_jac_diag=False): """ Args: inputs (torch.Tensor) state: not used requires_jac (bool): whether outputs input-output Jacobian. requires_jac_diag (bool): whetheer outputs diagonals of Jacobian. """ ndim = inputs.ndim if ndim == 1: inputs = inputs.unsqueeze(0) assert inputs.ndim == 2 and inputs.shape[-1] == self._input_size, \ ("inputs should has shape (B, {})!".format(self._input_size)) z = inputs for fc in self._fc_layers: z = fc(z) if ndim == 1: z = z.squeeze(0) if requires_jac: z = (z, self._compute_jac()) elif requires_jac_diag: z = (z, self._compute_jac_diag()) return z, state def compute_jac(self, inputs, output_partial_idx=None): """Compute the input-output Jacobian, support partial output. Args: inputs (Tensor): size (self._input_size) or (B, self._input_size) output_partial_idx (list): list of output indices for taking partial output-input Jacobian. Default is ``None``, where standard full output-input Jacobian will be used. Returns: Jacobian (Tensor): shape (out_size, in_size) or (B, out_size, in_size), where ``out_size`` is self._output_size if ``output_partial_idx`` is None, ``len(output_partial_idx)`` otherwise. """ assert inputs.ndim <= 2 and inputs.shape[-1] == self._input_size, \ ("inputs should has shape {}!".format(self._input_size)) self.forward(inputs) J = self._compute_jac(output_partial_idx=output_partial_idx) if inputs.ndim == 1: J = J.squeeze(0) return J def _compute_jac(self, output_partial_idx=None): """Compute the input-output Jacobian. """ if output_partial_idx is None: output_partial_idx = torch.arange(self._output_size) if len(self._fc_layers) > 1: mask = (self._fc_layers[-2].hidden_neurons > 0).float() J = torch.einsum('ia,ba,aj->bij', self._fc_layers[-1].weight[output_partial_idx, :], mask, self._fc_layers[-2].weight) for fc in reversed(self._fc_layers[0:-2]): mask = (fc.hidden_neurons > 0).float() J = torch.einsum('bia,ba,aj->bij', J, mask, fc.weight) else: mask = torch.ones_like(self._fc_layers[-1].hidden_neurons) mask = mask[:, output_partial_idx] J = torch.einsum('ji, bj->bji', self._fc_layers[-1].weight[output_partial_idx, :], mask) return J # [B, n_out, n_in] def compute_jac_diag(self, inputs): """Compute diagonals of the input-output Jacobian. """ assert inputs.ndim <= 2 and inputs.shape[-1] == self._input_size, \ ("inputs should has shape {}!".format(self._input_size)) self.forward(inputs) J_diag = self._compute_jac_diag() if inputs.ndim == 1: J_diag = J_diag.squeeze(0) return J_diag def _compute_jac_diag(self): """Compute diagonals of the input-output Jacobian. """ mask = (self._fc_layers[-2].hidden_neurons > 0).float() if len(self._hidden_layers) == 1: J = torch.einsum('ia,ba,ai->bi', self._fc_layers[-1].weight, mask, self._fc_layers[0].weight) # [B, n] else: J = torch.einsum('ia,ba,aj->bij', self._fc_layers[-1].weight, mask, self._fc_layers[-2].weight) for fc in reversed(self._fc_layers[1:-2]): mask = (fc.hidden_neurons > 0).float() J = torch.einsum('bia,ba,aj->bij', J, mask, fc.weight) mask = (self._fc_layers[0].hidden_neurons > 0).float() J = torch.einsum('bia,ba,ai->bi', J, mask, self._fc_layers[0].weight) # [B, n] return J def compute_vjp(self, inputs, vec, output_partial_idx=None): """Compute vector-Jacobian product, support partial output-input Jacobian. Args: inputs (Tensor): size (self._input_size) or (B, self._input_size) vec (Tensor): the vector for which the vector-Jacobian product is computed. Must be of size (self._output_size) or (B, self._output_size). output_partial_idx (list): list of output indices for taking partial output-input Jacobian. Default is ``None``, where standard full output-input Jacobian will be used. Returns: vjp (Tensor): shape (self._input_size) or (B, self._input_size). outputs (Tensor): outputs of the ReluMLP """ ndim = inputs.ndim assert vec.ndim == ndim, ("ndim of inputs and vec must be consistent!") if ndim > 1: assert ndim == 2, ("inputs must be a vector or matrix!") assert inputs.shape[0] == vec.shape[0], ( "batch size of inputs and vec must agree!") assert inputs.shape[-1] == self._input_size, ( "inputs should has shape {}!".format(self._input_size)) if output_partial_idx is None: assert vec.shape[-1] == self._output_size, ( "vec should has shape {}!".format(self._output_size)) else: assert vec.shape[-1] == len(output_partial_idx) or \ vec.shape[-1] == self._output_size, ( "vec should has shape {} or {}!".format( len(output_partial_idx), self._output_size)) outputs, _ = self.forward(inputs) vjp = self._compute_vjp(vec, output_partial_idx=output_partial_idx) return vjp, outputs def _compute_vjp(self, vec, output_partial_idx=None): """Compute vector-(partial) Jacobian product. """ ndim = vec.ndim if ndim == 1: vec = vec.unsqueeze(0) if output_partial_idx is None: output_partial_idx = torch.arange(self._output_size) if vec.shape[-1] == self._output_size: vec = vec[:, output_partial_idx] J = torch.matmul(vec, self._fc_layers[-1].weight[output_partial_idx, :]) for fc in reversed(self._fc_layers[0:-1]): mask = (fc.hidden_neurons > 0).float() J = torch.matmul(J * mask, fc.weight) if ndim == 1: J = J.squeeze(0) return J # [B, n_in] or [n_in] def compute_jvp(self, inputs, vec, output_partial_idx=None): """Compute Jacobian-vector product, support partial output-input Jacobian. Args: inputs (Tensor): size (self._input_size) or (B, self._input_size) vec (Tensor): the vector for which the Jacobian-vector product is computed. Must be of size (self._input_size) or (B, self._input_size). output_partial_idx (list): list of output indices for taking partial output-input Jacobian. Default is ``None``, where standard full output-input Jacobian will be used. Returns: jvp (Tensor): shape (out_size) or (B, out_size), where ``out_size`` is self._output_size if ``output_partial_idx`` is None, ``len(output_partial_idx)`` otherwise. outputs (Tensor): outputs of the ReluMLP """ ndim = inputs.ndim assert vec.ndim == ndim, \ ("ndim of inputs and vec must be consistent!") if ndim > 1: assert ndim == 2, \ ("inputs must be a vector or matrix!") assert inputs.shape[0] == vec.shape[0], \ ("batch size of inputs and vec must agree!") assert inputs.shape[-1] == self._input_size, \ ("inputs should has shape {}!".format(self._input_size)) assert vec.shape[-1] == self._input_size, \ ("vec should has shape {}!".format(self._input_size)) outputs, _ = self.forward(inputs) jvp = self._compute_jvp(vec, output_partial_idx=output_partial_idx) return jvp, outputs def _compute_jvp(self, vec, output_partial_idx=None): """Compute (partial) Jacobian-vector product. """ ndim = vec.ndim if ndim == 1: vec = vec.unsqueeze(0) if output_partial_idx is None: output_partial_idx = torch.arange(self._output_size) if len(self._fc_layers) > 1: mask = (self._fc_layers[0].hidden_neurons > 0).float() J = torch.matmul(vec, self._fc_layers[0].weight.t()) J = J * mask # [B, d_hidden] for fc in self._fc_layers[1:-1]: mask = (fc.hidden_neurons > 0).float() J = torch.matmul(J, fc.weight.t()) J = J * mask J = torch.matmul( J, self._fc_layers[-1].weight[output_partial_idx, :].t()) else: weight = self._fc_layers[0].weight[output_partial_idx, :] J = torch.matmul(vec, weight.t()) if ndim == 1: J = J.squeeze(0) return J # [B, n_out] or [n_out]
Java
UTF-8
1,910
3.203125
3
[]
no_license
package JavaBasicTrain; import com.sun.corba.se.impl.orbutil.concurrent.Sync; import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.ReentrantLock; /** * builder设计模式 */ public class User { private final String name; private final int age; private final int money;//可选 private final int girlFriend;//可选 private final int car;//可选 //定义内部类 public static class Builder{ //必须参数 private final String name; private final int age; //可选参数 private int money = 0; private int girlFriend = 0; private int car = 0; //构造函数 public Builder(String name, int age) { this.name = name; this.age = age; } //定义可选参数 public Builder money(int value){ money = value; return this; } public Builder girlFriend(int value){ girlFriend = value; return this; } public Builder car(int value){ car = value; return this; } //静态工厂方法 //设置方法返回自己本身,以便把方法连接起来 public User build(){ User user = new User(this); if(user.age > 120){ throw new RuntimeException("param error"); } return user; } } private User(Builder builder){ name = builder.name; age = builder.age; money = builder.money; girlFriend = builder.girlFriend; car = builder.car; } public static void main(String[] args) { //任意加可选参数 User user = new Builder("tom",123).money(5).car(0).build(); System.out.println(user.money); } }
SQL
UTF-8
18,834
3.078125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Apr 08, 2021 at 09:58 AM -- Server version: 10.4.10-MariaDB -- PHP Version: 7.3.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `rmsport` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- DROP TABLE IF EXISTS `admin`; CREATE TABLE IF NOT EXISTS `admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `password` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `name` varchar(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8_bin DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`id`, `email`, `password`, `name`, `remember_token`, `created_at`, `updated_at`) VALUES (6, 'admin@gmail.com', '$2y$10$l3dcAtLrRTmwzEbtbVMejOOV0j4VYFxJExG7mbpgYoaIEFCcBsyX6', '', NULL, '2021-04-06 12:39:30', '0000-00-00 00:00:00'); -- -------------------------------------------------------- -- -- Table structure for table `catalog` -- DROP TABLE IF EXISTS `catalog`; CREATE TABLE IF NOT EXISTS `catalog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `parent_id` int(11) NOT NULL DEFAULT 0, `sort_order` tinyint(4) NOT NULL DEFAULT 0, `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -- Dumping data for table `catalog` -- INSERT INTO `catalog` (`id`, `name`, `parent_id`, `sort_order`, `created_at`, `updated_at`) VALUES (24, 'Club', 0, 1, '2021-03-25 03:03:00', '0000-00-00 00:00:00'), (25, 'Sale', 0, 0, '2021-03-25 03:03:00', '0000-00-00 00:00:00'), (26, 'National Football Team', 0, 2, '2021-03-25 03:03:00', '0000-00-00 00:00:00'), (27, 'Soccer Shoes', 0, 3, '2021-03-25 03:03:00', '0000-00-00 00:00:00'), (28, 'Accessories', 0, 4, '2021-03-25 03:03:00', '0000-00-00 00:00:00'); -- -------------------------------------------------------- -- -- Table structure for table `order` -- DROP TABLE IF EXISTS `order`; CREATE TABLE IF NOT EXISTS `order` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `status` tinyint(4) NOT NULL DEFAULT 0, `user_id` int(11) NOT NULL DEFAULT 0, `user_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `user_email` varchar(50) COLLATE utf8_bin NOT NULL, `user_phone` varchar(20) COLLATE utf8_bin NOT NULL, `amount` decimal(15,4) NOT NULL DEFAULT 0.0000, `payment` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `payment_info` text COLLATE utf8_bin NOT NULL, `message` varchar(255) COLLATE utf8_bin NOT NULL, `security` varchar(16) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `user_id` (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Table structure for table `order_detail` -- DROP TABLE IF EXISTS `order_detail`; CREATE TABLE IF NOT EXISTS `order_detail` ( `order_id` bigint(20) NOT NULL, `product_id` int(255) NOT NULL, `qty` int(11) NOT NULL, `amount` decimal(15,4) NOT NULL DEFAULT 0.0000, `data` text COLLATE utf8_bin NOT NULL, `status` tinyint(4) DEFAULT 0, `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', KEY `order_detail_ibfk_1` (`product_id`), KEY `order_id` (`order_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- -------------------------------------------------------- -- -- Table structure for table `product` -- DROP TABLE IF EXISTS `product`; CREATE TABLE IF NOT EXISTS `product` ( `id` int(255) NOT NULL AUTO_INCREMENT, `catalog_id` int(11) NOT NULL, `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `price` decimal(15,4) NOT NULL DEFAULT 0.0000, `content` text COLLATE utf8_unicode_ci DEFAULT NULL, `discount` int(11) DEFAULT NULL, `image_link` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `image_list` text COLLATE utf8_unicode_ci DEFAULT NULL, `view` int(11) DEFAULT 0, `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `product_ibfk_1` (`catalog_id`) ) ENGINE=InnoDB AUTO_INCREMENT=118 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `product` -- INSERT INTO `product` (`id`, `catalog_id`, `name`, `price`, `content`, `discount`, `image_link`, `image_list`, `view`, `created_at`, `updated_at`) VALUES (16, 24, 'Real Madrid Home 2020-2021', '250.0000', NULL, NULL, NULL, 'RM_home.jpg', NULL, '2021-04-06 13:20:06', '0000-00-00 00:00:00'), (17, 24, 'Real Madrid Away 2020-2021', '250.0000', NULL, NULL, NULL, 'RM_away.jpg', NULL, '2021-04-06 13:20:18', '0000-00-00 00:00:00'), (18, 24, 'Real Madrid Third 2020-2021', '250.0000', NULL, NULL, NULL, 'RM_third.jpg', NULL, '2021-04-06 13:21:16', '0000-00-00 00:00:00'), (19, 24, 'Juvetus Home 2020-2021', '250.0000', NULL, NULL, NULL, 'juve_home.jpg', NULL, '2021-04-06 13:33:12', '0000-00-00 00:00:00'), (20, 24, 'Juvetus Away 2020-2021', '250.0000', NULL, NULL, NULL, 'juve_away.jpg', NULL, '2021-04-06 13:34:19', '0000-00-00 00:00:00'), (21, 24, 'Juvetus Third 2020-2021', '250.0000', NULL, NULL, NULL, 'juve_third.jpg', NULL, '2021-04-06 13:34:48', '0000-00-00 00:00:00'), (22, 24, 'Manchester United Home 2020-2021', '250.0000', NULL, NULL, NULL, 'MU_home.jpg', NULL, '2021-04-06 13:35:22', '0000-00-00 00:00:00'), (23, 24, 'Manchester United Away 2020-2021', '250.0000', NULL, NULL, NULL, 'MU_away.jpg', NULL, '2021-04-06 14:27:25', '0000-00-00 00:00:00'), (24, 24, 'Manchester United Third 2020-2021', '250.0000', NULL, NULL, NULL, 'MU_third.jpg', NULL, '2021-04-06 14:28:04', '0000-00-00 00:00:00'), (25, 24, 'Arsenal Home 2020-2021', '250.0000', NULL, NULL, NULL, 'ARS_home.jpg', NULL, '2021-04-06 14:29:17', '0000-00-00 00:00:00'), (26, 24, 'Arsenal Away 2020-2021', '250.0000', NULL, NULL, NULL, 'ARS_away.jpg', NULL, '2021-04-06 14:29:52', '0000-00-00 00:00:00'), (27, 24, 'Arsenal Third 2020-2021', '250.0000', NULL, NULL, NULL, 'ARS_third.jpg', NULL, '2021-04-06 14:30:41', '0000-00-00 00:00:00'), (28, 24, 'Bayern Munich Home 2020-2021', '250.0000', NULL, NULL, NULL, 'bayern_home.jpg', NULL, '2021-04-06 14:36:04', '0000-00-00 00:00:00'), (29, 24, 'Bayern Munich Away 2020-2021', '250.0000', NULL, NULL, NULL, 'bayern_away.jpg', NULL, '2021-04-06 14:37:04', '0000-00-00 00:00:00'), (30, 24, 'Bayern Munich Third 2020-2021', '250.0000', NULL, NULL, NULL, 'bayern_third.jpg', NULL, '2021-04-06 14:40:05', '0000-00-00 00:00:00'), (31, 24, 'Ajax Home 2020-2021', '250.0000', NULL, NULL, NULL, 'ajax_home.jpg', NULL, '2021-04-06 14:40:59', '0000-00-00 00:00:00'), (32, 24, 'Ajax Away 2020-2021', '250.0000', NULL, NULL, NULL, 'ajax_away.jpg', NULL, '2021-04-06 14:41:39', '0000-00-00 00:00:00'), (33, 24, 'Benfica Home 2020-2021', '250.0000', NULL, NULL, NULL, 'benfica_home.jpg', NULL, '2021-04-06 14:45:52', '0000-00-00 00:00:00'), (34, 24, 'Benfica Away 2020-2021', '250.0000', NULL, NULL, NULL, 'benfica_away.jpg', NULL, '2021-04-06 14:46:20', '0000-00-00 00:00:00'), (35, 24, 'Barcalona Home 2020-2021', '340.0000', NULL, NULL, NULL, 'barca_home.jpg', NULL, '2021-04-06 14:59:51', '0000-00-00 00:00:00'), (36, 24, 'Barcalona Away 2020-2021', '340.0000', NULL, NULL, NULL, 'barca_away.jpg', NULL, '2021-04-06 15:00:20', '0000-00-00 00:00:00'), (37, 24, 'Barcalona Third 2020-2021', '340.0000', NULL, NULL, NULL, 'barca_third.jpg', NULL, '2021-04-06 15:03:33', '0000-00-00 00:00:00'), (38, 24, 'Chelsea Home 2020-2021', '340.0000', NULL, NULL, NULL, 'chelsea_home.jpg', NULL, '2021-04-06 15:03:36', '0000-00-00 00:00:00'), (39, 24, 'Chelsea Away 2020-2021', '340.0000', NULL, NULL, NULL, 'chelsea_away.jpg', NULL, '2021-04-06 15:04:09', '0000-00-00 00:00:00'), (40, 24, 'Chelsea Third 2020-2021', '340.0000', NULL, NULL, NULL, 'chelsea_third.jpg', NULL, '2021-04-06 15:33:13', '0000-00-00 00:00:00'), (41, 24, 'Inter Milan Home 2020-2021', '340.0000', NULL, NULL, NULL, 'inter_home.jpg', NULL, '2021-04-06 15:59:08', '0000-00-00 00:00:00'), (42, 24, 'Inter Milan Away 2020-2021', '340.0000', NULL, NULL, NULL, 'inter_away.jpg', NULL, '2021-04-06 16:00:16', '0000-00-00 00:00:00'), (43, 24, 'Inter Milan Third 2020-2021', '340.0000', NULL, NULL, NULL, 'inter_third.jpg', NULL, '2021-04-06 16:00:15', '0000-00-00 00:00:00'), (44, 24, 'Liverpool Home 2020-2021', '340.0000', NULL, NULL, NULL, 'liverpool_home.jpg', NULL, '2021-04-06 16:00:57', '0000-00-00 00:00:00'), (45, 24, 'Liverpool Away 2020-2021', '340.0000', NULL, NULL, NULL, 'liverpool_away.jpg', NULL, '2021-04-06 16:07:11', '0000-00-00 00:00:00'), (46, 24, 'Liverpool Third 2020-2021', '340.0000', NULL, NULL, NULL, 'liverpool_third.jpg', NULL, '2021-04-06 16:07:14', '0000-00-00 00:00:00'), (47, 24, 'Paris Saint-Germain Home 2020-2021', '340.0000', NULL, NULL, NULL, 'PSG_home.jpg', NULL, '2021-04-06 16:09:26', '0000-00-00 00:00:00'), (48, 24, 'Paris Saint-Germain Away 2020-2021', '340.0000', NULL, NULL, NULL, 'PSG_away.jpg', NULL, '2021-04-06 16:13:19', '0000-00-00 00:00:00'), (49, 24, 'Paris Saint-Germain Third 2020-2021', '340.0000', NULL, NULL, NULL, 'PSG_third.jpg', NULL, '2021-04-06 16:14:10', '0000-00-00 00:00:00'), (50, 24, 'AS Roma Home 2020-2021', '340.0000', NULL, NULL, NULL, 'roma_home.jpg', NULL, '2021-04-06 16:21:17', '0000-00-00 00:00:00'), (51, 24, 'AS Roma Away 2020-2021', '340.0000', NULL, NULL, NULL, 'roma_away.jpg', NULL, '2021-04-06 16:21:46', '0000-00-00 00:00:00'), (52, 24, 'Totenham Home 2020-2021', '340.0000', NULL, NULL, NULL, 'TOT_home.jpg', NULL, '2021-04-06 16:22:54', '0000-00-00 00:00:00'), (53, 24, 'Totenham Away 2020-2021', '340.0000', NULL, NULL, NULL, 'TOT_away.jpg', NULL, '2021-04-06 16:26:03', '0000-00-00 00:00:00'), (54, 24, 'Totenham Third 2020-2021', '340.0000', NULL, NULL, NULL, 'TOT_third.jpg', NULL, '2021-04-06 16:26:38', '0000-00-00 00:00:00'), (55, 24, 'AC Milan Home 2020-2021', '270.0000', NULL, NULL, NULL, 'acmilan_home.jpg', NULL, '2021-04-06 16:32:11', '0000-00-00 00:00:00'), (56, 24, 'AC Milan Away 2020-2021', '270.0000', NULL, NULL, NULL, 'acmilan_away.jpg', NULL, '2021-04-06 16:32:46', '0000-00-00 00:00:00'), (57, 24, 'AC Milan Third 2020-2021', '270.0000', NULL, NULL, NULL, 'acmilan_third.jpg', NULL, '2021-04-06 16:35:15', '0000-00-00 00:00:00'), (58, 24, 'Manchester City Home 2020-2021', '270.0000', NULL, NULL, NULL, 'mancity_home.jpg', NULL, '2021-04-06 16:38:34', '0000-00-00 00:00:00'), (59, 24, 'Manchester City Away 2020-2021', '270.0000', NULL, NULL, NULL, 'mancity_away.jpg', NULL, '2021-04-06 16:38:18', '0000-00-00 00:00:00'), (60, 24, 'Manchester City Third 2020-2021', '270.0000', NULL, NULL, NULL, 'mancity_third.jpg', NULL, '2021-04-06 16:38:07', '0000-00-00 00:00:00'), (61, 24, 'Dormund Home 2020-2021', '270.0000', NULL, NULL, NULL, 'dormund_home.jpg', NULL, '2021-04-06 16:39:12', '0000-00-00 00:00:00'), (90, 26, 'Spain Home 2020-2021', '250.0000', NULL, NULL, NULL, 'spain_home.jpg', NULL, '2021-04-06 16:40:41', '0000-00-00 00:00:00'), (91, 26, 'Spain Away 2020-2021', '250.0000', NULL, NULL, NULL, 'spain_away.jpg', NULL, '2021-04-06 16:41:33', '0000-00-00 00:00:00'), (92, 26, 'Argentina Home 2020-2021', '250.0000', NULL, NULL, NULL, 'argentina_home.jpg', NULL, '2021-04-06 16:42:17', '0000-00-00 00:00:00'), (93, 26, 'Argentina Away 2020-2021', '250.0000', NULL, NULL, NULL, 'argentina_away', NULL, '2021-04-06 16:42:46', '0000-00-00 00:00:00'), (94, 26, 'Germany Home 2020-2021', '250.0000', NULL, NULL, NULL, 'germany_home.jpg', NULL, '2021-04-06 16:43:37', '0000-00-00 00:00:00'), (95, 26, 'Germany Away 2020-2021', '250.0000', NULL, NULL, NULL, 'germany_away.jpg', NULL, '2021-04-06 16:44:11', '0000-00-00 00:00:00'), (96, 26, 'Belgium Home 2020-2021', '250.0000', NULL, NULL, NULL, 'belgium_home.jpg', NULL, '2021-04-06 16:44:56', '0000-00-00 00:00:00'), (97, 26, 'Belgium Away 2020-2021', '250.0000', NULL, NULL, NULL, 'belgium_away.jpg', NULL, '2021-04-06 16:45:25', '0000-00-00 00:00:00'), (98, 26, 'Mexico Home 2020-2021', '250.0000', NULL, NULL, NULL, 'mexico_home.jpg', NULL, '2021-04-06 16:46:11', '0000-00-00 00:00:00'), (99, 26, 'Swenden Home 2020-2021', '250.0000', NULL, NULL, NULL, 'swenden_home.jpg', NULL, '2021-04-06 16:46:51', '0000-00-00 00:00:00'), (100, 26, 'Portugal Home 2020-2021', '340.0000', NULL, NULL, NULL, 'portugal_home.jpg', NULL, '2021-04-06 16:47:36', '0000-00-00 00:00:00'), (101, 26, 'Portugal Away 2020-2021', '340.0000', NULL, NULL, NULL, 'portugal_away.jpg', NULL, '2021-04-06 16:48:09', '0000-00-00 00:00:00'), (102, 26, 'Brazil Home 2020-2021', '340.0000', NULL, NULL, NULL, 'brazil_home.jpg', NULL, '2021-04-06 16:48:47', '0000-00-00 00:00:00'), (103, 26, 'Brazil Away 2020-2021', '340.0000', NULL, NULL, NULL, 'brazil_away.jpg', NULL, '2021-04-06 16:49:37', '0000-00-00 00:00:00'), (104, 26, 'England Home 2020-2021', '340.0000', NULL, NULL, NULL, 'england_home.jpg', NULL, '2021-04-06 16:50:19', '0000-00-00 00:00:00'), (105, 26, 'England Away 2020-2021', '340.0000', NULL, NULL, NULL, 'england_away.jpg', NULL, '2021-04-06 16:50:54', '0000-00-00 00:00:00'), (106, 26, 'France Home 2020-2021', '340.0000', NULL, NULL, NULL, 'france_home.jpg', NULL, '2021-04-06 17:11:03', '0000-00-00 00:00:00'), (107, 26, 'France Away 2020-2021', '340.0000', NULL, NULL, NULL, 'france_away.jpg', NULL, '2021-04-06 17:11:31', '0000-00-00 00:00:00'), (108, 26, 'Netherlands Home 2020-2021', '340.0000', NULL, NULL, NULL, 'netherlands_home.jpg', NULL, '0000-00-00 00:00:00', '0000-00-00 00:00:00'), (109, 26, 'Netherlands Away 2020-2021', '340.0000', NULL, NULL, NULL, 'netherlands_away.jpg', NULL, '2021-04-06 17:13:49', '0000-00-00 00:00:00'), (110, 26, 'Negeria Home 2020-2021', '340.0000', NULL, NULL, NULL, 'negeria_home.jpg', NULL, '2021-04-06 17:14:34', '0000-00-00 00:00:00'), (111, 26, 'Italia Home 2020-2021', '270.0000', NULL, NULL, NULL, 'italia_home.jpg', NULL, '2021-04-06 17:15:19', '0000-00-00 00:00:00'), (112, 26, 'Italia Away 2020-2021', '270.0000', NULL, NULL, NULL, 'italia_away.jpg', NULL, '2021-04-06 17:15:55', '0000-00-00 00:00:00'), (113, 26, 'Italia Third 2020-2021', '270.0000', NULL, NULL, NULL, 'italia_third.jpg', NULL, '2021-04-06 17:16:30', '0000-00-00 00:00:00'); -- -------------------------------------------------------- -- -- Table structure for table `sinhvien` -- DROP TABLE IF EXISTS `sinhvien`; CREATE TABLE IF NOT EXISTS `sinhvien` ( `id` int(10) NOT NULL AUTO_INCREMENT, `tensv` varchar(50) NOT NULL, `lop` varchar(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- -- Dumping data for table `sinhvien` -- INSERT INTO `sinhvien` (`id`, `tensv`, `lop`) VALUES (1, 'Nguyễn Cao Bảo Ngọc', 'D16_TH06'), (2, 'Nguyễn Ngọc Anh Thy', 'D17_TH03'), (3, 'Đỗ Phương Đô', 'D17_TH03'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; CREATE TABLE IF NOT EXISTS `users` ( `id` int(255) NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `address` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL, `password` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `google_id` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT current_timestamp(), `updated_at` timestamp NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `phone`, `address`, `password`, `google_id`, `remember_token`, `created_at`, `updated_at`) VALUES (19, 'Ngọc', 'test123@gmail.com', '0999087679', '180 Cao Lỗ', '$2y$10$kp931TVeQK/0.R9KRyuU8O2rR800tl.PzQlmPHNps/jTh64.LpRCG', NULL, 'woOzoO2WKKOggzDKaoLOQqFjcnMx6JvAdMKXBynBOZxXq3rjd4ajTt74Shwt', '2021-03-26 16:01:11', '0000-00-00 00:00:00'), (22, 'Ngọc Nguyễn 2', 'ngocnguyen7862@gmail.com', NULL, NULL, '$2y$10$HroNa0V9TerL82Wvm8m2he2yDsWmP5inyA8B8uw02fA33Vwz6Xo7q', NULL, NULL, '2021-04-02 19:39:04', '2021-04-02 19:39:04'), (26, 'Ngọc Nguyễn 9999', 'ngocnguyen7863@gmail.com', NULL, NULL, '$2y$10$l3dcAtLrRTmwzEbtbVMejOOV0j4VYFxJExG7mbpgYoaIEFCcBsyX6', NULL, NULL, '2021-04-02 19:56:44', '2021-04-02 19:56:44'), (27, 'Ngọc Nguyễn 100000', 'ngocnguyen7860000@gmail.com', NULL, NULL, '$2y$10$JmXZmxsmbolywpPyOfateeXT/9diLN.6rIig2K75YPrLn775xprqy', NULL, NULL, '2021-04-02 19:57:29', '2021-04-02 19:57:29'), (28, 'Phương Đô', 'dophuongdo1511@gmail.com', NULL, NULL, '$2y$10$CK7GY.EItE7Y1Dw5dFFn4e1dVAXnjOQA6KknlkWUq9aeyHBG.2hum', NULL, NULL, '2021-04-06 02:20:30', '2021-04-06 02:20:30'); -- -- Indexes for dumped tables -- -- -- Indexes for table `product` -- ALTER TABLE `product` ADD FULLTEXT KEY `name` (`name`); -- -- Constraints for dumped tables -- -- -- Constraints for table `order` -- ALTER TABLE `order` ADD CONSTRAINT `order_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE; -- -- Constraints for table `order_detail` -- ALTER TABLE `order_detail` ADD CONSTRAINT `order_detail_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON UPDATE CASCADE, ADD CONSTRAINT `order_detail_ibfk_2` FOREIGN KEY (`order_id`) REFERENCES `order` (`id`) ON UPDATE CASCADE; -- -- Constraints for table `product` -- ALTER TABLE `product` ADD CONSTRAINT `product_ibfk_1` FOREIGN KEY (`catalog_id`) REFERENCES `catalog` (`id`) ON UPDATE CASCADE; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C#
UTF-8
877
2.828125
3
[ "MIT" ]
permissive
using System; namespace BenchmarkDotNet.Diagnosers { public class PerfCollectProfilerConfig { /// <param name="performExtraBenchmarksRun">When set to true, benchmarks will be executed one more time with the profiler attached. If set to false, there will be no extra run but the results will contain overhead. False by default.</param> /// <param name="timeoutInSeconds">How long should we wait for the perfcollect script to finish processing the trace. 300s by default.</param> public PerfCollectProfilerConfig(bool performExtraBenchmarksRun = false, int timeoutInSeconds = 300) { RunMode = performExtraBenchmarksRun ? RunMode.ExtraRun : RunMode.NoOverhead; Timeout = TimeSpan.FromSeconds(timeoutInSeconds); } public TimeSpan Timeout { get; } public RunMode RunMode { get; } } }
Java
UTF-8
5,795
1.960938
2
[]
no_license
package com.htstar.ovms.enterprise.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.htstar.ovms.common.core.constant.SecurityConstants; import com.htstar.ovms.common.core.util.R; import com.htstar.ovms.common.log.annotation.SysLog; import com.htstar.ovms.common.security.annotation.Inner; import com.htstar.ovms.common.security.service.OvmsUser; import com.htstar.ovms.common.security.util.SecurityUtils; import com.htstar.ovms.enterprise.api.dto.CarSchedulingTimeDTO; import com.htstar.ovms.enterprise.api.dto.CarSchedulingTimeWhereDTO; import com.htstar.ovms.enterprise.api.entity.CarInfo; import com.htstar.ovms.enterprise.api.entity.CarSchedulingTime; import com.htstar.ovms.enterprise.service.CarInfoService; import com.htstar.ovms.enterprise.service.CarSchedulingTimeService; import org.apache.ibatis.annotations.Update; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; /** * * * @author htxk * @date 2020-10-29 12:07:04 */ @RestController @AllArgsConstructor @RequestMapping("/carschedulingtime" ) @Api(value = "carschedulingtime", tags = "管理排班") public class CarSchedulingTimeController { private final CarSchedulingTimeService carSchedulingTimeService; private final CarInfoService carInfoService; /** * 分页查询 * @param page 分页对象 * @param carSchedulingTime * @return */ @ApiOperation(value = "分页查询", notes = "分页查询") @PostMapping("/page" ) public R getCarSchedulingTimePage(@RequestBody CarSchedulingTimeDTO carSchedulingTimeDTO) { return R.ok(carSchedulingTimeService.getSchedulingAll(carSchedulingTimeDTO)); } /** * 通过日期查询判断是否使用车 * @param * @return R */ @ApiOperation(value = "通过日期查询判断是否使用车", notes = "通过日期查询判断是否使用车") @PostMapping("/rqweek") @Inner public int getCount(CarSchedulingTimeWhereDTO carSchedulingTimeWhereDTO,@RequestHeader(SecurityConstants.FROM) String from) { return carSchedulingTimeService.getBylicCode(carSchedulingTimeWhereDTO); } /** * 更具日期时间判断是否可以使用车,排班新车 * @return */ @GetMapping("/xcrqweek/{licCode}" ) @Inner int getlicCodeCount(@PathVariable("licCode") String licCode,@RequestHeader(SecurityConstants.FROM) String from){ return carSchedulingTimeService.getBylicCodeCount(licCode); } /** * 新增 * @param carSchedulingTime * @return R */ @ApiOperation(value = "新增", notes = "新增") @PostMapping public R save(@RequestBody CarSchedulingTime carSchedulingTime) { carSchedulingTime.setCreatetime(LocalDateTime.now()); OvmsUser user = SecurityUtils.getUser(); if ( user != null) { carSchedulingTime.setEtpId(user.getEtpId()); } boolean save = carSchedulingTimeService.save(carSchedulingTime); if(save){ return R.ok("保存成功"); }else{ return R.ok("保存失败"); } } /** * 修改 * @param carSchedulingTime * @return R */ @ApiOperation(value = "修改", notes = "修改") @PutMapping public R updateById(@RequestBody CarSchedulingTime carSchedulingTime) { carSchedulingTime.setUpdatetime(LocalDateTime.now()); return R.ok(carSchedulingTimeService.updateById(carSchedulingTime)); } /** * 通过id删除 * @param id id * @return R */ @ApiOperation(value = "通过id删除", notes = "通过id删除") @SysLog("通过id删除" ) @DeleteMapping("/{id}" ) public R removeById(@PathVariable Integer id) { return R.ok(carSchedulingTimeService.removeById(id)); } /** * 通过id查詢 * @param id id * @return R */ @ApiOperation(value = "通过id查詢", notes = "通过id查詢") @SysLog("通过id查詢" ) @GetMapping ("/{id}" ) public R getByById(@PathVariable Integer id) { return R.ok(carSchedulingTimeService.getById(id)); } /** * 修改 * @param carSchedulingTime * @return R */ @ApiOperation(value = "根据排班id删除车辆", notes = "根据排班id删除车辆") @PutMapping("/removeById") public R removeById(@RequestBody CarSchedulingTime carSchedulingTime) { carSchedulingTime.setUpdatetime(LocalDateTime.now()); UpdateWrapper<CarSchedulingTime> c = new UpdateWrapper<>(); c.lambda() .set(CarSchedulingTime::getCarId,carSchedulingTime.getCarId()) .or() .set(CarSchedulingTime::getUpdatetime,carSchedulingTime.getUpdatetime()) .or() .eq(CarSchedulingTime::getId,carSchedulingTime.getId()); return R.ok(carSchedulingTimeService.update(c)); } @GetMapping("/getsettings/{licCode}") @Inner public int getsettings(@PathVariable("licCode") String licCode,@RequestHeader(SecurityConstants.FROM) String from){ QueryWrapper<CarInfo> c = new QueryWrapper<>(); c.lambda().eq(CarInfo::getLicCode,licCode); c.lambda().eq(CarInfo::getApplyStatus,1); int count = carInfoService.count(c); return count; } }
Java
UTF-8
1,306
2.359375
2
[]
no_license
package com.capgemini.heskuelita.service.impl; import com.capgemini.heskuelita.core.beans.User; import com.capgemini.heskuelita.data.IUserDao; import com.capgemini.heskuelita.service.ISecurityService; import com.capgemini.heskuelita.service.SecurityException; public class SecurityServiceImpl implements ISecurityService { private IUserDao userDao; public SecurityServiceImpl (IUserDao userDao) { super (); this.userDao = userDao; } @Override public User login (User user) throws SecurityException { try { user = this.userDao.login (user.getUserName(), user.getPassword()); } catch (Exception e) { throw new SecurityException(e); } return user; } @Override public void signUp (User user) throws SecurityException{ try { this.userDao.signUp(user.getFirst_name(), user.getLast_name(),user.getBirthday(),user.getGender(), user.getDocType(),user.getIdentification(),user.getPhone(),user.getAdress(), user.getZipcode(),user.getUserName(),user.getEmail(),user.getPassword()); }catch (Exception e){ throw new SecurityException(e); } } }
Java
UTF-8
141
1.5625
2
[]
no_license
package com.example.appuidroid.ui.letterlist; public interface LetterListViewListener { public void onTouchingLetterChanged(String chr); }
C
UTF-8
365
3.8125
4
[]
no_license
# include <stdio.h> int main (void) { int a; int b; int c; int d; printf("please input two number:\n"); scanf("%d%d",&a,&b); printf("your input is: %4d%4d\n",a,b); if(b!=0) { c = a/b; d = a%b; printf("%d divided by %d is %d and the reminder is %d \n",a,b,c,d); } else { printf("Error: zero divisor\n"); } return 0; }
C#
UTF-8
2,116
2.578125
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright 2017 Google Inc. 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. using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Google.Cloud.Tools.ShowReverseDependencies { public class Program { private static void Main(string[] args) { if (args.Length != 3) { Console.WriteLine("Required arguments: json-file package-name depth"); Console.WriteLine("e.g. nuget-dependencies.json Google.Apis 3"); return; } var json = File.ReadAllText(args[0]); var allPackages = JsonConvert.DeserializeObject<List<PackageInfo>>(json); string package = args[1]; int depth = int.Parse(args[2]); var reverseMap = allPackages .SelectMany(p => p.Dependencies.Select(d => new { from = p.Id, to = d })) .ToLookup(p => p.to, p => p.from); List<string> sourceSet = new[] { package }.ToList(); for (int i = 1; i <= depth; i++) { sourceSet = sourceSet .SelectMany(p => reverseMap[p]) .OrderBy(p => p) .Distinct() .ToList(); Console.WriteLine($"Dependencies at depth {i}:"); foreach (var dependency in sourceSet) { Console.WriteLine(dependency); } Console.WriteLine(); } } } }
Java
UTF-8
10,301
2.21875
2
[ "MIT" ]
permissive
package net.ausiasmarch.dao.genericdao; import net.ausiasmarch.dao.daointerface.DaoInterface; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import net.ausiasmarch.bean.BeanInterface; import net.ausiasmarch.bean.UsuarioBean; import net.ausiasmarch.exceptions.MyException; import net.ausiasmarch.factory.BeanFactory; import net.ausiasmarch.helper.Log4jHelper; import net.ausiasmarch.setting.ConfigurationSettings; public class GenericDao implements DaoInterface { protected Connection oConnection = null; protected String ob = null; protected String strSQL = null; protected String strCountSQL = null; protected String strGetSQL = null; protected UsuarioBean oUsuarioBeanSession; protected int idSessionUser; protected int idSessionUserTipe; public GenericDao(Connection oConnection, String ob, UsuarioBean oUsuarioBeanSession) { this.oConnection = oConnection; this.ob = ob; //Sentencias SQL this.strSQL = "SELECT * FROM " + ob + " WHERE 1=1 "; this.strCountSQL = "SELECT COUNT(*) FROM " + ob + " WHERE 1=1 "; this.strGetSQL = "SELECT * FROM " + ob + " WHERE id=?"; if (oUsuarioBeanSession != null) { this.oUsuarioBeanSession = oUsuarioBeanSession; this.idSessionUser = oUsuarioBeanSession.getId(); this.idSessionUserTipe = oUsuarioBeanSession.getTipo_usuario_id(); } } @Override public BeanInterface get(int id) throws Exception { PreparedStatement oPreparedStatement = null; ResultSet oResultSet = null; BeanInterface oBean = null; strSQL = "Select * From " + ob + " WHERE id=?"; oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement.setInt(1, id); oResultSet = oPreparedStatement.executeQuery(); try { if (oResultSet.next()) { oBean = BeanFactory.getBean(ob); oBean = oBean.fill(oResultSet, oConnection, ConfigurationSettings.spread, oUsuarioBeanSession); } else { oBean = null; } return oBean; } catch (MyException ex) { String msg = this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName() + " ob:" + ob; Log4jHelper.errorLog(msg, ex); ex.addDescripcion(msg); throw ex; } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } } @Override public Integer getCount(Integer id, String filter) throws Exception { PreparedStatement oPreparedStatement = null; ResultSet oResultSet = null; BeanInterface oBean = BeanFactory.getBean(ob); try { if (id != null && filter != null) { strCountSQL += " AND " + oBean.getFieldId(filter) + " = " + id; } oPreparedStatement = oConnection.prepareStatement(strCountSQL); oResultSet = oPreparedStatement.executeQuery(); if (oResultSet.next()) { return oResultSet.getInt(1); } else { return -1; } } catch (MyException ex) { String msg = this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName() + " ob:" + ob; Log4jHelper.errorLog(msg, ex); ex.addDescripcion(msg); throw ex; } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } } @Override public ArrayList<BeanInterface> getPage(int page, int rpp, String orden, String direccion, String word, Integer id, String filter) throws Exception { PreparedStatement oPreparedStatement = null; ResultSet oResultSet = null; ArrayList<BeanInterface> listaBean = new ArrayList<>(); try { BeanInterface oBean = BeanFactory.getBean(ob); int offset; if (page == 1) { offset = 0; } else { offset = (rpp * page) - rpp; } int numparam = 0; //Condicion de ordenar if (orden == null) { strSQL += " LIMIT ? OFFSET ?"; oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement.setInt(++numparam, rpp); oPreparedStatement.setInt(++numparam, offset); } else { strSQL += " ORDER BY " + oBean.getFieldOrder(orden); if (direccion.equalsIgnoreCase("asc")) { strSQL += " ASC "; } else if (direccion.equalsIgnoreCase("desc")) { strSQL += " DESC "; } strSQL += "LIMIT ? OFFSET ?"; oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement.setInt(++numparam, rpp); oPreparedStatement.setInt(++numparam, offset); } numparam = 0; if (word != null) { strSQL = "SELECT * FROM " + ob + " WHERE 1=1 AND " + oBean.getFieldConcat() + " LIMIT ? OFFSET ?"; oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement = oBean.setFilter(numparam, oPreparedStatement, word, rpp, offset); } //Condicion de busqueda numparam = 0; //Condicion de filtro de objeto if (id != null && filter != null) { if (idSessionUser == 1) { strSQL += ""; oPreparedStatement = oConnection.prepareStatement("SELECT * FROM " + ob + " INNER JOIN " + filter + " ON " + filter + ".id = " + ob + "." + oBean.getFieldId(filter) + " WHERE " + oBean.getFieldId(filter) + " = ? LIMIT ? OFFSET ?"); oPreparedStatement = oBean.setFieldId(numparam, oPreparedStatement, id, rpp, offset); } } oResultSet = oPreparedStatement.executeQuery(); while (oResultSet.next()) { oBean = BeanFactory.getBean(ob); oBean = oBean.fill(oResultSet, oConnection, ConfigurationSettings.spread, oUsuarioBeanSession); listaBean.add(oBean); } } catch (MyException ex) { String msg = this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName() + " ob:" + ob; Log4jHelper.errorLog(msg, ex); ex.addDescripcion(msg); throw ex; } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } return listaBean; } @Override public Integer insert(BeanInterface oBeanParam) throws Exception { BeanInterface oBean = BeanFactory.getBean(ob); PreparedStatement oPreparedStatement = null; ResultSet oResultSet = null; int iResult = 0; try { String strsql = "INSERT INTO " + ob + oBean.getFieldInsert(); oPreparedStatement = oConnection.prepareStatement(strsql, Statement.RETURN_GENERATED_KEYS); oPreparedStatement = oBean.setFieldInsert(oBeanParam, oPreparedStatement); iResult = oPreparedStatement.executeUpdate(); oResultSet = oPreparedStatement.getGeneratedKeys(); oResultSet.next(); iResult = oResultSet.getInt(1); } catch (MyException ex) { String msg = this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName() + " ob:" + ob; Log4jHelper.errorLog(msg, ex); ex.addDescripcion(msg); throw ex; } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } return iResult; } @Override public Integer remove(int id) throws Exception { PreparedStatement oPreparedStatement = null; int iResult = 0; try { String strSQL = "DELETE FROM " + ob + " WHERE id=?"; oPreparedStatement = oConnection.prepareStatement(strSQL, Statement.RETURN_GENERATED_KEYS); oPreparedStatement.setInt(1, id); iResult = oPreparedStatement.executeUpdate(); } catch (MyException ex) { String msg = this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName() + " ob:" + ob; Log4jHelper.errorLog(msg, ex); ex.addDescripcion(msg); throw ex; } finally { if (oPreparedStatement != null) { oPreparedStatement.close(); } } return iResult; } @Override public Integer update(BeanInterface oBeanParam) throws Exception { BeanInterface oBean = BeanFactory.getBean(ob); PreparedStatement oPreparedStatement = null; int iResult = 0; try { String strSQL = "UPDATE " + ob + " SET " + oBean.getFieldUpdate() + " WHERE id = ?"; oPreparedStatement = oConnection.prepareStatement(strSQL, Statement.RETURN_GENERATED_KEYS); oPreparedStatement = oBean.setFieldUpdate(oBeanParam, oPreparedStatement); iResult = oPreparedStatement.executeUpdate(); } catch (MyException ex) { String msg = this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName() + " ob:" + ob; Log4jHelper.errorLog(msg, ex); ex.addDescripcion(msg); throw ex; } finally { if (oPreparedStatement != null) { oPreparedStatement.close(); } } return iResult; } }
Python
UTF-8
3,864
3.171875
3
[]
no_license
# ---------------------------------------------------------------------------------------------------------------------- import numpy as np # ---------------------------------------------------------------------------------------------------------------------- """ @author Julian Salinas, Armando Lopez, Andrey Mendoza, Brandon Dinarte @version 1.6.49 """ class Entrenamiento(object): def __init__(self, coleccion, porcentaje_coleccion, porcentaje_valores): """ Clase encargada de realizar el entrenamiento del sistema. El resultado de objetivo de este entrenamiento es encontrar los autovectores/caras que componen el autoespacio, además de sus respectivas proyecciones (o pesos) Además se guarda la muestra promedio para centrar las imagenes al origen cuando sea necesario clasificarlas @param coleccion: Instancia de Coleccion de donde vamos a extraer las imagenes @param porcentaje_coleccion: Representa la cant de imagenes que usaremos de la coleccion @param porcentaje_valores: Número que determine la cantidad de valores (o componentes) que se desean conservar @return Sin retorno """ # Obtenemos los índices de la coleccion de las imagenes que usaremos de muestra self.indices_entrenamiento = None self.obt_indices_entrenamiento(coleccion, porcentaje_coleccion) # Obtenemos la matriz de muestras para realizar el entrenamiento mat_entrenamiento = coleccion.obt_subconjunto(self.indices_entrenamiento) # Se centran todas las muestras de Px1 de la matriz A (PxM) al origen self.muestra_promedio = np.mean(mat_entrenamiento, axis=1, dtype="float64") mat_entrenamiento -= self.muestra_promedio # Se obtiene la matriz de covarianza C (MxM para ahorrar costo computacional) mat_covarianza = mat_entrenamiento.T * mat_entrenamiento mat_covarianza /= mat_entrenamiento.shape[1] - 1 # Para C se obtienen los autovectores V. autovals, autovects = np.linalg.eig(mat_covarianza) # Ordenar y obtener las autocaras mas significantes cant_valores = int(mat_entrenamiento.shape[1] * porcentaje_valores / 100) orden = np.argsort(autovals)[::-1] autovects = autovects[:, orden] autovects = autovects[0: cant_valores] # Se ocupan los autovectores U de la matriz PxP, por lo que se usa la fórmula U = AxV self.autoespacio = mat_entrenamiento * autovects.T self.autoespacio /= np.linalg.norm(self.autoespacio, axis=0) # Se realiza las proyecciones al nuevo autoespacio self.proyecciones = self.autoespacio.T * mat_entrenamiento # ---------------------------------------------------------------------------------------------------------------------- def obt_indices_entrenamiento(self, coleccion, porcentaje_coleccion): """ Obtenemos los índices de la coleccion de las imagenes que vamos a utilizar para el entrenamiento @param coleccion: Instancia de Coleccion de donde vamos a extraer las imagenes @param porcentaje_coleccion: Representa la cant de imagenes que usaremos de la coleccion @return: no retorna ningun valor """ self.indices_entrenamiento = np.array([], dtype="int32") total_sujs = coleccion.total_sujs imgs_x_suj = coleccion.total_imgs // total_sujs cant_imgs = int(imgs_x_suj * porcentaje_coleccion / 100) for i in range(0, total_sujs): escogidos = np.random.choice(range(0, imgs_x_suj), cant_imgs, False) escogidos += i * imgs_x_suj escogidos = np.sort(escogidos) self.indices_entrenamiento = np.append(self.indices_entrenamiento, [escogidos]) # ----------------------------------------------------------------------------------------------------------------------
Python
UTF-8
2,374
3.125
3
[]
no_license
############################################################################### # File name: execute.py # # Author: Milton Straw # # Date created: 12/4/2019 # # Date last modified: 12/11/2019 # # Instructor: Dr. Jason DeBacker # # Course: ECON 815 # ############################################################################### ''' This script solves my dynamic programming problem from Problem Set 7 by calling functions defined in `functions.py`. It then plots the value function as a function of a state variable. ''' # Import packages and scripts, listed alphabetically import functions import matplotlib.pyplot as plt import numpy as np # Parameters beta = 0.95 w_0 = 1000000 I_0 = 1500000 C = 250000 rho = 0.1 alpha = 0.7 gamma = 0.3 # Create grid for k lb_m = 0.4 ub_m = 2.0 size_m = 100 m_grid = np.linspace(lb_m, ub_m, size_m) # Create grid for depreciation delta epsilon = np.random.uniform(0, 0.1) delta_grid = rho + epsilon ''' ------------------------------------------------------------------------------- Value Function Iteration ------------------------|------------------------------------------------------ Call the `vfi()` function from `functions.py` imported above. ------------------------------------------------------------------------------- ''' vfi(V_params) ''' ------------------------------------------------------------------------------- Extract the decision rule. ------------------------|------------------------------------------------------ opt = vector, the optimal choice of c for each c ------------------------------------------------------------------------------- ''' optI = k_grid - optK # optimal investment ''' ------------------------------------------------------------------------------- Visualization ------------------------------------------------------------------------------- ''' # Plot value function plt.figure() plt.plot(k_grid[1:], VF[1:]) plt.xlabel('Quality as a Fn of Depreciated Equipment Stock') plt.ylabel('Value Function') plt.title('Value Function - deterministic investment in quality') plt.show()
Markdown
UTF-8
1,893
2.765625
3
[]
no_license
--- layout: post title: "junit mockmvc 한글깨짐 처리시 restdocs 에러" date: 2021-08-11 11:37 +0900 comments: true tags : ["spring restdocs","junit 한글깨짐","restdocs","REST Docs configuration not found","Did you forget to apply a MockMvcRestDocumentationConfigurer when building the MockMvc instance"] categories : ["java"] sitemap : changefreq : daily priority : 1.0 ---> # junit mockmvc 한글깨짐 처리시 restdocs 에러 ```java @BeforeEach public void before(WebApplicationContext ctx) { this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx) .addFilters(new CharacterEncodingFilter("UTF-8", true)) .alwaysDo(print()) .build(); } ``` 일반적으로 한글깨짐 처리시 위에처럼 mockMvc를 생성할때 필터를 동작시키는 방법으로 처리를 한다. 그런데 rest docs를 같이 사용하면 아래의 에러를 볼수 있다. ``` REST Docs configuration not found. Did you forget to apply a MockMvcRestDocumentationConfigurer when building the MockMvc instance? java.lang.IllegalStateException: REST Docs configuration not found. Did you forget to apply a MockMvcRestDocumentationConfigurer when building the MockMvc instance? ``` 처리 방안은 아래처럼 하나를 추가해주면 된다. ```java @ExtendWith({RestDocumentationExtension.class}) @SpringBootTest @AutoConfigureRestDocs public class ControllerTest{ @BeforeEach public void before(WebApplicationContext ctx, RestDocumentationContextProvider restDocumentationContextProvider) { this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx) .apply(documentationConfiguration(restDocumentationContextProvider)) .addFilters(new CharacterEncodingFilter("UTF-8", true)) .alwaysDo(print()) .build(); } } ``` 위처럼 수정해주면 에러 없이 정상 동작을 한다. # 참고자료 -----
TypeScript
UTF-8
6,472
2.671875
3
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2019 Toshiba Corporation * SPDX-License-Identifier: Apache-2.0 */ import { interaction, Renderer } from "pixi.js"; import InteractionEvent = interaction.InteractionEvent; import InteractionManager = interaction.InteractionManager; import { EShape } from "../e-shape"; import { EShapeRuntime } from "../e-shape-runtime"; import { EShapeRuntimeReset } from "../e-shape-runtime-reset"; /** * An action runtime. * Please note that all the action runtimes are shared across shapes. */ export interface EShapeActionRuntime { readonly reset: EShapeRuntimeReset; /** * Called to initialize this action runtime for the given shape. * * @param shape a shape * @param runtime a runtime */ initialize(shape: EShape, runtime: EShapeRuntime): void; /** * Called to execute this action for the given shape. * * @param shape a shape * @param runtime a runtime * @param time a current time */ execute(shape: EShape, runtime: EShapeRuntime, time: number): void; /** * Called when the shape size is changed. * * @param shape a shape * @param runtime a runtime */ onResize(shape: EShape, runtime: EShapeRuntime): void; /** * Called when a shape is clicked. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onClick(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent | KeyboardEvent): void; /** * Called when a shape is double clicked. * @param shape a shape * @param runtime a runtime * @param e an event object * @param manager the interaction manager */ onDblClick( shape: EShape, runtime: EShapeRuntime, e: MouseEvent | TouchEvent, manager: InteractionManager ): void; /** * Called when a pointer or a key are about to be pressed on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onDowning(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent | KeyboardEvent): void; /** * Called when a pointer or a key get pressed on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onDown(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent | KeyboardEvent): void; /** * Called when a pointer is moved on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onMove(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a pointer gets on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onOver(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a pointer gets out of a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onOut(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a pointer or a key get released on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onUp(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent | KeyboardEvent): void; /** * Called when a pointer or a key get released outside of a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onUpOutside(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent | KeyboardEvent): void; /** * Called when a shape is pressed. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onPressed(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent | KeyboardEvent): void; /** * Called when a shape is released. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onUnpressed(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent | KeyboardEvent): void; /** * Called when a key is pressed on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onKeyDown(shape: EShape, runtime: EShapeRuntime, e: KeyboardEvent): void; /** * Called when a key is released on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onKeyUp(shape: EShape, runtime: EShapeRuntime, e: KeyboardEvent): void; /** * Called when a shape get focused. * * @param shape a shape * @param runtime a runtime */ onFocus(shape: EShape, runtime: EShapeRuntime): void; /** * Called when a shape losees a focuse. * * @param shape a shape * @param runtime a runtime */ onBlur(shape: EShape, runtime: EShapeRuntime): void; /** * Called when a shape is right-clicked. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onRightClick(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a secondary button is about to be pressed on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onRightDowning(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a secondary button gets pressed on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onRightDown(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a secondary button gets released on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onRightUp(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a secondary button get released outside of a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onRightUpOutside(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a secondary button is pressed on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onRightPressed(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a secondary button is released on a shape. * * @param shape a shape * @param runtime a runtime * @param e an event object */ onRightUnpressed(shape: EShape, runtime: EShapeRuntime, e: InteractionEvent): void; /** * Called when a shape get rendered. * * @param shape a shape * @param runtime a runtime */ onRender(shape: EShape, runtime: EShapeRuntime, time: number, renderer: Renderer): void; }
C
UTF-8
1,872
2.546875
3
[]
no_license
// vim: nu et ts=8 sts=2 sw=2 typedef struct Environment { SDL_Window* window; SDL_Surface* screen; SDL_Renderer* renderer; PxSz screenSize; int shortDimension; bool isOrientationHorizontal; bool haveJoystick; } Environment; #define dieSDL(FAILED_FUNCTION_NAME) \ die("%s: %s", (FAILED_FUNCTION_NAME), SDL_GetError()); void ResizeWindow(Environment* env) { SDL_GetRendererOutputSize(env->renderer, &env->screenSize.w, &env->screenSize.h); env->isOrientationHorizontal = env->screenSize.w >= env->screenSize.h; env->shortDimension = env->isOrientationHorizontal ? env->screenSize.h : env->screenSize.w; } void InitSDL(Environment* env) { if (0 != SDL_Init(SDL_INIT_VIDEO)) dieSDL("SDL_Init"); env->window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (!env->window) dieSDL("SDL_CreateWindow"); env->screen = SDL_GetWindowSurface(env->window); if (!env->screen) dieSDL("SDL_GetWindowSurface"); // Add flag SDL_RENDERER_PRESENTVSYNC to enable vsync. env->renderer = SDL_CreateRenderer(env->window, -1, SDL_RENDERER_ACCELERATED); if (!env->renderer) dieSDL("SDL_CreateRenderer"); int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) die("IMG_Init: %s", IMG_GetError()); ResizeWindow(env); } SDL_Texture* loadImageAsTexture(Environment* env, const char* path) { SDL_Surface* surface = IMG_Load(path); if (!surface) die("IMG_Load(%s): %s", path, IMG_GetError()); SDL_Texture* texture = SDL_CreateTextureFromSurface(env->renderer, surface); if (!texture) dieSDL("SDL_CreateTextureFromSurface"); SDL_FreeSurface(surface); return texture; } Uint64 GetTime() { return (Uint64)TIMER_MILLISECOND_MULTIPLIER * SDL_GetTicks(); }
PHP
UTF-8
1,416
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Imports; use App\Models\Cliente; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithHeadingRow; use Maatwebsite\Excel\Concerns\WithValidation; use PhpOffice\PhpSpreadsheet\Shared\Date; class ClientesImport implements ToModel,WithValidation { public function model(array $row) { // $inicio = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[7]); // $final = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[8]); return new Cliente([ 'ced'=>$row[0], 'nombre'=>$row[1], 'telefono'=>$row[2], 'correo'=>$row[3], 'municipio'=>$row[4], 'calle'=>$row[5], 'estrato'=>$row[6], // 'fecha_inicio'=>$row[7], // 'fecha_final'=>$row[8], 'tipo_servicio'=>$row[7], 'reuso'=>$row[8], 'tecnologia'=>$row[9], 'canon'=>$row[10], 'estado'=>$row[11], ]); } public function rules(): array { return [ '0'=>['unique:clientes,ced'], '3'=>['unique:clientes,correo'], '5'=>['required'], '6'=>['required'], '7'=>['required'], '8'=>['required'], ]; } }
Markdown
UTF-8
474
2.515625
3
[]
no_license
# Summary * [Introduction](README.md) * [环境心理学:为什么 是什么 怎么做](chapter1.md) * [自然与人类本性](chapter2.md) * [环境知觉和环境认知](chapter3.md) * [脑神经](chapter3.1.md) * [环境——行为关系理论](chapter4.md) * [噪声](chapter5.md) * [声音传播原理相关](chapter5.1.md) * [天气、气候和行为](chapter6.md) * [灾难、有毒物质及污染](chapter7.md) * [个人空间与领地性](chapter8.md)
C
UTF-8
844
3.46875
3
[]
no_license
#include <iostream> using namespace std; int max(int a, int b, int c); int max4(int a, int b, int c, int d); int main() { int a, b, c ,d; cin>>a>>b>>c>>d; //max(a, b, c); cout<<max4( a, b, c, d) <<endl; return 0; } int max4(int a, int b, int c, int d) { int tmp = max(a, b, c); if(tmp>d) return tmp; else return d; } int max(int a, int b, int c) { if (a>b) { if(a>c) { return a; } else { return c; } } else { if(b<c) return c; else return b; } /*if(a>b && a<c) { return c; } else { if (a>c) { return a; } else { return b; } return a; } }
C++
UTF-8
344
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; long long n, m; long long g( long long x ){ if( x % 2 ) return x * ( ( x + 1 ) / 2 ); return ( x / 2 ) * ( x + 1 ); } int main( ){ cin >> n >> m; cout << ( g( ( n / m ) - 1 ) * ( m - ( n % m ) ) ) + ( g( ( ( n + m - 1 ) / m ) - 1 ) ) * ( n % m ) << " " << g( n - m ); return 0; }
C#
UTF-8
2,025
2.703125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Characters { Vegan, DJ, Master, Tiger, Hagbard, Olle, Asp, Fitkin } [System.Serializable] public class CharacterData { [SerializeField] Characters m_type; public Characters Type { get { return m_type; } } [SerializeField] private string m_name = ""; public string Name { get{ return m_name; } } // Level of intimacy 0 <= x <= 5 [SerializeField] private float m_intimacyLevel = 0f; public int IntimacyLevel { get{ return (int)m_intimacyLevel; } } [SerializeField] private GameObject m_charPrefab = null; public GameObject CharacterPrefab { get{ return m_charPrefab; } } [SerializeField] private AudioClip[] m_vocals; public AudioClip[] Vocals { get { return m_vocals; } } [SerializeField] private int m_talkRate = 4; public int TalkRate { get { return m_talkRate; } } /// <summary> /// Init character data. /// </summary> /// <param name="Intimacy">Clamped to 0f >= x >= 5f</param></param> /// <param name="prefab">Prefab.</param> public CharacterData(string name, float intimacy, GameObject prefab) { m_name = name; m_intimacyLevel = (intimacy < 0 ? 0 : intimacy) > 5 ? 5 : intimacy; m_charPrefab = prefab; } /// <summary> /// Empty constuctor. /// </summary> public CharacterData(){} public void InstantiateCharacter() { GameObject tmp = GameObject.Instantiate(m_charPrefab); tmp.SendMessage("LoadCharData", this); } /// <summary> /// Updates the intimacy. /// </summary> /// <param name="Intimacy">Clamped to 0 >= x >= 5</param> public void AddIntimacy(float intimacy) { m_intimacyLevel += intimacy; // m_intimacyLevel = (m_intimacyLevel < 0f ? 0f : m_intimacyLevel) > 5f ? 5f : m_intimacyLevel; } }
PHP
UTF-8
1,074
2.578125
3
[]
no_license
<?php require '../../controllers/customerController.php'; $key=$_GET["key"]; $customers = searchCustomer($key); ?> <table> <?php foreach($customers as $customer) { echo "<tr>"; echo "<td>".$customer["c_id"]."</td>"; echo "<td>".$customer["name"]."</td>"; echo "<td>".$customer["dob"]."</td>"; echo "<td>".$customer["age"]."</td>"; echo "<td>".$customer["mobile"]."</td>"; echo "<td>".$customer["address"]."</td>"; echo "<td>".$customer["email"]."</td>"; echo "<td>".$customer["gender"]."</td>"; echo "</tr>"; } ?> </table>
Java
UTF-8
6,307
2.625
3
[]
no_license
package com.bsb.hike.ios.tests.groupChat; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.bsb.hike.ios.base.AppiumCapabilities; import com.bsb.hike.ios.library.HikeLibrary; import com.bsb.hike.ios.screens.GroupContactSelectionScreen; import com.bsb.hike.ios.screens.GroupThreadScreen; import com.bsb.hike.ios.screens.HomeScreenMenu; import com.bsb.hike.ios.screens.NewGroupScreen; public class DeletingMessageInGroup extends HikeLibrary { AppiumCapabilities appium = new AppiumCapabilities(); HomeScreenMenu homeScreenMenuObj = new HomeScreenMenu(); @BeforeTest public void setUp() throws Exception{ appium.setUp(); //driver.launchApp(); } @AfterClass public void tearDown() throws Exception{ driver.quit(); } /*@Test public void test001_DeleteAllExistingChats() { Reporter.log(iOSAutomation_DESCRIPTION+ " : 1. Iterate over all chats. \n" + "2. Delete all chats. \n" + "3. Ensure 'please make my day' text is visible.\n"); homeScreenMenuObj.deleteAllExistingChats(); }*/ @Test(priority=1) public void test002_ClearChatFromInsideChat() { Reporter.log(iOSAutomation_DESCRIPTION+ " : 1. Go to a group. \n" + "2. Send some messages. \n" + "3. Clear messages from options.\n" + "4. Ensure that the chat thread is empty."); String textToEnter = "This is a random text to clear."; String groupName = "IOS automation group"; //create a new group NewGroupScreen newGroupObj = homeScreenMenuObj.clickOnNewGroup_Lbl(); newGroupObj.typeGroupName(groupName); GroupContactSelectionScreen contactSelectionScreenObj = newGroupObj.clickOnNextButton(); contactSelectionScreenObj.searchForAContactWithoutClear(HIKE_CONTACT_NAME); contactSelectionScreenObj.selectFirstContactInResults(); contactSelectionScreenObj.searchForAContactWithoutClear(HIKE_CONTACT_NAME_1); contactSelectionScreenObj.selectFirstContactInResults(); GroupThreadScreen groupThreadObj = contactSelectionScreenObj.clickOnDoneButton(groupName); groupThreadObj.sendMessage(textToEnter); groupThreadObj.sendMessage(textToEnter); groupThreadObj.sendMessage(textToEnter); //cancel clear chat and assert groupThreadObj.clearChatCancel(); Assert.assertEquals(groupThreadObj.getLastMessage(), textToEnter, "All messages were cleared when they should not have."); //clear chat groupThreadObj.clearChat(); Assert.assertTrue(groupThreadObj.getLastMessage().startsWith("Group chat with"), "All messages were not cleared."); } @Test(priority=2) public void test003_ValidateOptions() { Reporter.log(iOSAutomation_DESCRIPTION+" : 1. Start chat with any existing group. \n" + "2. Long press on any message. \n" + "3. Validate if options are populated - copy, delete, forward. \n"); String textToForward = "This is a random string to delete"; String groupName = "IOS Automation group"; goToHome(); GroupThreadScreen groupThreadObj = (GroupThreadScreen) homeScreenMenuObj.goToSpecificUserThread(groupName, true); groupThreadObj.sendMessage(textToForward); groupThreadObj.longPressOnLastMessage(); //assert presence of copy, delete, forward buttons Assert.assertTrue(isElementPresent(groupThreadObj.getCopyMessage()), "Copy message did not appear after long press on element"); Assert.assertTrue(isElementPresent(groupThreadObj.getDeleteMessage()), "Delete message did not appear after long press on element"); Assert.assertTrue(isElementPresent(groupThreadObj.getForwardMessage()), "Forward message did not appear after long press on element"); } @Test(priority=3) public void test004_DeletingSingleMessageAndValidate() { Reporter.log(iOSAutomation_DESCRIPTION+ " : 1. Go to a group. \n" + "2. Send some messages. \n" + "3. Clear single message.\n" + "4. Go back and verify that last message deleted."); int counter = 1; String textToEnter = "Send message"; String groupName = "IOS Automation group"; goToHome(); GroupThreadScreen groupThreadObj = (GroupThreadScreen) homeScreenMenuObj.goToSpecificUserThread(groupName, true); groupThreadObj.sendMessage(textToEnter + counter++); groupThreadObj.sendMessage(textToEnter + counter++); groupThreadObj.sendMessage(textToEnter + counter); goToHome(); String currentLastMessage = homeScreenMenuObj.getLastMessageInView(groupThreadObj.getGroupName()); Assert.assertEquals(currentLastMessage, "You: " + textToEnter + counter, "Last message in the chat thread does not match the one in home screen preview"); //go to chat and delete last message groupThreadObj = (GroupThreadScreen) homeScreenMenuObj.goToSpecificUserThread(groupThreadObj.getGroupName(), true); groupThreadObj.deleteLastMessage(); currentLastMessage = groupThreadObj.getLastMessage(); goToHome(); //fetch user's last message sent String updatedLastMessage = homeScreenMenuObj.getLastMessageInView(groupThreadObj.getGroupName()); Assert.assertEquals(updatedLastMessage, "You: " + currentLastMessage, "Last message in the chat thread does not match the one in home screen preview"); } @Test(priority=4) public void test005_ValidateStickerAsLastMessage() { Reporter.log(iOSAutomation_DESCRIPTION+ " : 1. Go to a chat. \n" + "2. Send a sticker. \n" + "3. Verify 'Via' share button.\n" + "4. Delete and verify tha message preview is changed on home screen."); String groupName = "IOS Automation group"; goToHome(); GroupThreadScreen groupThreadObj = (GroupThreadScreen) homeScreenMenuObj.goToSpecificUserThread(groupName, true); groupThreadObj.sendSticker(); groupThreadObj.longPressOnLastMessage(); Assert.assertTrue(isElementPresent(groupThreadObj.getShareViaMessage()), "Share via option did not appear after long press on sticker"); groupThreadObj.deleteLastMessage(); String lastMessageInThread = groupThreadObj.getLastMessage(); goToHome(); String messageInHomeView = homeScreenMenuObj.getLastMessageInView(groupThreadObj.getGroupName()); //TODO will fail if sticker is still a last message Assert.assertEquals(messageInHomeView, "You: " + lastMessageInThread, "Message in home view did not get updated after deleting sticker"); } }
Java
UTF-8
445
1.695313
2
[]
no_license
package com.example.przelewy24.controller; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.springframework.lang.NonNull; @AllArgsConstructor @Getter @Setter public class ClientTransactionRequest { @NonNull private int amount; @NonNull private String currency; @NonNull private String description; @NonNull private String email; @NonNull private String client; }
C
ISO-8859-1
544
4.3125
4
[]
no_license
#include <stdio.h> /* 8. Faa uma funo que receba como parmetro um nmero inteiro positivo e retorne o fatorial do mesmo. */ int fat(int N) { if(N==1||N==0) { return 1; } else { return N*fat(N-1); } } int fatorial(int N) { int i,fat=1; for(i=N;i>=1;i--) { fat*=i; } return fat; } int main() { printf("Fatorial: %i\n", fat(3)); printf("Fatorial: %i\n", fat(4)); printf("Fatorial: %i\n", fat(5)); printf("Fatorial: %i\n", fat(6)); return 0; }
Markdown
UTF-8
855
2.8125
3
[]
no_license
### Hi there 👋 My name is Oleg, and I'm a software geek 👨‍💻 🔭 I’m currently working on: - The biggest container registry in the world 🐳 https://hub.docker.com - Docker Hub, Docker Desktop & Docker CLI 💬 Ask me about: - Docker, Containers, Kubernetes & Go / Golang 📫 How to reach me: - I'm on [LinkedIn](https://www.linkedin.com/in/ob1dev/) - Find me on Twitter at [@ob1dev](https://twitter.com/ob1dev) <!-- **ob1dev/ob1dev** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. Here are some ideas to get you started: - 🔭 I’m currently working on ... - 🌱 I’m currently learning ... - 👯 I’m looking to collaborate on ... - 🤔 I’m looking for help with ... - 💬 Ask me about ... - 📫 How to reach me: ... - 😄 Pronouns: ... - ⚡ Fun fact: ... -->
Java
UTF-8
82
1.75
2
[]
no_license
package ru.gasheva.client; public interface PhotoObserver { void update(); }
C++
UTF-8
1,883
3.328125
3
[]
no_license
#include "Rook.h" // Constructor Rook::Rook(char type) : Piece(type) { } // Destructor Rook::~Rook() { } /* Function will get coordinates and will check if this move is valid by Rook's possible moves. Input: int (&coordinates)[4] --> The 4 coordinates: (x, y) current, (x, y) target. Output: bool flag --> true if the move is valid, false if not. */ bool Rook::isValidStep(int(&coordinates)[AMOUNT_OF_COORD]) const { int changedCoord = 0, lastCoordToCheck = 0; if (coordinates[X_CURRENT] != coordinates[X_TARGET] && coordinates[Y_CURRENT] != coordinates[Y_TARGET]) { return false; } if (coordinates[X_CURRENT] != coordinates[X_TARGET]) { if (coordinates[X_CURRENT] < coordinates[X_TARGET]) { changedCoord = coordinates[X_CURRENT] + 1; lastCoordToCheck = coordinates[X_TARGET]; } else { changedCoord = coordinates[X_TARGET] + 1; lastCoordToCheck = coordinates[X_CURRENT]; } while (changedCoord != lastCoordToCheck) { if (Board::_chessBoard[changedCoord][coordinates[Y_CURRENT]] != NULL) { return false; } changedCoord++; } } else { if (coordinates[Y_CURRENT] < coordinates[Y_TARGET]) { changedCoord = coordinates[Y_CURRENT] + 1; lastCoordToCheck = coordinates[Y_TARGET]; } else { changedCoord = coordinates[Y_TARGET] + 1; lastCoordToCheck = coordinates[Y_CURRENT]; } while (changedCoord != lastCoordToCheck) { if (Board::_chessBoard[coordinates[X_CURRENT]][changedCoord] != NULL) { return false; } changedCoord++; } } return true; }
Python
UTF-8
550
3.421875
3
[]
no_license
# -*- coding: utf-8 -*- ''' Created on 06/12/2012 @author: Maria ''' import tkinter as tk def result(): print( " this sum of 2+2 is : ", 2+2) mainWindow = tk.Tk() mainWindow = root.tk("Password Generator") win = tk.Frame() win.pack() label1 = tk.Label( win, text = "click New to create a new password.").pack(side=tk.TOP) button1 = tk.Button( win, text = "New", command = result, cursor="plus").pack(side=tk.LEFT) button2 = tk.Button( win, text = "Quit", command = win.quit).pack(side=tk.RIGHT) win.mainloop()
Java
UTF-8
6,177
2.4375
2
[]
no_license
/** * Copyright (C) 2010 Leon Blakey <lord.quackstar at gmail.com> * * This file is part of PircBotX. * * PircBotX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PircBotX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PircBotX. If not, see <http://www.gnu.org/licenses/>. */ package org.pircbotx.hooks; import java.lang.reflect.Method; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.commons.lang3.StringUtils; import org.pircbotx.PircBotX; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.VoiceEvent; import org.pircbotx.hooks.types.GenericMessageEvent; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * * @author Leon Blakey <lord.quackstar at gmail.com> */ public class ListenerAdapterTest { /** * Makes sure adapter uses all events * @throws Exception */ @Test(description = "Verify ListenerAdapter supports all events") public void eventImplementTest() throws Exception { //Get all file names List<String> classFiles = getClasses(VoiceEvent.class); //Get all events ListenerAdapter uses List<String> classMethods = new ArrayList(); for (Method curMethod : ListenerAdapter.class.getDeclaredMethods()) { assertEquals(curMethod.getParameterTypes().length, 1, "More than one parameter in method " + curMethod); Class<?> curClass = curMethod.getParameterTypes()[0]; if (!curClass.isInterface()) classMethods.add(curClass.getSimpleName()); } //Subtract the differences classFiles.removeAll(classMethods); String leftOver = StringUtils.join(classFiles.toArray(), ", "); assertEquals(classFiles.size(), 0, "ListenerAdapter does not implement " + leftOver); } @Test(description = "Verify ListenerAdapter supports all event interfaces") public void interfaceImplementTest() throws IOException { List<String> classFiles = getClasses(GenericMessageEvent.class); //Get all interfaces ListenerAdapter uses List<String> classMethods = new ArrayList(); for (Method curMethod : ListenerAdapter.class.getDeclaredMethods()) { assertEquals(curMethod.getParameterTypes().length, 1, "More than one parameter in method " + curMethod); Class<?> curClass = curMethod.getParameterTypes()[0]; if (curClass.isInterface()) classMethods.add(curClass.getSimpleName()); } //Subtract the differences classFiles.remove("GenericEvent"); classFiles.removeAll(classMethods); String leftOver = StringUtils.join(classFiles.toArray(), ", "); assertEquals(classFiles.size(), 0, "ListenerAdapter does not implement " + leftOver); } @Test(description = "Verify all methods in ListenerAdapter throw an exception") public void throwsExceptionTest() { for (Method curMethod : ListenerAdapter.class.getDeclaredMethods()) { Class<?>[] exceptions = curMethod.getExceptionTypes(); assertEquals(exceptions.length, 1, "Method " + curMethod + " in ListenerManager doesn't throw an exception or thows too many"); assertEquals(exceptions[0], Exception.class, "Method " + curMethod + " in ListenerManager doesn't throw the right exception"); } } @Test(description = "Do an actual test with a sample ListenerAdapter") public void usabilityTest() throws Exception { TestListenerAdapter listener = new TestListenerAdapter(); PircBotX bot = new PircBotX(); //Test if onMessage got called listener.onEvent(new MessageEvent(bot, null, null, null)); assertTrue(listener.isCalled(), "onMessage wasn't called on MessageEvent"); //Test if onGenericChannelMode (interface) got called listener.setCalled(false); listener.onEvent(new MessageEvent(bot, null, null, null)); assertTrue(listener.isCalled(), "onMessage wasn't called on MessageEvent"); } protected static List<String> getClasses(Class<?> clazz) throws IOException { String sep = System.getProperty("file.separator"); //Since dumping path in getResources() fails, extract path from root Enumeration<URL> rootResources = clazz.getClassLoader().getResources(""); assertNotNull(rootResources, "Voice class resources are null"); assertEquals(rootResources.hasMoreElements(), true, "No voice class resources"); File root = new File(rootResources.nextElement().getFile().replace("%20", " ")).getParentFile(); assertTrue(root.exists(), "Root dir (" + root + ") doesn't exist"); //Get root directory as a file File dir = new File(root, sep + "classes" + sep + (clazz.getPackage().getName().replace(".", sep)) + sep); assertNotNull(dir, "Fetched Event directory is null"); assertTrue(dir.exists(), "Event directory doesn't exist"); assertTrue(dir.isDirectory(), "Event directory isn't a directory"); //Get classes in directory List<String> classFiles = new ArrayList(); assertTrue(dir.listFiles().length > 0, "Event directory is empty"); for (File clazzFile : dir.listFiles()) //If its a directory, its not a .class, or its a subclass, ignore if (clazzFile.isFile() && clazzFile.getName().contains("class") && !clazzFile.getName().contains("$")) classFiles.add(clazzFile.getName().split("\\.")[0]); return classFiles; } @Data @EqualsAndHashCode(callSuper = false) protected class TestListenerAdapter extends ListenerAdapter { protected boolean called = false; @Override public void onGenericMessage(GenericMessageEvent event) throws Exception { called = true; } @Override public void onMessage(MessageEvent event) throws Exception { called = true; } } }
Python
UTF-8
3,949
3.6875
4
[]
no_license
# Robin Camille Davis # February 28, 2014 # Methods II # Homework 1 # Section B: Open-ended programming problem # This script compares one text to another text from nltk.book import * from math import log import nltk.data sentsplitter = nltk.data.load('tokenizers/punkt/english.pickle') # # Following compares word frequency distributions and returns # the average difference in word frequencies and number of words # not shared for sum of all words in both texts. # def getfreq(text): """Returns frequency distribution of a text, from NLTK""" fd = FreqDist(text) return fd def lowertext(text): """Returns a text in all lowercase""" lowtext = [] for w in text: w = w.lower() lowtext.append(w) return lowtext def comparefreq(textA, textB): """Returns average difference in word frequencies and number of words per text, for two texs""" textA = lowertext(textA) textB = lowertext(textB) fdA = getfreq(textA) fdB = getfreq(textB) freqdiffs = [] notshared = [] #not used in final function, but left it in: words in A not B, or B not A for s in fdA: if s in fdB: freqdiff = abs((fdA.freq(s) - (fdB.freq(s)))) #w.write(s + '\t' + str(freqdiff) + '\n') freqdiffs.append(freqdiff) else: notshared.append(s) for s in fdB: if s not in fdA: notshared.append(s) notshareddec = len(notshared) / float(len(textA) + len(textB)) #number of words not shared, as a decimal freqsum = 0 for i in freqdiffs: freqsum = freqsum + i freqavg = freqsum / len(freqdiffs) #average difference of frequencies return freqavg # # Following compares average word length. # def avgwordlength(text): """Returns average word length in a text (float)""" lowtext = lowertext(text) textfreq = getfreq(lowtext) words = textfreq.keys() #dedupe totalchars = 0 for s in words: #may include some punctuation totalchars = totalchars + len(s) textlength = len(words) return totalchars / float(textlength) def compareavgwl(textA, textB): """Returns difference in average word length in a text""" wlA = avgwordlength(textA) wlB = avgwordlength(textB) return abs(wlA - wlB) # # Following compares average sentence length. # def avgsentlength(text): """Returns average sentence length in a text, in chars (float)""" textstring = ' '.join(text) sents = sentsplitter.tokenize(textstring) totalsentlength = 0 for s in sents: totalsentlength = totalsentlength + len(s) #length in chars numsents = len(sents) return totalsentlength / float(numsents) def compareavgsl(textA, textB): """Returns difference in average sentence length in a text""" slA = avgsentlength(textA) slB = avgsentlength(textB) return abs(slA - slB) # # Following combines word frequency difference, average word length difference, # and average sentence length difference into one similarity score. # A pair of texts that are exactly the same has a score of zero. # def scoresim(textA, textB): wf = comparefreq(textA, textB) * 10000 #heavy weight given to word freq wl = compareavgwl(textA, textB) slraw = compareavgsl(textA, textB) sl = log(slraw, 10) #decrease weight (log base 10) score = wf + wl + sl return score # # Find similarity scores between texts # textset = [text1, text2, text3, text4, text5, text6, text7, text8, text9] pairs = [] table = open('table.csv','w') table.write('Text1,Text2,Score\n') for t in textset: for t2 in textset: if t is not t2: if [t,t2] not in pairs: #dedupe if [t2,t] not in pairs: pairs.append([t,t2]) print t, t2 table.write(str(t) + ',' + str(t2) + ',' + str(scoresim(t,t2)) + '\n') table.close() print 'Finished file: ', table
Shell
UTF-8
549
2.828125
3
[ "MIT" ]
permissive
# 通过 readlink 获取绝对路径,再取出目录 work_path=$(dirname $(readlink -f $0)) systemctl stop saynice-api systemctl stop saynice-web mv $work_path/saynice-api-amd64-linux-v1 /usr/local/bin/saynice-api mv $work_path/saynice-web-amd64-linux /usr/local/bin/saynice-web mv $work_path/saynice-api.service /lib/systemd/system mv $work_path/saynice-web.service /lib/systemd/system rm -rf $work_path systemctl daemon-reload systemctl enable saynice-api systemctl enable saynice-web systemctl start saynice-api systemctl start saynice-web
Java
UTF-8
3,080
2.234375
2
[]
no_license
package com.wtd.ddd.controller.study; import com.wtd.ddd.controller.ApiResult; import com.wtd.ddd.model.commons.Id; import com.wtd.ddd.model.study.Apply; import com.wtd.ddd.model.study.Post; import com.wtd.ddd.model.study.StudyCode; import com.wtd.ddd.service.StudyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import static com.wtd.ddd.controller.ApiResult.OK; /** * Created By mand2 on 2020-10-24. */ @RestController @RequestMapping("api/study") public class StudyController { private final StudyService studyService; @Autowired public StudyController(StudyService studyService) { this.studyService = studyService; } //모집글 쓰기 @PostMapping("/post") public ApiResult<Post> posting(@RequestBody StudyPostRequest postRequest) { return OK(studyService.writePost(postRequest.newPost())); } //모집글 수정 @PutMapping("/post/{postSeq}") public ApiResult<Post> editPost(@RequestBody StudyPostRequest postRequest, @PathVariable Long postSeq) { return OK(studyService.modifyPost(postRequest.newPost(postSeq))); } //모집글 삭제 @DeleteMapping("/post/{postSeq}") public ApiResult<Id<Post, Long>> deletePost(@RequestBody StudyPostRequest postRequest, @PathVariable Long postSeq) { return OK(studyService.deletePost(postRequest.newPost(postSeq))); } //모집글 다건조회-리스트 @GetMapping("/post") public ApiResult<StudyPostResponse> getList(@ModelAttribute Pageable pageable, @RequestParam(required = false, defaultValue = "") String title, @RequestParam(required = false, defaultValue = "") String placeSeq, @RequestParam(required = false, defaultValue = "") String statusSeq) { Long offset = pageable.offset(); int limit = pageable.limit(); return OK(studyService.posts( title, Id.of(StudyCode.class, placeSeq), Id.of(StudyCode.class, statusSeq), offset, limit)); } //모집글 단건조회-자세히보기 @GetMapping("/post/{postSeq}") public ApiResult<StudyPostResponse> view(@PathVariable Long postSeq) { return OK(studyService.findPost(Id.of(Post.class, postSeq))); } //지원하기 @PostMapping("/apply/{postSeq}") public ApiResult<Apply> applying(@RequestBody StudyPostRequest postRequest, @PathVariable Long postSeq) { return OK(studyService.apply(postRequest.newApply(postSeq))); } //지원 결과안내 (수락/거절) 혹은 지원취소 @PutMapping("/apply/status/{applySeq}") public ApiResult<Apply> changeApplyStatus(@PathVariable Long applySeq, @RequestBody StudyPostRequest postRequest){ return OK(studyService.applyModify( Id.of(Apply.class, applySeq), Id.of(StudyCode.class, postRequest.getApplyStatus()))); } }
TypeScript
UTF-8
1,244
2.578125
3
[ "MIT" ]
permissive
import { Get, Post, Res, Param, Body, HttpCode, Controller, Patch, Put, Delete } from '@nestjs/common'; import { PostsService } from '../../service/posts/posts.service'; import { Posts } from '../../model/entity/posts.entity'; @Controller('posts') export class PostsController { constructor(private readonly postService: PostsService) { } @Get() async findAll(@Res() res) { res.send(await this.postService.findAll()); } @Post() async createPost(@Body() post: Posts) { // console.log('--->', post); const createdPost = await this.postService.create(post); return { message: 'post created succesfully', data: createdPost, }; } // find single post by ID @Get(':id') async getById(@Param() params: any) { return this.postService.findByID(parseInt(params.id, 10)); } // Update post @Put(':id') async updateById(@Body() post: Posts, @Res() res, @Param('id') id: number) { await this.postService.updateData(id, post); return res.json(await { message: 'post updated succesfully' }); } // Delete @Delete(':id') async remove(@Param('id') id, @Res() res) { await this.postService.delete(id); return res.json(await { message: 'post deleted succesfully' }); } }
SQL
UTF-8
460
3.40625
3
[]
no_license
-- -- @lc app=leetcode.cn id=180 lang=mysql -- -- [180] 连续出现的数字 -- # Write your MySQL query statement below select distinct l1.Num as ConsecutiveNums from Logs l1 join Logs l2 on l1.Id = l2.Id-1 join Logs l3 on l1.Id = l3.Id-2 where l1.Num = l2.Num and l1.Num = l3.Num; -- select distinct l1.Num as ConsecutiveNums -- from Logs l1, Logs l2, Logs l3 -- where l1.Id = l2.Id-1 -- and l1.Id = l3.Id-2 -- and l1.Num = l2.Num -- and l1.Num = l3.Num;
JavaScript
UTF-8
313
2.6875
3
[]
no_license
const bcrypt = require("bcrypt"); const saltRounds = 11; module.exports = { async generate(password) { return await bcrypt.hash(password, saltRounds).then(hash => hash); }, async compare(password, passwordHash) { const match = await bcrypt.compare(password, passwordHash); return match; } }
Go
UTF-8
9,536
2.640625
3
[ "Apache-2.0" ]
permissive
/* * Cadence - The resource-oriented smart contract programming language * * Copyright 2019-2020 Dapper Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package checker import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/onflow/cadence/runtime/sema" ) func TestCheckFunctionConditions(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int) { pre { x != 0 } post { x == 0 } } `) require.NoError(t, err) } func TestCheckInvalidFunctionPreConditionReference(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int) { pre { y == 0 } post { z == 0 } } `) errs := ExpectCheckerErrors(t, err, 2) assert.IsType(t, &sema.NotDeclaredError{}, errs[0]) assert.Equal(t, "y", errs[0].(*sema.NotDeclaredError).Name, ) assert.IsType(t, &sema.NotDeclaredError{}, errs[1]) assert.Equal(t, "z", errs[1].(*sema.NotDeclaredError).Name, ) } func TestCheckInvalidFunctionNonBoolCondition(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int) { pre { 1 } post { 2 } } `) errs := ExpectCheckerErrors(t, err, 2) assert.IsType(t, &sema.TypeMismatchError{}, errs[0]) assert.IsType(t, &sema.TypeMismatchError{}, errs[1]) } func TestCheckFunctionPostConditionWithBefore(t *testing.T) { t.Parallel() checker, err := ParseAndCheck(t, ` fun test(x: Int) { post { before(x) != 0 } } `) require.NoError(t, err) assert.Len(t, checker.Elaboration.VariableDeclarationValueTypes, 1) assert.Len(t, checker.Elaboration.VariableDeclarationTargetTypes, 1) } func TestCheckFunctionPostConditionWithBeforeNotDeclaredUse(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test() { post { before(x) != 0 } } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.NotDeclaredError{}, errs[0]) } func TestCheckInvalidFunctionPostConditionWithBeforeAndNoArgument(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int) { post { before() != 0 } } `) errs := ExpectCheckerErrors(t, err, 2) assert.IsType(t, &sema.ArgumentCountError{}, errs[0]) assert.IsType(t, &sema.TypeParameterTypeInferenceError{}, errs[1]) } func TestCheckInvalidFunctionPreConditionWithBefore(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int) { pre { before(x) != 0 } } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.NotDeclaredError{}, errs[0]) assert.Equal(t, "before", errs[0].(*sema.NotDeclaredError).Name, ) } func TestCheckInvalidFunctionWithBeforeVariableAndPostConditionWithBefore(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int) { post { before(x) == 0 } let before = 0 } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.RedeclarationError{}, errs[0]) } func TestCheckFunctionWithBeforeVariable(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int) { let before = 0 } `) require.NoError(t, err) } func TestCheckFunctionPostCondition(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: Int): Int { post { y == 0 } let y = x return y } `) require.NoError(t, err) } func TestCheckInvalidFunctionPreConditionWithResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(): Int { pre { result == 0 } return 0 } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.NotDeclaredError{}, errs[0]) assert.Equal(t, "result", errs[0].(*sema.NotDeclaredError).Name, ) } func TestCheckInvalidFunctionPostConditionWithResultWrongType(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(): Int { post { result == true } return 0 } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.InvalidBinaryOperandsError{}, errs[0]) } func TestCheckFunctionPostConditionWithResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(): Int { post { result == 0 } return 0 } `) require.NoError(t, err) } func TestCheckInvalidFunctionPostConditionWithResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test() { post { result == 0 } } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.NotDeclaredError{}, errs[0]) assert.Equal(t, "result", errs[0].(*sema.NotDeclaredError).Name, ) } func TestCheckFunctionWithoutReturnTypeAndLocalResultAndPostConditionWithResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test() { post { result == 0 } let result = 0 } `) require.NoError(t, err) } func TestCheckFunctionWithoutReturnTypeAndResultParameterAndPostConditionWithResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(result: Int) { post { result == 0 } } `) require.NoError(t, err) } func TestCheckInvalidFunctionWithReturnTypeAndLocalResultAndPostConditionWithResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(): Int { post { result == 2 } let result = 1 return result * 2 } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.RedeclarationError{}, errs[0]) } func TestCheckInvalidFunctionWithReturnTypeAndResultParameterAndPostConditionWithResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(result: Int): Int { post { result == 2 } return result * 2 } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.RedeclarationError{}, errs[0]) } func TestCheckInvalidFunctionPostConditionWithFunction(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test() { post { (fun (): Int { return 2 })() == 2 } } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.FunctionExpressionInConditionError{}, errs[0]) } func TestCheckFunctionPostConditionWithMessageUsingStringLiteral(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test() { post { 1 == 2: "nope" } } `) require.NoError(t, err) } func TestCheckInvalidFunctionPostConditionWithMessageUsingBooleanLiteral(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test() { post { 1 == 2: true } } `) errs := ExpectCheckerErrors(t, err, 1) assert.IsType(t, &sema.TypeMismatchError{}, errs[0]) } func TestCheckFunctionPostConditionWithMessageUsingResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(): String { post { 1 == 2: result } return "" } `) require.NoError(t, err) } func TestCheckFunctionPostConditionWithMessageUsingBefore(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: String) { post { 1 == 2: before(x) } } `) require.NoError(t, err) } func TestCheckFunctionPostConditionWithMessageUsingParameter(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` fun test(x: String) { post { 1 == 2: x } } `) require.NoError(t, err) } func TestCheckFunctionWithPostConditionAndResourceResult(t *testing.T) { t.Parallel() _, err := ParseAndCheck(t, ` resource R {} resource Container { let resources: @{String: R} init() { self.resources <- {"original": <-create R()} } fun withdraw(): @R { post { self.add(<-result) } return <- self.resources.remove(key: "original")! } fun add(_ r: @R): Bool { self.resources["duplicate"] <-! r return true } destroy() { destroy self.resources } } `) errs := ExpectCheckerErrors(t, err, 1) require.IsType(t, &sema.InvalidMoveOperationError{}, errs[0]) }
Java
UTF-8
676
1.945313
2
[]
no_license
package com.bawei.caolina201907.contract; import com.bawei.caolina201907.model.HomeModel; import com.bawei.lib_core.base.mvp.BaseModel; import com.bawei.lib_core.base.mvp.BasePresenter; import com.bawei.lib_core.base.mvp.BaseView; public interface HomeContract { abstract class HomePresenter extends BasePresenter<IHomeModel,IHomeView> { @Override public IHomeModel getModel() { return new HomeModel(); } public abstract void getHome(); } interface IHomeModel extends BaseModel { void getHome(); } interface IHomeView extends BaseView { void sucess(String result); } }
Python
UTF-8
677
2.796875
3
[]
no_license
import os, requests, zipfile class FileDownloader: def __init__(self, url, path): self.url = url self.path = path def __enter__(self): get_file = requests.get(self.url) with open(self.path, 'wb') as file: file.write(get_file.content) return self def __exit__(self, exc_type, exc_val, exc_tb): pass url_adress = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip' file_path = 'pomoce/euroxref.zip' with FileDownloader(url_adress, file_path) as f: with zipfile.ZipFile(f.path, 'r') as z: a_file = z.namelist()[0] os.chdir('pomoce/') z.extract(a_file, '.', pwd=None)
Java
UTF-8
191
1.820313
2
[]
no_license
package Ex2; public class MainEx2App { public static void main(String[] args) { //Ceamos un objeto de la clase que hemos creado. Peliculas ventana = new Peliculas(); } }
C#
UTF-8
422
2.71875
3
[]
no_license
using System; namespace Cashbox.Data.Entities { public abstract class BaseEntity { public BaseEntity(Guid id) { if (Guid.Equals(id, default(Guid))) throw new ArgumentException("The id can't be the default value."); this.Id = id; } public BaseEntity() { } public Guid Id { get; set; } } }
Markdown
UTF-8
1,314
2.859375
3
[]
no_license
--- title: "Relaunch!" layout: "post" categories: [Jekyll, LESS] --- After nearly a year of inactivity, I have finally returned to my blog. I had neglected it for so long primarily because I don't like Blogger's compose options. After spending so much time on StackOverflow and GitHub, I find Markdown far more convenient than Windows Live Writer or Blogger's compose window, especially when writing about code. I also was never very happy with the design I originally created, and doing raw HTML / CSS design in Blogger is painful. To solve these problems, I just finished porting my blog to [Jekyll](https://jekyllrb.com) on [GitHub Pages](https://pages.github.com/). Now that I can write posts in my [favorite Markdown editor](http://vswebessentials.com/), I hope to end up writing much more. In the next few posts, I'll write about [how I designed the new blog]({% post_url 2013-05-27-about-this-design %}) and how I migrated my existing content. My old blog is still up at [old-blog.slaks.net](http://old-blog.slaks.net). However, all of the content has been migrated to the new one (with the same URLs), so that should not be necessary. If you see anything wrong with the new site, let me know [on Twitter](https://twitter.com/Schabse) or [by email](mailto:Blog@SLaks.net?subject=Blog+Migration+Problem).
C
UTF-8
2,591
3.25
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "common.h" #include "utils.h" #include "pboDataTypes.h" #include "pboExtractor.h" #define VERSION "0.1" static void version(char *myself) { printf("%s version %s (compiled %s)\n", myself, VERSION, __DATE__); } static void help(char *myself) { /* show some help how to use the program */ printf("Usage: %s [options] <file to extract>\n", myself); printf("Options:\n"); printf(" --file <input file> pbo file to read from. (Default is stdin)\n"); printf(" --output <output file> file to save the extracted file to (Default is stdout)\n"); printf(" --help show this help\n"); } int main(int argc, char *argv[]) { int i; char *inFileName; char *outFileName;; char *fileToExtract; FILE *inFile; FILE *outFile; boolean optionReadStdIn; boolean optionWriteStdOut; /* analyze command line */ inFileName = NULL; outFileName = NULL; fileToExtract = NULL; optionReadStdIn = TRUE; optionWriteStdOut = TRUE; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { /* option */ if (strcmp(argv[i], "--file") == 0) { optionReadStdIn = FALSE; i++; if (i < argc) { inFileName = argv[i]; } else { error("no input file"); } } else if (strcmp(argv[i], "--output") == 0) { optionWriteStdOut = FALSE; i++; if (i < argc) { outFileName = argv[i]; } else { error("no output file"); } } else if (strcmp(argv[i], "--help") == 0) { help(argv[0]); exit(0); } else { error("unrecognized option '%s'; try '%s --help'", argv[i], argv[0]); } } else { /* file */ if (fileToExtract != NULL) { error("more than one file name not allowed"); } fileToExtract = argv[i]; } } if (fileToExtract == NULL) { error("fileToExtract is not specified"); } if (optionReadStdIn) { inFile = stdin; } else { inFile = fopen(inFileName, "rb"); } if (inFile == NULL) { error("cannot open input file '%s'", inFileName); } if (optionWriteStdOut) { outFile = stdout; } else { outFile = fopen(outFileName, "wb"); } if (outFile == NULL) { error("cannot open output file '%s'", outFileName); } PboExtractor_ExtractFile(fileToExtract,inFile,outFile); if (!optionReadStdIn) { fclose(inFile); } if (!optionWriteStdOut) { fclose(outFile); } return 0; }
Shell
UTF-8
432
3.296875
3
[]
no_license
#!/bin/bash if [ -z "$1" ]; then echo "call : pmshutdown <workflow>" echo "example: pmshutdown modis.py" exit 1 fi if [ "$CALVALUS_INST" == "" ]; then CALVALUS_INST=.; fi workflow=$(basename ${1%.py}) workflow=${workflow%.sh} if [ ! -e $CALVALUS_INST/${workflow}.pid ]; then echo "missing ${workflow}.pid file in $CALVALUS_INST" ps -elf|grep python exit 1 fi kill $(cat $CALVALUS_INST/${workflow}.pid)
PHP
UTF-8
8,114
2.65625
3
[]
no_license
<?php namespace Admin\Controller; use Think\Controller; class OrderController extends PubController { // public function batAddOrder(){ // $model = M('Order'); // $startTime = strtotime('-50 day');//先获取50天前的时间戮 // for($i=0;$i<500;$i++){ // $startTime += mt_rand(2,8640);//在循环里让时间戮 随机增加 // $data['add_time' ] = date('Y-m-d h:i:s',$startTime);//给下单时间赋值为时间戮转成的时间字符串 // $data['order_sn' ] = date('Ymdhis',$startTime) . rand_str(6);//订单编号 yyyymmddhhssii 14位时间+6位随机字符串 // $data['consignee' ] = '收货人' . $i; // $data['address' ] = '地址' . $i;//地址 // $data['mobile' ] = '158158' . $i;//手机 // $data['total_amount' ] = $i * 2;//订单总价 // $data['for' ] = '来源' . $i;//来源 // $data['pro_name' ] = $this->proArr[mt_rand(0,count($this->proArr) - 1)];//随机产品名称 // echo $model->add($data) , ' '; // } // } public function toExcel(){ import('Org.Util.PHPExcel');//引入PHPExcel类库文件 $excel = new \PHPExcel();//创建PHPExcel对象的实例 $excel->setActiveSheetIndex(0) ->setCellValue('A1','hello') ->setCellValue('B2','b2 1234') ->setCellValue('C1','c1 agasfd') ->setCellValue('D2','d2 gg44'); for ($i=0; $i < 15; $i++) { $excel->getActiveSheet()->setCellValue('E' . ($i + 1),$i); } $excel->getActiveSheet()->setCellValue('A8','a8' . "\r\n" . 'abc中文'); $excel->getActiveSheet()->setCellValue('A8','修改了'); //$excel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1); $excel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);//设置A8可以换行 import('Org.Util.PHPExcel.IOFactory');//引入PHPExcel类库IOFactory文件 $obj = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');//实例化 $obj->save('test.xlsx');//调用保存excel文件 } public function toExcel2(){ //练习:在excel单元格里从1到50显示数字,每个单元格显示一个数字,每行只有前6个单元格显示数字 import('Org.Util.PHPExcel');//引入PHPExcel类库文件 $excel = new \PHPExcel();//创建PHPExcel对象的实例 $excel->setActiveSheetIndex(0); //a b c d e f //1 2 3 4 5 6 //7 8 9 10 11 12 //13 //i 除以 6 的余数是1时,对应字母是a //i 除以 6 的余数是2时,对应字母是b //i 除以 6 的余数是3时,对应字母是c $j = 1; for ($i=1; $i < 51; $i++) { $j = ceil($i / 6); $m = $i % 6; if($m == 0)$m = 6; $excel->getActiveSheet()->setCellValue(chr(($m) + 64) . $j,$i); } import('Org.Util.PHPExcel.IOFactory');//引入PHPExcel类库IOFactory文件 $obj = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');//实例化 $obj->save('test.xlsx');//调用保存excel文件 } protected function _toExcel($model,$map){ //echo '导出excel'; $data = $model->where($map)->order('id')->select(); import('Org.Util.PHPExcel');//引入PHPExcel类库文件 $excel = new \PHPExcel();//创建PHPExcel对象的实例 $excel->setActiveSheetIndex(0);//让第一个表是当前活动表 //$filed数组定义Excel的列名和data里的字段名和关系,以及列宽 $filed = array( 'a' => array('id' , 'ID',8), 'b' => array('order_sn' , '订单号',24),//array('order_sn' 是data里的字段名, '订单号' 是中文字字段名 ,24 是列宽度), 'c' => array('pro_name' , '商品名称',24), 'd' => array('consignee' , '收货人',8), 'e' => array('address' , '地址',30), 'f' => array('mobile' , '手机',14), 'g' => array('total_amount' , '价格',8), 'h' => array('add_time' , '时间',20), 'i' => array('for' , '来源',40), ); //循环写入表头和设置列宽度 foreach ($filed as $k => $v) { $excel->getActiveSheet()->setCellValue($k . 1,$v[1]);//把中文字段名写入表头 $excel->getActiveSheet()->getColumnDimension($k)->setWidth($v[2]);//设置列宽 } //循环把$data里面的数据写入excel里面 foreach ($data as $key => $value) { foreach ($filed as $k => $v) { $excel->getActiveSheet()->setCellValue($k . ($key + 2),$value[$v[0]]); } } import('Org.Util.PHPExcel.IOFactory');//引入PHPExcel类库IOFactory文件 $obj = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');//实例化 $file_name = 'OutExcel/excel_' . date('Ymdhis') . rand_str(6) . '.xlsx';//随机生成一个文件名 //文件名前面的 OutExcel 表示保存导出excel文件的目录,需要在项目根目录下建好OutExcel这个文件夹 $obj->save($file_name);//调用保存excel文件 //跳转到生成的excel文件的URL就会下载这个文件 redirect($file_name, 0); } public function index(){ $time_star = I('get.time_star'); $time_end = I('get.time_end'); $is_out = I('get.is_out','',FILTER_SANITIZE_NUMBER_INT); $pro_name = I('get.pro_name'); $time_star = str_replace('T',' ',$time_star);//HTML5 本地日期时间输入框的vvalue会自动在日期和时间之间加一个T,这里把T替换为空格 $time_end = str_replace('T',' ',$time_end);//HTML5 本地日期时间输入框的vvalue会自动在日期和时间之间加一个T,这里把T替换为空格 $time_star = str_replace('t',' ',$time_star);//有可能有的浏览器会加小写的t这里也替换一次 $time_end = str_replace('t',' ',$time_end);//有可能有的浏览器会加小写的t这里也替换一次 $map = array(); if($pro_name != ''){//判断如果提交来的产品下标不为空,那就增加下面一个模糊搜索条件 $name = '搜索结果'; $map['pro_name'] = array('LIKE','%' . $pro_name . '%'); } if($time_star !== '' || $time_end !== ''){ if($time_star !== '' && $time_end !== ''){ $map['add_time'] = array('between', $time_star . ',' . $time_end); }else{ if($time_star)$map['add_time'] = array('EGT',$time_star); if($time_end) $map['add_time'] = array('ELT',$time_end); } } if($is_out === '0' )$map['is_out' ] = 0; elseif($is_out == 1 )$map['is_out' ] = 1; $orderField = 'id desc'; $model = M('order'); if(I('get.to_excel') == '1'){//如果get传来的to_excel是等于1就执行导出 //实现导出功能的代码写在这里 $this->_toExcel($model,$map);//调用_toExcel方法实现导出excel,传$map条件过去 让index里面获取条件的代码列表页和导出功能共同,不用再写一遍 }else{//如果get传来的to_excel 不是等于1就执行下面的显示普通的列表页面 $count = $model->where($map)->count('id'); $page = new \Think\Page($count,12); $pageHtml = $page->show(); $data = $model->where($map)->limit($page->firstRow.','. $page->listRows)->order($orderField)->select(); $this->assign('data',$data); $this->assign('pageHtml',$pageHtml); $this->assign('count',$count); $this->assign('time_star',I('get.time_star')); $this->assign('time_end',I('get.time_end')); $this->assign('is_out',$is_out); $this->assign('pro_name',$pro_name); $this->display(); } } }
Java
UTF-8
397
1.65625
2
[ "Apache-2.0" ]
permissive
package com.agri.monitor.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class WorkBenchController { @RequestMapping("/workbench") public String index() { return "/workbench"; } @RequestMapping("/dataoverview") public String dataview() { return "/dataoverview"; } }
PHP
UTF-8
1,070
2.703125
3
[]
no_license
<!DOCTYPE html> <html> <head> <title>Add news</title> </head> <body> <form method="post" action="add.php"> <p>Название новости:</p> <input type="text" name="title"> <p>Текст новости:</p> <textarea cols="40" rows="10" name="text"></textarea> <p>Автор новости:</p> <input type="text" name="author"> <!-- <input type="hidden" name="date" value="<?php echo date('Y-m-d') ?>" /> <input type="hidden" name="time" value="<?php echo date('h:i:s') ?>" /> --> <p></p> <input type="submit" name="add" value="add"> </form> <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $title = strip_tags(trim($_POST['title'])); $text = strip_tags(trim($_POST['text'])); $author = strip_tags(trim($_POST['author'])); // $date = $_POST['date']; // $time = $_POST['time']; if ($title && $text && $author) { include_once("db.php"); mysql_query(" INSERT INTO news (title, text, author /*, date, time*/) VALUES ('$title', '$text', '$author'/*, '$date', '$time'*/) "); mysql_close(); } } ?> </body> </html>
Java
UTF-8
1,202
3.125
3
[ "Apache-2.0" ]
permissive
package ru.asemenov.Tracker; /** * Class StartUI решение задачи части 002 урока 4. * @author asemenov * @version 1 */ public class StartUI { /** * this.input. */ private Input input; /** * this.tracker. */ private Tracker tracker; /** * StartUI. * @param input input. * @param tracker tracker. */ public StartUI(Input input, Tracker tracker) { this.input = input; this.tracker = tracker; } /** * Вывод меню. */ public void init() { MenuTracker menu = new MenuTracker(this.input, this.tracker); int[] ranges = new int[menu.getRange()]; for (int i = 0; i < ranges.length; i++) { ranges[i] = i; } menu.fillActions(); do { menu.show(); menu.select(input.ask("Select:", ranges)); } while (!"y".equals(this.input.ask("Exit?(y):"))); } /** * Метод запуска. * @param args args */ public static void main(String[] args) { Input input = new ValidateInput(); Tracker tracker = new Tracker(); new StartUI(input, tracker).init(); } }
Markdown
UTF-8
10,632
2.84375
3
[]
no_license
# Politic-Thoery ## Anti-Enlightenment Burkean Outlook Irish, Edmund Burke (1729 - 1797), conservative (time-heritage) Outlook Hostility to science (1789 French Revolution, rebuild the whole regime) Aristotle Decentering of the individual (Kennedy) Burke’s selection on the French Revolution Time could change Value of Caution Conservative is not reactionary Campare Robert Peel Lord Patrick Devlin Morals and the criminal law. (Report on homosexuality and prostitution, should be legal) 1957 A sociological theory, not a philosophical theory The public absorb the public morality, which has intolerance, indignation and disgust, tells you a line that you cannot cross if you are thinking about change. The law should evolve to accord with the morals and culture of a society. (According to Devlin) Try to do without justifying individual rights is even harder Contemporary communitarianism. (Alasdair Maclntyre) Marx better than Christianity, —> Disappointed Marxist, —> Disappointed enlightenment thinker Why after virtue? Virtue (Aristotle). (For Hobbes it is massive confusion from the clear interest) Macintyre thinks that Aristotelian tradition needs to be revived and adapted for contemporary purpose. Karl Stevenson (critic of Hume’s, in transition of classical to Neo-classical utilitarianism, the classical utilitarians had no problem with interpersonal judgements of utility, Hume is not that sure, but he thinks that most people are alike, focus on what’s good for one people, interpersonal compare isn’t a issue; Stevenson said that maybe people are not fundamentally alike in the kind of moral judgements that they make) Stevenson’s Emotivism Ethical sentences express emotional attitudes, not propositions Moral arguments are exercises in persuasive definition The hurray!/boo! theory of morality Emotivist Culture Rawls’ enduring pluralism (Starts with the assumption that we have fundamentally different values, never reconcile, Rousseau’s social contract, theory of taking men as they are and laws as they might be. They don’t agree on fundamental moral questions) Neo-classical denial of ICU(interpersonal compare of utility) Stevenson’s emotivism Nozick’s right-as-side constraints All means abandonment of the virtues Instrumental rationale Symptoms: Affirmative action. (Abortion, Nuclear disarmament)CNN crossfire If people are really emotivist, yeah boo morality culture, not expected to persuade, why are they going through the forms of rational arguments? Challenge other’s logic and be more cogent? Why this ritual of rational argument and reason giving and citing evidence and changeling other's ???? Mclntyre : We have an expectation about moral argument that our practice doesn’t deliver on. We engage in forms of moral judgements because we inherited a tradition which is basically being dismembered. We’ve inherited bits and pieces of a tradition in which it was completely accepted that people can be persuaded in moral arguments. But we/ve also detached those strands of the tradition from the unifying assumptions about human nature that gave them their point. And so we’ve inherited sort of incoherent pieces of a once coherent world view. Reason why people engage in this argument is because it’s a kind of performative illustration of the dissatisfaction with the enlightenment has brought. Enlightenment culture finally produce this emotivist culture which we all act out, live in, participate in. Deeply we are uncomfortable in this yeah boo theory of morality. Understand historically. Paradox: this cognitive dissonance, society-wide scale in that nobody expects to persuade anybody of anything in this emotivist culture.(Charles Stevenson) Basic choice: Aristotle or Nietzsche (Nietzsche: Good and evil, Nihilism???) Practice: Any coherent and complex form of socially established cooperative human activity through which goods internal to that activity are realised. (How to fit in a community, internalise) Virtue: (moral philosophy, Nicomachean Ethics) An acquired human quality the possession and exercise of which tends to enable us to achieve those goods which are internal to practices and the lack of which effectively prevents us from achieving any such good. —After virtue. (Pitcher’s Pitch; Hegel, The Phenomenology of Spirit, where he talks about different social forms of social orgnizatins, etc master slave society unstable, master dissatisfying wants recognition from sb regards as equal, as sb worth getting recognition from, master not from slaves. Be affirmed by people we value, and we would value within a practice cuz they understand them inside.)Virtues are embedded in practices, in order to understand and do well, we respect those goods, subordinate to the practices and excel. (Who set the virtues up? Nobody, we are by natural constitution, historical creatures, we start from where we are, we don’t start from some magical choice about where we would like to go) ### Communitarianism > I think, therefore I am. ----- Rene Descartes Cogito (1596-1650) All about me, me, me, The individual was the centre of Enlightenment story. > I am because we are, and since we are, therefore I am ----John S. MBiti, Ubuntu alternative Only discover your identity by reference to you group into which you were born and see that group perceives your identity. Group and community comes before, defines the individual. **Hope Ubantu wasn't corrupted by the Enlightenment project !!!** #### Other Communitarians ##### Michael Sandel (Utilitarianism give the good a bad name) - Liberalism and the Limits of Justice (1982) - "The Procedural Republic and the Unencumbered Self" (1984) - What Money Can't Buy: The Moral Limits of Markets (2012) ##### Charles Taylor - Hegal and Modern Society (1979) - Source of the Self (1992) (Ubantu-like) ##### Richard Rorly - Philosophy and the Mirror of Nature (1979) (How The Enlightenment project in metaphysics had to fail) - "Postmodernist Bourgeois Liberalism" (1983) ##### Michael Walzer - Speres of Justice (1983) (leaning on Aristotle) - Interpretation and Social Criticism (1987) ### Maclntyre: What was the Enlightment project that had to fail? "Justifying morality" -> Deriving moral precepts we find appealing from a scientific account of the human condition. The science is going to produce a morality that justifies individual rights. > Rousseau, Social Contract > "... taking men as they are and laws as they might be" paradigm case of a programmatic statement of the Enlightment >Bentham, pleasure seeking and pain avoidance guides human behavior, let's come up with principles bad on that. Utilitarianism can justify, but with many things that we're deeply uncommfortable with, genocide etc. Nozick or others, take human behavior as we find it, turn into principle, end is unsatisfying. Why? Cuz We have inherited the precepts of ethics from older tradition (Aristotelian). Taking on the Enlightment, we've abandoned the intellectual framework within which it make sense. > Aristotle's Teleological Scheme, After Virtue, pp. 52-3 > a threefold scheme in which human nature as it happens to be. Human nature in its untutored state, human beings as we find >them in the world is initially discrepant and discordant with the precepts of ethic and needs to be transformed by the >instruction of practical reason and ex, and experience into human nature as it could be if it realized its telos. We are >malleable creatures, we are plastic creatures, we are shaped. And ethics is about how to shape us. It's not derived from how >we start out, right? Each of the three elements in the scheme, the conception of untutored human nature, the conception of >the precepts of irrational ethics and the conception of human nature as it could be if it realized its telos. Requires >reference to the other two if its status and function are to be intelligible. Ethics is about how to creat people who can realize the potential for virtue. So can't derive it from the start. (People do lack virtues) Lots of Plato and Aristotle's ethic do with education, while Bentham, Rawls or Nozick say nothing to education. Begining and end of story about human psychology. **Aristotle, A teleological picture of human psychology** People like raw clay, it can be shaped, malleable. The Hopelessness of the Enlightenment Project After Virtue, p.55 Since the moral injunctions were originally at home in a scheme in which their purpose was to correct, improve and educate human nature, they're clearly not going to be such as could be deduced from true statements about human nature. They were there to change human nature. Or justified in some other way by appealing to its characteristics. The injunctions of morality thus understood, are likely to be ones that human nature, thus understood, has strong tendencies to disobey, right? So things we're not going to be inclined to do, contra benta, right? Hence the 18th century moral philosophists engaged what was, in what was inevitably an unsuccessful project. For they did, indeed, attempt to find a rational basis for their moral beliefs in a particular understanding of human nature, while inheriting a set of moral injunctions on one hand and a conception of human nature of the other which had been expressly designed to be discrepant with one another. Discrepant with one another. **They inherited incoherent fragments of a once coherent scheme of thought and action and, since they did not recognize their own peculiar historical and cultural situation, they could not recognize the impossible and quixotic character of their own self-appointed task.** ## Concluding Anti-Enlightenment Thought ## Contro Aristotle, we reason about ends as well as means. Maclntyre historicizes the Aristotelian tradition, the virtues that are affirmed than tradition evolve over time. (while Aristotle just deliberate the means, take the ens the virtue as timeless universals) Contro Burke, tradition noursih disagreement Tradition bound reason ranges over empirical and normative understanding - explain to a child that the world doesn't fall down beause a gaint holds it up - Part of being a Jew involes arguing about what is means to be a Jew. We have abandoned historicized Aristitelianism in favor of the chimerical Enlightenment Projecct Maclntyre - Causal account of the social world (naive history of moral disgreement; Hopeless on conflict; Vapid prescriptions) - Sructure of human psychology (Teleological; Development, Intrinsically other-referential) Neo-Aritotle, close today's human psychology, behavioral psychologist(Paul Bloom) Rejecting Science Decentering individual
Python
UTF-8
2,935
4
4
[]
no_license
# wire-spin: simple animated 3d objects in Python def tetrahedron(): ''' Return a hashed set containing the line segments of a tetrahedron. Form: {[(x,y,z),(x,y,z)], [(x,y,z),(x,y,z)], ...} i.e., {[(point), (vector)], ... } Each element of the set is a list containing six numerical elements. The first three of these elements represent a point in 3d space. The next three elements represent a vector that indicates the direction and length of the line originating at the given point. ''' lines = [ [0,0,0, 1,1,0], [0,0,0, 1,0,1], [0,0,0, 0,1,1], [0,1,1, 1,-1,0], [0,1,1, 1,0,-1], [1,0,1, 0,1,-1] ] return lines def calc_rejection(vector1, vector2): '''Return the "rejection" of vector1 onto vector2''' # the projection is calculated by # vector projection a' = [(a*(b/|b|)](b/|b|) # The quantity in square brackets is a scalar quantity. # The vector "rejection" is then calc. as = a - a' import math a1 = vector1[0] a2 = vector1[1] a3 = vector1[2] b1 = vector2[0] b2 = vector2[1] b3 = vector2[2] magnitude_b = math.sqrt(b1**2 + b2**2 + b3**2) bu1 = b1 / magnitude_b bu2 = b2 / magnitude_b bu3 = b3 / magnitude_b ap1 = a1 * bu1 ap2 = a2 * bu2 ap3 = a3 * bu3 ap = ap1 + ap2 + ap3 ap1 = ap * bu1 ap2 = ap * bu2 ap3 = ap * bu3 # Calculate the "rejection" (the part along the plane, i.e. perpend. to # plane vector given. r1 = a1 - ap1 r2 = a2 - ap2 r3 = a3 - ap3 return [r1, r2, r3] def project_line_to_plane(line, plane): ''' Return 3d vector projection onto given 2d plane "line" is a six-element list, first three for start-point, next for vector "plane" is actually just a vector perpendicular to plane. Because we are not doing anything with perspective, location of plane does not matter. ''' # position vector (start-point) a = line[0:3] # line-segment >end-point vector<, from origin b = [line[3] + a[0], line[4] + a[1], line[5] + a[2]] proj1 = calc_rejection(a, plane) proj2 = calc_rejection(b, plane) projected_line = proj1 + proj2 return projected_line def project_mesh(mesh, viewing_plane): for line in mesh: proj = project_line_to_plane(line, viewing_plane) print(proj, "\n") def draw_line(line): ''' Accepts a 4-element list/tuple representing a line Expects form (startpoint_x, startpoint_y, endpoint_x, endpoint_y) ''' import tkinter root = tkinter.Tk() canvas = tkinter.Canvas(root) canvas.config(background='black') canvas.pack() canvas.create_line(line[0], line[1], line[2], line[3], fill="light gray", width=1) root.mainloop() plane = (1,1,1) tet = tetrahedron() project_mesh(tet, plane) segment = (45,20, 200, 200) #draw_line(segment)
JavaScript
UTF-8
4,224
2.59375
3
[ "Apache-2.0" ]
permissive
/** * * Copyright 2014-present Basho Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var UpdateSetBase = require('./updatesetbase'); var inherits = require('util').inherits; var Joi = require('joi'); var ByteBuffer = require('bytebuffer'); var utils = require('../../utils'); var rpb = require('../../protobuf/riakprotobuf'); var DtOp = rpb.getProtoFor('DtOp'); var SetOp = rpb.getProtoFor('SetOp'); /** * Provides the Update Set class, its builder, and its response. * @module CRDT */ /** * Command used tp update a set in Riak * * As a convenience, a builder class is provided: * * var update = new UpdateSet.Builder() * .withBucketType('sets') * .withBucket('myBucket') * .withKey('set_1') * .withAdditions(['this', 'that', 'other']) * .withCallback(callback) * .build(); * * See {{#crossLink "UpdateSet.Builder"}}UpdateSet.Builder{{/crossLink}} * @class UpdateSet * @constructor * @param {String[]|Buffer[]} [options.additions] The values to be added to the set. * @param {String[]|Buffer[]} [options.removals] The values to remove from the set. Note that a context is required. * @extends UpdateSetBase */ function UpdateSet(options, callback) { var set_opts = { additions: options.additions, removals: options.removals }; delete options.additions; delete options.removals; UpdateSetBase.call(this, options, callback); var self = this; Joi.validate(set_opts, schema, function(err, opts) { if (err) { throw err; } self.additions = opts.additions; self.removals = opts.removals; }); } inherits(UpdateSet, UpdateSetBase); UpdateSet.prototype.constructDtOp = function() { var dt_op = new DtOp(); var setOp = new SetOp(); dt_op.setSetOp(setOp); setOp.adds = UpdateSetBase.buflist(this.additions); setOp.removes = UpdateSetBase.buflist(this.removals); return dt_op; }; UpdateSet.prototype.getUpdateRespValues = function(dtUpdateResp) { return dtUpdateResp.set_value; }; var schema = Joi.object().keys({ additions: Joi.array().default([]).optional(), removals: Joi.array().default([]).optional() }); /** * A builder for constructing UpdateSet instances. * * Rather than having to manually construct the __options__ and instantiating * a UpdateSet directly, this builder may be used. * * var update = new UpdateSet.Builder() * .withBucketType('myBucketType') * .withBucket('myBucket') * .withKey('myKey') * .withAdditions(['this', 'that', 'other']) * .withCallback(myCallback) * .build(); * * @class UpdateSet.Builder * @extends UpdateSetBase.Builder */ function Builder() { UpdateSetBase.Builder.call(this); } inherits(Builder, UpdateSetBase.Builder); /** * Construct an UpdateSet instance. * @method build * @return {UpdateSet} */ Builder.prototype.build = function() { var cb = this.callback; delete this.callback; return new UpdateSet(this, cb); }; /** * The values you wish to add to this set. * @method withAdditions * @param {String[]|Buffer[]} additions The values to add. * @chainable */ utils.bb(Builder, 'additions'); /** * The values you wish to remove from this set. * __Note:__ when performing removals a context must be provided. * @method withRemovals * @param {String[]|Buffer[]} removals The values to remove. * @chainable */ utils.bb(Builder, 'removals'); module.exports = UpdateSet; module.exports.Builder = Builder;
C++
UTF-8
3,908
2.625
3
[]
no_license
//#include <Arduino.h> /* Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp Ported to Arduino ESP32 by Evandro Copercini updates by chegewara */ /* #include <BLEDevice.h> #include <BLEUtils.h> #include <BLEServer.h> #include <iostream> #include <string> #include <sstream> #include <stdint.h> #include <sys/time.h> // See the following for generating UUIDs: // https://www.uuidgenerator.net/ #define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" #define CHARACTERISTIC_UUID2 "85964631-7217-4d04-86eb-a4372bf35320" #define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" BLECharacteristic *pSensor2; BLECharacteristic *pSensor; float sensor2 = 0.6789; float sensor1 = 20.0000; int64_t timestamp; bool deviceConnected = false; bool oldDeviceConnected = false; class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; } }; void setup() { Serial.begin(115200); Serial.println("Starting BLE work!"); BLEDevice::init("d6cb27"); BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); BLEService *pService = pServer->createService(SERVICE_UUID); //Sensor 1 pSensor = pService->createCharacteristic( CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ ); char buf[25]; int got_len = snprintf(buf, 8, "%f", sensor1); // should never happen, but check nonetheless if (got_len > sizeof(buf)) throw std::invalid_argument("Float is longer than string buffer"); pSensor->setValue(buf); //Sensor 2 pSensor2 = pService->createCharacteristic( CHARACTERISTIC_UUID2, BLECharacteristic::PROPERTY_READ ); char buf2[25]; int got_len2 = snprintf(buf2, 8, "%f", sensor2); // should never happen, but check nonetheless if (got_len2 > sizeof(buf2)) throw std::invalid_argument("Float is longer than string buffer"); pSensor2->setValue(buf2); pService->start(); // BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); pAdvertising->addServiceUUID(SERVICE_UUID); //pAdvertising->addServiceUUID(SERVICE2_UUID); pAdvertising->setScanResponse(true); pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue pAdvertising->setMinPreferred(0x12); BLEDevice::startAdvertising(); struct timeval tp; gettimeofday(&tp, NULL); int64_t ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; Serial.println("Characteristic defined! Now you can read it in your phone!"); Serial.println("Timestamp " + ms); } void loop() { if (deviceConnected) { Serial.print("\nDevice is connected...\n"); } else{ Serial.print("\nDevice is NOT connected...\n"); } // put your main code here, to run repeatedly: char buf2[25]; int got_len2 = snprintf(buf2, 8, "%f", sensor2); // should never happen, but check nonetheless if (got_len2 > sizeof(buf2)) throw std::invalid_argument("Float is longer than string buffer"); pSensor2->setValue(buf2); //Serial.printf("Temperature is %sº\n", buf2); char buf1[25]; got_len2 = snprintf(buf1, 8, "%f", sensor1); // should never happen, but check nonetheless if (got_len2 > sizeof(buf1)) throw std::invalid_argument("Float is longer than string buffer"); pSensor->setValue(buf1); //Serial.printf("Density is %sg/cm^3\n", buf1); delay(1000); sensor2+=0.1001; sensor1-=0.1001; } */
Shell
UTF-8
471
2.84375
3
[ "MIT" ]
permissive
#!/usr/bin/env bash OLD_DIR=$(pwd) SCRIPT_DIR=$(dirname ${BASH_SOURCE[0]}) SRC_DIR=$(cd $SCRIPT_DIR/../src; pwd) echo "SRC_DIR=$SRC_DIR" cd $SRC_DIR/main/java echo -n ' => Compiling proto for java... ' protoc --java_out=. \ com/ctrip/ferriswheel/proto/workbook.proto \ com/ctrip/ferriswheel/proto/action.proto \ --descriptor_set_out=../resources/ferriswheel-proto.desc --include_imports \ && echo 'Done!' || (echo 'Failed!'; exit 1) cd $OLD_DIR echo 'All done!'
Python
UTF-8
866
2.546875
3
[]
no_license
#! /usr/bin/env python3 import socket import os import time import sys import signal import time def sig_handler(signum,frame): print("Stopping application") exit(0) signal.signal(signal.SIGINT,sig_handler) soc = socket.socket() soc.bind(('',1632)) #help(soc.listen) soc.listen(1) while(True): c,addr = soc.accept() print("Person Connected: ",c,addr) # Receiving file from client fileName = c.recv(1024).decode('utf-8') fileName = "1"+fileName.split('/')[-1] print(fileName) with open(fileName,'w+') as fd: while True: print("INSIDE TRUE") bi = c.recv(1024) print("lol b",bi) if bi== b'<<EOF>>': break fd.write(bi.decode('utf-8')) with open(fileName,'r') as fd: for line in fd: c.sendall(bytes(line,'utf-8')) c.sendall(b"\n") time.sleep(0.5) c.sendall(bytes(time.ctime(os.path.getmtime(fileName))+"\n",'utf-8')) c.close()
C++
UTF-8
281
2.765625
3
[]
no_license
#include<iostream> int main() { std::string str = "HI THIS IS BRAIN"; std::string *pointString = &str; std::string &refString = str; std::cout << str << std::endl; std::cout << *pointString << std::endl; std::cout << refString << std::endl; return 0; }
Python
UTF-8
2,790
2.5625
3
[]
no_license
# Copyright 2012 Davoud Taghawi-Nejad # # Module Author: Davoud Taghawi-Nejad # # ABCE is open-source software. If you are using ABCE for your research you are # requested the quote the use of this software. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License and quotation of the # author. 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. """ The :class:`abceagent.Agent` class is the basic class for creating your agent. It automatically handles the possession of goods of an agent. In order to produce/transforme goods you need to also subclass the :class:`abceagent.Firm` [1]_ or to create a consumer the :class:`abceagent.Household`. For detailed documentation on: Trading: see :class:`abceagent.Trade` Logging and data creation: see :class:`abceagent.Database` and :doc:`simulation_results` Messaging between agents: see :class:`abceagent.Messaging`. .. autoexception:: abcetools.NotEnoughGoods .. [1] or :class:`abceagent.FirmMultiTechnologies` for simulations with complex technologies. """ from __future__ import division class NetworkLogger: def log_agent(self, color='blue', style='filled', shape='circle'): try: if self.round % self._network_drawing_frequency == 0: self.logger_connection.put(('node', self.round, ((self.group, self.idn), color, style, shape))) except TypeError: raise SystemExit("ABCE Error: simulation.network(.) needs to be called in start.py") def log_network(self, list_of_nodes): """ loggs a network. List of nodes is a list with the numbers of all agents, this agent is connected to. Args: list_of_nodes: list of nodes that the agent is linked to. A list of noteds must have the following format: [('agent_group', agent_idn), ('agent_group', agent_idn), ...] If your color: integer for the color style(True/False): filled or not shape(True/False): form of the bubble """ try: if self.round % self._network_drawing_frequency == 0: self.logger_connection.put(('edges', self.round, ((self.group, self.idn), list_of_nodes))) except TypeError: raise SystemExit("ABCE Error: simulation.network(.) needs to be called in start.py")
Python
UTF-8
549
2.921875
3
[]
no_license
import matplotlib.pyplot as plt import numpy as np import cv2 def getImage(nome): return cv2.imread(nome, cv2.IMREAD_COLOR) def filterBlue(img): for line in img: for pix in line: pix[0] = 0 def filterGreen(img): for line in img: for pix in line: pix[1] = 0 def filterRed(img): for line in img: for pix in line: pix[2] = 0 def showImage_cv2(img): cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() img = getImage('python.png') filterBlue(img) #filterGreen(img) filterRed(img) print(img) showImage_cv2(img)
Java
UTF-8
5,867
3.109375
3
[]
no_license
package com.mvj.estruturadados; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertThrows; class VetorTest { //https://assertj.github.io/doc/#assertj-overview @Test void deveAdicionarElementoNoVetor() { var vetor = new Vetor(5); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); vetor.adiciona("4"); var foiAdicionado = vetor.adiciona("5"); assertThat(foiAdicionado).isTrue(); } @Test void deveRetornarQuantidadeDeElementosDoVetor() { var vetor = new Vetor(5); assertThat(vetor.tamanho()).isEqualTo(0); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); assertThat(vetor.tamanho()).isEqualTo(3); vetor.adiciona("4"); vetor.adiciona("5"); vetor.adiciona("6"); vetor.adiciona("7"); assertThat(vetor.tamanho()).isEqualTo(7); } @Test public void deveRetornarToStringDoVetor() { var vetor = new Vetor(5); assertThat(vetor.toString()).isEqualTo("[]"); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); assertThat(vetor.toString()).isEqualTo("[1, 2, 3]"); vetor.adiciona("4"); vetor.adiciona("5"); vetor.adiciona("6"); vetor.adiciona("7"); assertThat(vetor.toString()).isEqualTo("[1, 2, 3, 4, 5, 6, 7]"); } @Test public void deveRetornarPosicaoDeUmElementoNoVetor() { var vetor = new Vetor(5); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); vetor.adiciona("4"); vetor.adiciona("5"); assertThat(vetor.busca("3")).isEqualTo(2); assertThat(vetor.busca("0")).isEqualTo(-1); } @Test public void deveAdicionarElementoEmUmaPosicaoDoVetor() { var vetor = new Vetor(5); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); vetor.adiciona("4"); vetor.adiciona(0, "0"); assertThat(vetor.busca("0")).isEqualTo(0); assertThat(vetor.busca("4")).isEqualTo(4); vetor.adiciona(2, "9"); assertThat(vetor.busca("0")).isEqualTo(0); assertThat(vetor.busca("9")).isEqualTo(2); assertThat(vetor.busca("3")).isEqualTo(4); assertThat(vetor.tamanho()).isEqualTo(6); } @Test public void deveRetornarExceptionSeAdicionarEmIndiceMenorQueZero() { var vetor = new Vetor(5); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); vetor.adiciona("4"); // assertThatThrownBy(() -> { // vetor.adiciona(-1, "0"); // }).isInstanceOf(IllegalArgumentException.class) // .hasMessage("Posição inválida"); // assertThatExceptionOfType(IllegalArgumentException.class) // .isThrownBy(() -> { // vetor.adiciona(-1, "0"); // }).withMessage("Posição inválida"); assertThatIllegalArgumentException().isThrownBy(() -> { vetor.adiciona(-1, "0"); }).withMessage("Posição inválida"); } @Test public void deveRetornarExceptionSeAdicionarEmIndiceMaiorQueTamanho() { var vetor = new Vetor(5); vetor.adiciona(0, "0"); vetor.adiciona(1, "1"); assertThatIllegalArgumentException().isThrownBy(() -> { vetor.adiciona(10, "2"); }).withMessage("Posição inválida"); } @Test public void deveRemoverElementoEmUmaPosicaoDoVetor() { var vetor = new Vetor(5); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); vetor.adiciona("4"); vetor.remove(0); assertThat(vetor.busca("1")).isEqualTo(-1); assertThat(vetor.busca("2")).isEqualTo(0); assertThat(vetor.tamanho()).isEqualTo(3); } @Test public void deveRetornarExceptionSeRemoverEmIndiceMenorQueZero() { var vetor = new Vetor(5); vetor.adiciona("1"); vetor.adiciona("2"); assertThatIllegalArgumentException().isThrownBy(() -> { vetor.remove(-1); }).withMessage("Posição inválida"); } @Test public void deveRemoverElemento() { var vetor = new Vetor(5); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); vetor.adiciona("4"); vetor.remove("1"); assertThat(vetor.busca("1")).isEqualTo(-1); assertThat(vetor.busca("2")).isEqualTo(0); assertThat(vetor.tamanho()).isEqualTo(3); } @Test public void deveRetornarTrueCasaContenhaElemanto() { var vetor = new Vetor<String>(5); vetor.adiciona("1"); vetor.adiciona("2"); vetor.adiciona("3"); vetor.adiciona("4"); assertThat(vetor.contem("1")).isTrue(); assertThat(vetor.contem("0")).isFalse(); } @Test public void deveRetornarIndiceDoUltimoElemanto() { var vetor = new Vetor<String>(5); vetor.adiciona("0"); vetor.adiciona("2"); vetor.adiciona("0"); vetor.adiciona("4"); assertThat(vetor.ultimoIndiceDe("0")).isEqualTo(2); assertThat(vetor.ultimoIndiceDe("2")).isEqualTo(1); assertThat(vetor.ultimoIndiceDe("5")).isEqualTo(-1); assertThat(vetor.ultimoIndiceDe(null)).isEqualTo(-1); } @Test public void deveLimparVetor() { var vetor = new Vetor<String>(); vetor.adiciona("0"); vetor.adiciona("2"); vetor.adiciona("0"); vetor.adiciona("4"); vetor.limpar(); assertThat(vetor.contem("4")).isFalse(); assertThat(vetor.tamanho()).isEqualTo(0); } }
PHP
UTF-8
956
2.5625
3
[]
no_license
<?php namespace App\Observers; /** * @author: wanghui * @date: 2017/4/20 下午4:23 * @email: hank.huiwang@gmail.com */ use App\Cache\UserCache; use App\Models\Company\CompanyData; use App\Models\UserInfo\ProjectInfo; use Illuminate\Contracts\Queue\ShouldQueue; class UserProjectObserver implements ShouldQueue { /** * 任务最大尝试次数 * * @var int */ public $tries = 1; public function created(ProjectInfo $projectInfo) { UserCache::delUserInfoCache($projectInfo->user_id); CompanyData::initCompanyData($projectInfo->customer_name,$projectInfo->user_id,2); } public function updated(ProjectInfo $projectInfo){ UserCache::delUserInfoCache($projectInfo->user_id); CompanyData::initCompanyData($projectInfo->customer_name,$projectInfo->user_id,2); } public function deleted(ProjectInfo $projectInfo){ UserCache::delUserInfoCache($projectInfo->user_id); } }
C++
GB18030
615
2.703125
3
[]
no_license
#pragma once /*============================================================================= Object.h: Direct base class for alpha Lyrae Engine =============================================================================*/ // mapмصĶ̳д࣬缸壬 // ʵ˻ļÿΨһid class Object { private: static unsigned int g_count; //objectĸ unsigned int m_ID; //ÿid public: Object(); virtual ~Object() {} static unsigned int GetCount() { return g_count; } unsigned int GetID() { return m_ID; } };
PHP
UTF-8
6,476
2.984375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: calumwillis * Date: 14/02/2020 * Time: 17:02 */ ini_set("session.save_path", "/home/unn_w17006735/sessionData"); session_start(); require_once("functions.php"); $input = array(); $errors = false; //Gathers the variables from the form and sets stores them in the input array. $input['title'] = filter_has_var(INPUT_GET, 'title') ? $_GET['title'] : null; $input['first_name'] = filter_has_var(INPUT_GET, 'first_name') ? $_GET['first_name'] : null; $input['last_name'] = filter_has_var(INPUT_GET, 'last_name') ? $_GET['last_name'] : null; $input['password'] = filter_has_var(INPUT_GET, 'password') ? $_GET['password'] : null; $input['retype_password'] = filter_has_var(INPUT_GET, 'retype_password') ? $_GET['retype_password'] : null; //Trims any whiteshpace out of the input data. $input['title'] = trim($input['title']); $input['password'] = trim($input['password']); $input['retype_password'] = trim($input['retype_password']); //checks no input has been left empty. if(($input['first_name'] == null)||(strlen($input['first_name'])>20)) //if the first name entry is null or is greater than 20. { $errors = true; } if(($input['last_name'] == null)||(strlen($input['last_name'])>20)) //if the last name entry is null or is greater than 20. { $errors = true; } //checks the title is either 'Mr.', 'Mrs.' or 'Ms.' $titleChoices = array('mr','mrs','ms'); if (!in_array($input['title'],$titleChoices)) { $errors = true; } //Checks both passwords are the same. if ((!$input['password']==$input['retype_password']) || (strlen($input['password']) < 8)) //if the first password doesn't equals the second password or the password is too short. { $errors = true; } //If there are errors the page will redirect page to the form page, else it will call the function to add the data to the database. if ($errors == true) { header('Location: '.newTeacherForm.'.php'); } else { $input['password_hash'] = password_hash($input['password'], PASSWORD_DEFAULT); //Creates a hash of the password entered. try { $input['username'] = generateUsername($input['first_name'], $input['last_name']); //Creates the username and stores in the a variable. //Code to add initial details to account table. $dbConn = getConnection(); $insertSQL = "INSERT INTO Account (first_name, last_name, password_hash, username) VALUES (:first_name, :last_name, :password_hash, :username)"; $stmt = $dbConn->prepare($insertSQL); $stmt->execute(array(':first_name' => $input['first_name'], ':last_name' => $input['last_name'], ':password_hash' => $input['password_hash'], ':username' => $input['username'])); $dbConn = getConnection(); $SQLquery = "SELECT Account.id_pk FROM Account WHERE Account.username =:username"; $stmt = $dbConn->prepare($SQLquery); $stmt->execute(array(':username' => $input['username'])); $user = $stmt->fetchObject(); $userID = $user->id_pk; $dbConn = getConnection(); $insertSQL = "INSERT INTO Teacher (title, account_id_fk) VALUES (:title, :userID)"; $stmt = $dbConn->prepare($insertSQL); $stmt->execute(array(':title' => $input['title'], 'userID' => $userID)); $names = array('Good Work!', 'Great Idea!', 'Attendance', 'Excellent Contribution!', 'Well Done!'); $coins = array(1000, 1000, 500, 1500, 750); $qCoins = array(2, 2, 1, 3, 1); for ($i = 0; $i <= 4; $i++) { $dbConn = getConnection(); $insertSQL = "INSERT INTO Preset (teacher_id_fk, name, message, coins, q_coins) VALUES (:teacherID, :name, :message, :coins, :qCoins)"; $stmt = $dbConn->prepare($insertSQL); $stmt->execute(array(':teacherID' => $userID, ':name' => $names[$i], ':message' => "", ':coins' => $coins[$i], ':qCoins' => $qCoins[$i])); } } catch (Exception $e) { echo "A problem occurred. Please try again."; } header('Location: loginProcess.php?username='.$input['username'].'&password='.$input['password']); } function generateUsername($first_name, $last_name) { //Divides the first name string based on how big it is. if (strlen($first_name) >= 3) { $a = substr($first_name, 0, 3); } else if (strlen($first_name) > 1) { $a = substr($first_name, 0, 2); } else { $a = substr($first_name, 0, 1); } //Divides the last name string based on how big it is. if (strlen($last_name) >= 3) { $b = substr($last_name, 0, 3); } else if (strlen($last_name) > 1) { $b = substr($last_name, 0, 2); } else { $b = substr($last_name, 0, 1); } $a = strtolower($a); $b = strtolower($b); $name = $a.$b; $num = findDuplicates($name); if ($num > 0) { $name = $name . $num; //Adds the next available number to the username. } return $name; } function findDuplicates($name) //Function that checks how many similar usernames already exist/ { $outputName = $name; $b = false; $i = 0; while ($b == false) { if (($i > 0)) { $outputName = $name.$i; } $dbConn = getConnection(); $SQLquery = "SELECT username FROM Account WHERE username =:username"; $stmt = $dbConn->prepare($SQLquery); $stmt->execute(array(':username' => $outputName)); $temp = $stmt->fetchColumn(); if ($temp) { $i = $i + 1; $b = false; } else { $b = true; } } return $i; } ?>
Python
UTF-8
6,987
2.578125
3
[]
no_license
import scrapy import re def remove_tags(text): tag_re = re.compile(r"<[^>]+>") return tag_re.sub("", text) class MorizonSpider(scrapy.Spider): name = "morizon" def start_requests(self): for i in range(1, 35): yield scrapy.Request( f"https://www.morizon.pl/dzialki/budowlana/minski/?page={i}", callback=self.parse_advert, ) def parse_advert(self, response): pages = response.xpath( '//a[@class="property_link property-url"]/@href' ).extract() dates = response.xpath( '//span[@class="single-result__category single-result__category--date"]/text()' ).extract() dates_added = ["".join(date.split()).replace("-", "/") for date in dates] data = zip(pages, dates_added) for page, date in data: request = scrapy.Request(url=page, callback=self.parse_advert_data) request.meta["link"] = page request.meta["date_added"] = date yield request @staticmethod def parse_advert_data(response): data = { "place": response.xpath('//div[@class="col-xs-9"]/h1/strong/span[2]/text()') .get() .split(",")[0] .strip(), "county": "".join( response.xpath('//div[@class="col-xs-9"]/h1/strong/span/text()') .get() .split() ) .lower() .replace(",", ""), "price": "".join( response.xpath('//li[@class="paramIconPrice"]/em/text()') .get() .replace(",", ".") .split() ), "price_per_m2": "".join( response.xpath('//li[@class="paramIconPriceM2"]/em/text()') .get() .replace(",", ".") .split() ), "area": "".join( response.xpath('//li[@class="paramIconLivingArea"]/em/text()') .get() .replace(",", ".") .split() ), "link": response.meta["link"], "date_added": response.meta["date_added"], "description": remove_tags( " ".join(response.xpath('//div[@class="description"]').get().split()) ), "image_url": response.xpath('//div[@class="imageBig"]/img/@src').get(), } yield data class AdresowoSpider(scrapy.Spider): name = "adresowo" def start_requests(self): for i in range(1, 13): yield scrapy.Request( f"https://adresowo.pl/dzialki/powiat-minski/fz1z4_l{i}", callback=self.parse_advert, ) def parse_advert(self, response): pages = response.xpath('//div[@class="result-info"]/a/@href').extract() for page in pages: url = f"https://adresowo.pl{page}" request = scrapy.Request(url=url, callback=self.parse_advert_data) request.meta["link"] = url yield request @staticmethod def parse_advert_data(response): data = { "place": response.xpath('//span[@class="offer-header__city"]/text()') .get() .strip(), "county": "miński", "price": response.xpath( '//div[@class="offer-summary__item offer-summary__item1"]/div/span/text()' ) .get() .replace(" ", "") .replace(",", "."), "price_per_m2": response.xpath( '//div[@class="offer-summary__item offer-summary__item2"]/div/span/text()' ) .get() .replace(" ", "") .replace(",", "."), "area": response.xpath( '//div[@class="offer-summary__item offer-summary__item1"]/div[2]/span/text()' ) .get() .replace(" ", "") .replace(",", "."), "link": response.meta["link"], "date_added": "brak danych", "description": remove_tags( " ".join( response.xpath( '//p[@class="offer-description__text offer-' 'description__text--drop-cap"]' ) .get() .split() ) ) + "\n" + remove_tags( " ".join( response.xpath('//ul[@class="offer-description__summary"]') .get() .split() ) ), "image_url": response.xpath('//div[@class="offer-gallery"]/img/@src').get(), } yield data class StrzelczykSpider(scrapy.Spider): name = "strzelczyk" def start_requests(self): for i in range(0, 3): yield scrapy.Request( f"https://www.sulejowek-nieruchomosci.pl/oferty/dzialki/sprzedaz/?page={i}", callback=self.parse_advert, ) def parse_advert(self, response): pages = response.xpath('//div[@class="link-to-offer"]/@data-href').extract() for page in pages: url = f"https://www.sulejowek-nieruchomosci.pl/{page}" request = scrapy.Request(url=url, callback=self.parse_advert_data) request.meta["link"] = url yield request @staticmethod def parse_advert_data(response): data = { "place": response.xpath( '//li[@class="breadcrumb-item active"]/a/span/text()' ) .get() .strip(), "county": "brak danych", "price": response.xpath( '//div[@class="col-md-3 offer--shortcut__details cena"]/span[@class="offer--shortcut__span-value"]/text()' ) .get() .replace(" ", ""), "price_per_m2": response.xpath( '//div[@class="col-md-3 offer--shortcut__details cena_za"]/span[@class="offer--shortcut__span-value"]/text()' ) .get() .split()[0] .replace(",", "."), "area": "".join( response.xpath( '//div[@class="col-md-3 offer--shortcut__details powierzchnia"]/span[@class="offer--shortcut__span-value"]/text()' ) .get() .replace(",", ".") .replace("m²", "") .split() ), "link": response.meta["link"], "date_added": "brak danych", "description": remove_tags( " ".join( response.xpath('//div[@class="section__text-group"]').get().split() ) ), "image_url": response.xpath( '//div[@class="image-container"]/a/@href' ).get(), } yield data
Swift
UTF-8
1,365
2.90625
3
[]
no_license
// // EventDetailViewModel.swift // SeatGeekEvents // // Created by Анастасия Ковалева on 3/24/20. // Copyright © 2020 Anastasia Rodzik. All rights reserved. // import Foundation import Bond import ReactiveKit protocol EventViewModel { var isFavorite: Observable<Bool> { get } var eventViewModel: EventViewModelProtocol { get } func favouriteButtonTapped() } struct EventDetailViewModel: EventViewModel { let isFavorite: Observable<Bool> var eventViewModel: EventViewModelProtocol private let favoritesManager: FavoritesHandler private let disposeBag = DisposeBag() init(eventViewModel: EventViewModelProtocol, favoritesManager: FavoritesHandler) { self.eventViewModel = eventViewModel self.favoritesManager = favoritesManager isFavorite = Observable<Bool>(eventViewModel.isFavorite.value) isFavorite .bind(to: eventViewModel.isFavorite) .dispose(in: disposeBag) } func favouriteButtonTapped() { let eventIdentifier = eventViewModel.identifier if isFavorite.value { favoritesManager.removeFromFavorite(eventIdentifier: eventIdentifier) isFavorite.value = false } else { favoritesManager.makeFavorite(eventIdentifier: eventIdentifier) isFavorite.value = true } } }
Markdown
UTF-8
6,252
2.53125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Troubleshoot cluster validation reporting description: Troubleshoot cluster validation reporting and validate QoS settings configuration for Azure Stack HCI clusters author: jasongerend ms.topic: troubleshooting ms.date: 04/17/2023 ms.author: jgerend --- # Troubleshoot cluster validation reporting > Applies to: Azure Stack HCI, versions 22H2 and 21H2; Windows Server 2022, Windows Server 2019 This topic helps you troubleshoot cluster validation reporting for network and storage QoS (quality of service) settings across servers in an Azure Stack HCI cluster, and verify that important rules are defined. For optimal connectivity and performance, the cluster validation process verifies that Data Center Bridging (DCB) QoS configuration is consistent and, if defined, contains appropriate rules for Failover Clustering and SMB/SMB Direct traffic classes. DCB is required for RDMA over Converged Ethernet (RoCE) networks, and is optional (but recommended) for Internet Wide Area RDMA Protocol (iWARP) networks. ## Install data center bridging Data Center Bridging must be installed to use QoS-specific cmdlets. To check if the Data Center Bridging feature is already installed on a server, run the following cmdlet in PowerShell: ```PowerShell Get-WindowsFeature -Name Data-Center-Bridging -ComputerName Server1 ``` If Data Center Bridging is not installed, install it by running the following cmdlet on each server in the cluster: ```PowerShell Install-WindowsFeature –Name Data-Center-Bridging -ComputerName Server1 ``` ## Run a cluster validation test Either use the Validate feature in Windows Admin Center by selecting **Tools > Servers > Inventory > Validate cluster**, or run the following PowerShell command: ```PowerShell Test-Cluster –Node Server1, Server2 ``` Among other things, the test will validate that DCB QoS Configuration is consistent, and that all servers in the cluster have the same number of traffic classes and QoS Rules. It will also verify that all servers have QoS rules defined for Failover Clustering and SMB/SMB Direct traffic classes. You can view the validation report in Windows Admin Center, or by accessing a log file in the current working directory. For example: C:\Users\<username>\AppData\Local\Temp\ Near the bottom of the report, you will see "Validate QoS Settings Configuration" and a corresponding report for each server in the cluster. To understand which traffic classes are already set on a server, use the `Get-NetQosTrafficClass` cmdlet. To learn more, see [Validate an Azure Stack HCI cluster](../deploy/validate.md). ## Validate networking QoS rules Validate the consistency of DCB willing status and priority flow control status settings between servers in the cluster. ### DCB willing status Network adapters that support the Data Center Bridging Capability Exchange protocol (DCBX) can accept configurations from a remote device. To enable this capability, the DCB willing bit on the network adapter must be set to true. If the willing bit is set to false, the device will reject all configuration attempts from remote devices and enforce only the local configurations. If you're using RDMA over Converged Ethernet (RoCE) adapters, then the willing bit should be set to false on all servers. All servers in an Azure Stack HCI cluster should have the DCB willing bit set the same way. Use the `Set-NetQosDcbxSetting` cmdlet to set the DCB willing bit to either true or false, as in the following example: ```PowerShell Set-NetQosDcbxSetting –Willing $false ``` ### DCB flow control status Priority-based flow control is essential if the upper layer protocol, such as Fiber Channel, assumes a lossless underlying transport. DCB flow control can be enabled or disabled either globally or for individual network adapters. If enabled, it allows for the creation of QoS policies that prioritize certain application traffic. In order for QoS policies to work seamlessly during failover, all servers in an Azure Stack HCI cluster should have the same flow control status settings. If you're using RoCE adapters, then priority flow control must be enabled on all servers. Use the `Get-NetQosFlowControl` cmdlet to get the current flow control configuration. All priorities are disabled by default. Use the `Enable-NetQosFlowControl` and `Disable-NetQosFlowControl` cmdlets with the -priority parameter to turn priority flow control on or off. For example, the following command enables flow control on traffic tagged with priority 3: ```PowerShell Enable-NetQosFlowControl –Priority 3 ``` ## Validate storage QoS rules Validate that all nodes have a QoS rule for failover clustering and for SMB or SMB Direct. Otherwise, connectivity problems and performance problems may occur. ### QoS Rule for failover clustering If **any** storage QoS rules are defined in a cluster, then a QoS rule for failover clustering should be present, or connectivity problems may occur. To add a new QoS rule for failover clustering, use the `New-NetQosPolicy` cmdlet as in the following example: ```PowerShell New-NetQosPolicy "Cluster" -Cluster -Priority 6 ``` ### QoS rule for SMB If some or all nodes have QOS rules defined but do not have a QOS Rule for SMB, this may cause connectivity and performance problems for SMB. To add a new network QoS rule for SMB, use the `New-NetQosPolicy` cmdlet as in the following example: ```PowerShell New-NetQosPolicy -Name "SMB" -SMB -PriorityValue8021Action 3 ``` ### QoS rule for SMB Direct SMB Direct bypasses the networking stack, instead using RDMA methods to transfer data. If some or all nodes have QOS rules defined but do not have a QOS Rule for SMB Direct, this may cause connectivity and performance problems for SMB Direct. To create a new QoS policy for SMB Direct, issue the following commands: ```PowerShell New-NetQosPolicy "SMB Direct" –NetDirectPort 445 –Priority 3 ``` ## Next steps For related information, see also: - [Data Center Bridging](/windows-server/networking/technologies/dcb/dcb-top) - [Manage Data Center Bridging](/windows-server/networking/technologies/dcb/dcb-manage) - [QoS Common Configurations](/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/jj735302(v=ws.11))
Python
UTF-8
929
2.890625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 11 10:34:32 2018 @author: """ import csv import MySQLdb connection = MySQLdb.connect(db="----",user="root",passwd="------",host='localhost') cursor=connection.cursor() count = 0; #table 作成 sql = 'create table name (id int, content varchar(32), content2 varchar(32), content3 varchar(32))' cursor.execute(sql) print('* testテーブルを作成\n') # テーブル一覧の取得 #sql = 'show tables;' #cursor.execute(sql) #print('===== テーブル一覧 =====') #print(cursor.fetchone()) f = open("------.csv", "r") reader = csv.reader(f) #一行目を取得 #header = next(reader) #print(header) for row in reader: sql = "INSERT IGNORE INTO name values(%s,%s,%s,%s)" count += 1; print(count,row[0], row[1], row[2]) cursor.execute(sql, (count,row[0], row[1], row[2])) f.close() connection.commit() cursor.close() connection.close()
Java
UTF-8
1,219
2.46875
2
[]
no_license
package cn.itcast.bookstore.category.service; import java.util.List; import cn.itcast.bookstore.category.dao.CategoryDao; import cn.itcast.bookstore.category.domain.Category; public class CategoryService { private static final String String = null; private CategoryDao categoryDao=new CategoryDao(); public List<Category> findAll(){ return categoryDao.findAll(); } public void add(String cname) throws CategoryException{ Category category=categoryDao.findByCname(cname); if(category!=null) throw new CategoryException("该类别已经存在"); category=new Category(); category.setCname(cname); category.setCid(categoryDao.getTotal()+1+""); categoryDao.add(category); } public void delete(String cid) throws CategoryException{ if(categoryDao.findBooksByCid(cid)>0) throw new CategoryException("该类别下还有图书,不能删除"); categoryDao.delete(cid); } public Category findByCid(String cid) throws CategoryException { Category category=categoryDao.findByCid(cid); if(category==null) throw new CategoryException("不存在此类别"); return category; } public void edit(Category category) { categoryDao.edit(category.getCname(),category.getCid()); } }
Markdown
UTF-8
8,606
2.671875
3
[ "MIT" ]
permissive
# Phrase\TagsApi All URIs are relative to *https://api.phrase.com/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**tagCreate**](TagsApi.md#tagCreate) | **POST** /projects/{project_id}/tags | Create a tag [**tagDelete**](TagsApi.md#tagDelete) | **DELETE** /projects/{project_id}/tags/{name} | Delete a tag [**tagShow**](TagsApi.md#tagShow) | **GET** /projects/{project_id}/tags/{name} | Get a single tag [**tagsList**](TagsApi.md#tagsList) | **GET** /projects/{project_id}/tags | List tags ## tagCreate > \Phrase\Model\TagWithStats tagCreate($project_id, $tag_create_parameters, $x_phrase_app_otp) Create a tag Create a new tag. ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKey('Authorization', 'YOUR_API_KEY'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Authorization', 'token'); $apiInstance = new Phrase\Api\TagsApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $project_id = 'project_id_example'; // string | Project ID $tag_create_parameters = new \Phrase\Model\TagCreateParameters(); // \Phrase\Model\TagCreateParameters | $x_phrase_app_otp = 'x_phrase_app_otp_example'; // string | Two-Factor-Authentication token (optional) try { $result = $apiInstance->tagCreate($project_id, $tag_create_parameters, $x_phrase_app_otp); print_r($result); } catch (Exception $e) { echo 'Exception when calling TagsApi->tagCreate: ', $e->getMessage(), PHP_EOL; } ?> ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **project_id** | **string**| Project ID | **tag_create_parameters** | [**\Phrase\Model\TagCreateParameters**](../Model/TagCreateParameters.md)| | **x_phrase_app_otp** | **string**| Two-Factor-Authentication token (optional) | [optional] ### Return type [**\Phrase\Model\TagWithStats**](../Model/TagWithStats.md) ### Authorization [Basic](../../README.md#Basic), [Token](../../README.md#Token) ### HTTP request headers - **Content-Type**: application/json - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## tagDelete > tagDelete($project_id, $name, $x_phrase_app_otp, $branch) Delete a tag Delete an existing tag. ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKey('Authorization', 'YOUR_API_KEY'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Authorization', 'token'); $apiInstance = new Phrase\Api\TagsApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $project_id = 'project_id_example'; // string | Project ID $name = 'name_example'; // string | name $x_phrase_app_otp = 'x_phrase_app_otp_example'; // string | Two-Factor-Authentication token (optional) $branch = my-feature-branch; // string | specify the branch to use try { $apiInstance->tagDelete($project_id, $name, $x_phrase_app_otp, $branch); } catch (Exception $e) { echo 'Exception when calling TagsApi->tagDelete: ', $e->getMessage(), PHP_EOL; } ?> ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **project_id** | **string**| Project ID | **name** | **string**| name | **x_phrase_app_otp** | **string**| Two-Factor-Authentication token (optional) | [optional] **branch** | **string**| specify the branch to use | [optional] ### Return type void (empty response body) ### Authorization [Basic](../../README.md#Basic), [Token](../../README.md#Token) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## tagShow > \Phrase\Model\TagWithStats tagShow($project_id, $name, $x_phrase_app_otp, $branch) Get a single tag Get details and progress information on a single tag for a given project. ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKey('Authorization', 'YOUR_API_KEY'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Authorization', 'token'); $apiInstance = new Phrase\Api\TagsApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $project_id = 'project_id_example'; // string | Project ID $name = 'name_example'; // string | name $x_phrase_app_otp = 'x_phrase_app_otp_example'; // string | Two-Factor-Authentication token (optional) $branch = my-feature-branch; // string | specify the branch to use try { $result = $apiInstance->tagShow($project_id, $name, $x_phrase_app_otp, $branch); print_r($result); } catch (Exception $e) { echo 'Exception when calling TagsApi->tagShow: ', $e->getMessage(), PHP_EOL; } ?> ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **project_id** | **string**| Project ID | **name** | **string**| name | **x_phrase_app_otp** | **string**| Two-Factor-Authentication token (optional) | [optional] **branch** | **string**| specify the branch to use | [optional] ### Return type [**\Phrase\Model\TagWithStats**](../Model/TagWithStats.md) ### Authorization [Basic](../../README.md#Basic), [Token](../../README.md#Token) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) ## tagsList > \Phrase\Model\Tag[] tagsList($project_id, $x_phrase_app_otp, $page, $per_page, $branch) List tags List all tags for the given project. ### Example ```php <?php require_once(__DIR__ . '/vendor/autoload.php'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKey('Authorization', 'YOUR_API_KEY'); $config = Phrase\Configuration::getDefaultConfiguration()->setApiKeyPrefix('Authorization', 'token'); $apiInstance = new Phrase\Api\TagsApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client(), $config ); $project_id = 'project_id_example'; // string | Project ID $x_phrase_app_otp = 'x_phrase_app_otp_example'; // string | Two-Factor-Authentication token (optional) $page = 1; // int | Page number $per_page = 25; // int | allows you to specify a page size up to 100 items, 25 by default $branch = my-feature-branch; // string | specify the branch to use try { $result = $apiInstance->tagsList($project_id, $x_phrase_app_otp, $page, $per_page, $branch); print_r($result); } catch (Exception $e) { echo 'Exception when calling TagsApi->tagsList: ', $e->getMessage(), PHP_EOL; } ?> ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **project_id** | **string**| Project ID | **x_phrase_app_otp** | **string**| Two-Factor-Authentication token (optional) | [optional] **page** | **int**| Page number | [optional] **per_page** | **int**| allows you to specify a page size up to 100 items, 25 by default | [optional] **branch** | **string**| specify the branch to use | [optional] ### Return type [**\Phrase\Model\Tag[]**](../Model/Tag.md) ### Authorization [Basic](../../README.md#Basic), [Token](../../README.md#Token) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md)
Rust
UTF-8
10,252
2.90625
3
[]
no_license
use super::BlockAllocator; use crate::alloc::changeset::ChangeSet; use std::mem::{size_of, ManuallyDrop}; use std::ptr::NonNull; pub const CHUNK_DEGREE: usize = 24; pub const CHUNK_SIZE: usize = 1 << CHUNK_DEGREE; // 16MB per block #[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] pub struct Handle(u32); impl Handle { #[inline] pub const fn none() -> Self { Handle(u32::MAX) } #[inline] pub fn is_none(&self) -> bool { self.0 == u32::MAX } #[inline] pub fn offset(&self, n: u32) -> Self { Handle(self.0 + n) } #[inline] pub fn get_slot_num(&self) -> u32 { let mask = CHUNK_SIZE as u32 - 1; self.0 & mask } #[inline] pub fn get_chunk_num(&self) -> u32 { self.0 >> CHUNK_DEGREE } #[inline] pub fn from_index(chunk_index: u32, block_index: u32) -> Handle { Handle(chunk_index << CHUNK_DEGREE | block_index) } } impl Default for Handle { fn default() -> Self { Handle::none() } } type ArenaAllocatorChunk<T> = [ArenaSlot<T>; CHUNK_SIZE / size_of::<T>()]; pub type ArenaBlockAllocator = dyn BlockAllocator; #[repr(C)] struct FreeSlot { next: Handle, // 32 bits } union ArenaSlot<T: ArenaAllocated> { occupied: ManuallyDrop<T>, free: FreeSlot, } pub trait ArenaAllocated: Sized + Default {} pub struct ArenaAllocator<T: ArenaAllocated> { block_allocator: Box<ArenaBlockAllocator>, chunks: Vec<NonNull<ArenaSlot<T>>>, freelist_heads: [Handle; 8], newspace_top: Handle, // new space to be allocated pub(crate) size: u32, // number of allocated slots pub(crate) num_blocks: u32, // number of allocated blocks pub(crate) capacity: u32, // number of available slots pub changeset: ChangeSet, } // ArenaAllocator contains NunNull which makes it !Send and !Sync. // NonNull is !Send and !Sync because the data they reference may be aliased. // Here we guarantee that NonNull will never be aliased. // Therefore ArenaAllocator should be Send and Sync. unsafe impl<T: ArenaAllocated> Send for ArenaAllocator<T> {} unsafe impl<T: ArenaAllocated> Sync for ArenaAllocator<T> {} impl<T: ArenaAllocated> ArenaAllocator<T> { const NUM_SLOTS_IN_CHUNK: usize = CHUNK_SIZE / size_of::<T>(); pub fn new(block_allocator: Box<ArenaBlockAllocator>) -> Self { debug_assert!( size_of::<T>() >= size_of::<FreeSlot>(), "Improper implementation of ArenaAllocated" ); Self { block_allocator, chunks: vec![], freelist_heads: [Handle::none(); 8], // Space pointed by this is guaranteed to have free space > 8 newspace_top: Handle::none(), size: 0, num_blocks: 0, capacity: 0, changeset: ChangeSet::new(0), } } pub fn alloc(&mut self, len: u32) -> Handle { assert!(0 < len && len <= 8, "Only supports block size between 1-8!"); self.size += len; self.num_blocks += 1; // Retrieve the head of the freelist let sized_head = self.freelist_pop(len as u8); let handle: Handle = if sized_head.is_none() { // If the head is none, it means we need to allocate some new slots if self.newspace_top.is_none() { // We've run out of newspace. // Allocate a new memory chunk from the underlying block allocator. let chunk_index = self.chunks.len() as u32; let chunk = unsafe { self.block_allocator.allocate_block().unwrap() }; self.chunks .push(unsafe { NonNull::new_unchecked(chunk as _) }); self.capacity += Self::NUM_SLOTS_IN_CHUNK as u32; self.newspace_top = Handle::from_index(chunk_index, len); Handle::from_index(chunk_index, 0) } else { // There's still space remains to be allocated in the current chunk. let handle = self.newspace_top; let slot_index = handle.get_slot_num(); let chunk_index = handle.get_chunk_num(); let remaining_space = Self::NUM_SLOTS_IN_CHUNK as u32 - slot_index - len; let new_handle = Handle::from_index(chunk_index, slot_index + len); if remaining_space > 8 { self.newspace_top = new_handle; } else { if remaining_space > 0 { self.freelist_push(remaining_space as u8, new_handle); } self.newspace_top = Handle::none(); } handle } } else { // There's previously used blocks stored in the freelist. Use them first. sized_head }; // initialize to zero let slot_index = handle.get_slot_num(); let chunk_index = handle.get_chunk_num(); unsafe { let base = self.chunks[chunk_index as usize] .as_ptr() .add(slot_index as usize); for i in 0..len { let i = &mut *base.add(i as usize); i.occupied = Default::default(); } } handle } pub unsafe fn free(&mut self, handle: Handle, block_size: u8) { self.freelist_push(block_size, handle); self.size -= block_size as u32; self.num_blocks -= 1; } fn freelist_push(&mut self, n: u8, handle: Handle) { debug_assert!(1 <= n && n <= 8); let index: usize = (n - 1) as usize; self.get_slot_mut(handle).free.next = self.freelist_heads[index]; self.freelist_heads[index] = handle; } fn freelist_pop(&mut self, n: u8) -> Handle { let index: usize = (n - 1) as usize; let sized_head = self.freelist_heads[index]; if !sized_head.is_none() { self.freelist_heads[index] = unsafe { self.get_slot(sized_head).free.next }; } sized_head } #[inline] fn get_slot(&self, handle: Handle) -> &ArenaSlot<T> { let slot_index = handle.get_slot_num(); let chunk_index = handle.get_chunk_num(); unsafe { let base = self.chunks[chunk_index as usize].as_ptr(); &*base.add(slot_index as usize) } } #[inline] fn get_slot_mut(&mut self, handle: Handle) -> &mut ArenaSlot<T> { let slot_index = handle.get_slot_num(); let chunk_index = handle.get_chunk_num(); unsafe { let base = self.chunks[chunk_index as usize].as_ptr(); &mut *base.add(slot_index as usize) } } // method here due to compiler bug #[inline] pub fn get(&self, index: Handle) -> &T { unsafe { let slot = self.get_slot(index); &slot.occupied } } #[inline] pub fn get_mut(&mut self, index: Handle) -> &mut T { unsafe { let slot = self.get_slot_mut(index); &mut slot.occupied } } pub fn changed(&mut self, index: Handle) { self.changeset.changed(index) } pub fn changed_block(&mut self, index: Handle, len: u32) { self.changeset.changed_block(index, len) } pub fn flush(&mut self) { if !self.block_allocator.can_flush() { return; } let chunks = &self.chunks; let mut iter = self.changeset.drain().map(|(chunk_index, range)| { let ptr = chunks[chunk_index]; let size: u32 = size_of::<T>() as u32; let range = (range.start * size)..(range.end * size); (ptr.as_ptr() as *mut u8, range) }); unsafe { self.block_allocator.flush(&mut iter); } } } /* Disabled due to compiler bug impl<T: ArenaAllocated> Index<Handle> for ArenaAllocator<T> { type Output = T; fn index(&self, index: Handle) -> &Self::Output { unsafe { let slot = self.get_slot(index); &slot.occupied } } } impl<T: ArenaAllocated> IndexMut<Handle> for ArenaAllocator<T> { fn index_mut(&mut self, index: Handle) -> &mut Self::Output { unsafe { let slot = self.get_slot_mut(index); &mut slot.occupied } } } */ #[cfg(test)] mod tests { use super::*; use std::mem::size_of; impl ArenaAllocated for u128 {} #[test] fn test_alloc() { let block_allocator = crate::alloc::SystemBlockAllocator::new(); let mut arena: ArenaAllocator<u128> = ArenaAllocator::new(Box::new(block_allocator)); let num_slots_in_chunk = CHUNK_SIZE / size_of::<u128>(); for i in 0..(num_slots_in_chunk as u32 - 8) { let handle = arena.alloc(1); assert_eq!(handle.get_slot_num(), i); assert_eq!(handle.get_chunk_num(), 0); } assert_eq!(arena.capacity, num_slots_in_chunk as u32); for i in 0..10 { let handle = arena.alloc(1); assert_eq!(handle.get_slot_num(), i); assert_eq!(handle.get_chunk_num(), 1); } assert_eq!(arena.capacity, num_slots_in_chunk as u32 * 2); assert_eq!( arena.freelist_heads[7], Handle(num_slots_in_chunk as u32 - 8) ); let handle = arena.alloc(5); assert_eq!(handle.get_slot_num(), 10); assert_eq!(handle.get_chunk_num(), 1); let handle = arena.alloc(8); assert_eq!(handle.get_slot_num(), num_slots_in_chunk as u32 - 8); assert_eq!(handle.get_chunk_num(), 0); } #[test] fn test_free() { let block_allocator = crate::alloc::SystemBlockAllocator::new(); let mut arena: ArenaAllocator<u128> = ArenaAllocator::new(Box::new(block_allocator)); let handles: Vec<Handle> = (0..8).map(|_| arena.alloc(4)).collect(); for handle in handles.iter().rev() { unsafe { arena.free(*handle, 4) }; } assert_eq!(arena.alloc(1), Handle(8 * 4)); for handle in handles.iter() { let new_handle = arena.alloc(4); assert_eq!(*handle, new_handle); } } }
Java
UTF-8
2,847
2.296875
2
[ "Apache-2.0" ]
permissive
package org.esupportail.smsuapiadmin.dto.beans; import java.util.Date; import org.esupportail.smsuapi.domain.beans.sms.SmsStatus; /** * UISms is the representation on the web side of the Sms persistent. * * @author MZRL3760 * */ public class UISms extends UIObject { /** * identifier (database) of the account. */ private String id; /** * application. */ private UIApplication application; /** * account. */ private UIAccount account; /** * initialId. */ private String initialId; /** * senderId. */ private String senderId; /** * state. */ private SmsStatus state; /** * date. */ private Date date; /** * phone. */ private String phone; /** * Default constructor. */ public UISms() { // nothing to do } /** * Setter for 'id'. * * @param id */ public void setId(final String id) { this.id = id; } /** * Getter for 'id'. * * @return */ public String getId() { return id; } /** * Getter for 'application'. * * @return */ public UIApplication getApplication() { return application; } /** * Setter for 'application'. * * @return */ public void setApplication(final UIApplication application) { this.application = application; } /** * Getter for 'account'. * * @return */ public UIAccount getAccount() { return account; } /** * Setter for 'account'. * * @return */ public void setAccount(final UIAccount account) { this.account = account; } /** * Getter for 'initialId'. * * @return */ public String getInitialId() { return initialId; } /** * Setter for 'initialId'. * * @return */ public void setInitialId(final String initialId) { this.initialId = initialId; } /** * Getter for 'senderId'. * * @return */ public String getSenderId() { return senderId; } /** * Setter for 'senderId'. * * @return */ public void setSenderId(final String senderId) { this.senderId = senderId; } /** * Getter for 'state'. * * @return */ public SmsStatus getState() { return state; } /** * Setter for 'state'. * * @return */ public void setState(final SmsStatus state) { this.state = state; } /** * Getter for 'date'. * * @return */ public Date getDate() { return date; } /** * Setter for 'date'. * * @return */ public void setDate(final Date date) { this.date = date; } /** * Getter for 'phone'. * * @return */ public String getPhone() { return phone; } /** * Setter for 'phone'. * * @return */ public void setPhone(final String phone) { this.phone = phone; } }
Python
UTF-8
679
2.859375
3
[]
no_license
import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html app = dash.Dash() app.layout = html.Div([ dcc.Input(id='my-id', value='initial value', type="text"), html.Button('Click Me', id='button'), html.Div(id='my-div') ]) @app.callback( Output(component_id='my-div', component_property='children'), [Input('button', 'n_clicks')], state=[State(component_id='my-id', component_property='value')] ) def update_output_div(n_clicks, input_value): return 'You\'ve entered "{}" and clicked {} times'.format(input_value, n_clicks) if __name__ == '__main__': app.run_server()