language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
236
3.875
4
[]
no_license
const valores = [] for (var i = 0; i < 10; i++) { valores.push(function(){ console.log(i) }) } //Quando a função é chamada, o loop já foi executado, e a variável sobrescrita. valores[2]() valores[5]() valores[8]()
TypeScript
UTF-8
275
3.484375
3
[ "MIT" ]
permissive
// union types var values : number | number[]; values = [123, 123908, 132, 231313131312322132123, 123123213,312312] type int = number; type float = number; type long = number; type double = number; type stringArray = string[]; type numberArray = number[]; var x = "123";
JavaScript
UTF-8
2,804
4.03125
4
[]
no_license
// Whats your BMI // // var ericsNewMass = 113.3980925; // var ericsOldMass = 127.0058636; // var ericsHeight = 1.9; // var ericsOldBMI = ericsOldMass / (ericsHeight * ericsHeight); // var ericsNewBMI = ericsNewMass / (ericsHeight * ericsHeight); // console.log(ericsOldBMI); // console.log(ericsNewBMI); // var isHigher = ericsNewBMI > ericsOldBMI; // console.log(isHigher) // if(ericsNewBMI < ericsOldBMI){ // console.log("You lost weight") // } else { // console.log("You gained weight! Oh no!") // } var person1 = { fullName: 'EricW', height: 1.9, mass: 113.3980925, bmiCalc: function(){ this.bmi = this.mass / (this.height * this.height); } } // person1.bmiCalc(); // console.log(person1); var person2 = { fullName: 'JohnD', height: 1.6, mass: 105, bmiCalc: function(){ this.bmi = this.mass / (this.height * this.height); } } // person2.bmiCalc(); // console.log(person2); // Loops and Iterations // var eric = { bills: [124, 48, 268, 180, 42], calcTips: function(){ this.tips = []; this.finalBill = []; for(var i = 0; i < this.bills.length; i++){ var percentage; var bill = this.bills[i]; if(bill < 50){ percentage = 0.20; } else if(bill >= 50 && bill <= 200){ percentage = 0.15; } else if(bill > 200){ percentage = 0.10; } this.tips[i] = Math.floor(bill * percentage); this.finalBill[i] = bill + bill * percentage; } } }; eric.calcTips(); console.log(eric); var mark = { bills: [77, 375, 110, 45], calcTips: function(){ this.tips = []; this.finalBill = []; for(var i = 0; i < this.bills.length; i++){ var percentage; var bill = this.bills[i]; if(bill < 100){ percentage = 0.20; } else if(bill >= 100 && bill <= 300){ percentage = 0.15; } else if(bill > 300){ percentage = 0.10; } this.tips[i] = Math.floor(bill * percentage); this.finalBill[i] = bill + bill * percentage; } } }; function avgTipCalc(tips){ var sum = 0; for(var i = 0; i < tips.length; i++){ sum = sum + tips[i]; } return sum / tips.length; } mark.calcTips(); console.log(mark); eric.average = avgTipCalc(eric.tips); mark.average = avgTipCalc(mark.tips); console.log(eric.average, mark.average); if(eric.average > mark.average){ console.log("Eric's family pays a higher average of tips with: " + eric.average + " per meal"); } else { console.log("Mark's family pays a higher average of tips with: $" + mark.average + " per meal"); }
Java
UTF-8
9,853
1.828125
2
[]
no_license
/* */ package com.adventnet.appmanager.snapshot.bean; /* */ /* */ import com.adventnet.appmanager.db.AMConnectionPool; /* */ import com.adventnet.awolf.data.DatasetProduceException; /* */ import com.adventnet.awolf.data.DatasetProducer; /* */ import java.io.Serializable; /* */ import java.sql.ResultSet; /* */ import java.util.Date; /* */ import java.util.Map; /* */ import java.util.Vector; /* */ import org.jfree.data.category.CategoryDataset; /* */ import org.jfree.data.category.DefaultIntervalCategoryDataset; /* */ import org.jfree.data.time.TimeSeries; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class HostCpuGraph /* */ implements DatasetProducer, Serializable /* */ { /* */ private AMConnectionPool pool; /* 28 */ long cpuuse = 0L; /* 29 */ long cpufree = 0L; /* 30 */ private String category = "default"; /* */ private ResultSet rs; /* */ private int i; /* 33 */ private String appname = null; /* */ private String haid; /* 35 */ private TimeSeries ts = null; /* 36 */ private Vector HostResourceCount = new Vector(); /* 37 */ private Vector HostResourceId = new Vector(); /* 38 */ final String[] seriesNames = { "Cpu Used", "Cpu Free" }; /* */ DefaultIntervalCategoryDataset ds; /* 40 */ String[] categories = null; /* 41 */ Long[][] startValues = (Long[][])null; /* 42 */ Long[][] endValues = (Long[][])null; /* */ /* */ public HostCpuGraph() /* */ { /* 46 */ this.pool = AMConnectionPool.getInstance(); /* */ } /* */ /* */ public Object produceDataset(Map params) throws DatasetProduceException /* */ { /* 51 */ String mainQuery = "select AM_ManagedObject.ResourceName, AM_ManagedObject.ResourceId from ManagedObject,AM_PARENTCHILDMAPPER,AM_ManagedObject where AM_PARENTCHILDMAPPER.PARENTID=" + this.haid + " and ManagedObject.name=AM_ManagedObject.RESOURCENAME and AM_ManagedObject.RESOURCEID=AM_PARENTCHILDMAPPER.CHILDID and ManagedObject.Type ='Node'"; /* */ try /* */ { /* 54 */ this.rs = AMConnectionPool.executeQueryStmt(mainQuery); /* 55 */ while (this.rs.next()) /* */ { /* */ /* 58 */ String hostname = this.rs.getString(1); /* 59 */ this.HostResourceCount.add(hostname); /* 60 */ String hostid = this.rs.getString(2); /* 61 */ this.HostResourceId.add(hostid); /* */ } /* */ /* */ /* 65 */ this.categories = new String[this.HostResourceCount.size()]; /* 66 */ this.startValues = new Long[this.seriesNames.length][this.categories.length]; /* 67 */ this.endValues = new Long[this.seriesNames.length][this.categories.length]; /* 68 */ for (this.i = 0; this.i < this.HostResourceCount.size();) /* */ { /* 70 */ this.categories[this.i] = ((String)this.HostResourceId.get(this.i)); /* 71 */ long collectionTime = getMaxCollectionTimeFrom("select max(COLLECTIONTIME) from HostDataCollected where RESOURCENAME like '%" + (String)this.HostResourceCount.get(this.i) + "%'"); /* 72 */ if (collectionTime != -1L) /* */ { /* 74 */ AMConnectionPool cp = AMConnectionPool.getInstance(); /* 75 */ String query = "select CURVALUE from HostDataCollected where RESOURCENAME like '%" + (String)this.HostResourceCount.get(this.i) + "%' and CATEGORY like '%" + getCategory() + "%' and CollectionTime = " + collectionTime + ""; /* 76 */ ResultSet set = null; /* */ try /* */ { /* 79 */ set = AMConnectionPool.executeQueryStmt(query); /* 80 */ if (set.next()) /* */ { /* 82 */ this.cpuuse = set.getLong(1); /* 83 */ this.cpufree = (100L - this.cpuuse); /* 84 */ this.startValues[0][this.i] = new Long(0L); /* 85 */ this.endValues[0][this.i] = new Long(this.cpuuse); /* 86 */ this.startValues[1][this.i] = new Long(0L); /* 87 */ this.endValues[1][this.i] = new Long(this.cpufree); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ try /* */ { /* 99 */ if (set != null) { /* 100 */ set.close(); /* */ } /* */ } /* */ catch (Exception e) { /* 104 */ e.printStackTrace(); /* */ } /* 68 */ this.i += 1; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ } /* */ catch (Exception exp) /* */ { /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 93 */ exp.printStackTrace(); /* */ } /* */ finally /* */ { /* */ try /* */ { /* 99 */ if (set != null) { /* 100 */ set.close(); /* */ } /* */ } /* */ catch (Exception e) { /* 104 */ e.printStackTrace(); /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* 111 */ this.rs.close(); /* */ } /* */ catch (Exception e) /* */ { /* 115 */ e.printStackTrace(); /* */ } /* */ /* 118 */ this.ds = new DefaultIntervalCategoryDataset(this.seriesNames, this.categories, this.startValues, this.endValues); /* 119 */ return this.ds; /* */ } /* */ /* */ /* */ private final long getMaxCollectionTimeFrom(String query) /* */ { /* 125 */ AMConnectionPool cp = AMConnectionPool.getInstance(); /* 126 */ ResultSet set = null; /* 127 */ collectionTime = -1L; /* */ try /* */ { /* 130 */ set = AMConnectionPool.executeQueryStmt(query); /* 131 */ if (set.next()) {} /* */ /* 133 */ return set.getLong(1); /* */ } /* */ catch (Exception exp) /* */ { /* 137 */ exp.printStackTrace(); /* */ } /* */ finally /* */ { /* */ try /* */ { /* 143 */ if (set != null) { /* 144 */ set.close(); /* */ } /* */ } catch (Exception e) { /* 147 */ e.printStackTrace(); /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ public boolean hasExpired(Map params, Date since) /* */ { /* 157 */ return true; /* */ } /* */ /* */ public String getProducerId() /* */ { /* 162 */ return "CpuGraph"; /* */ } /* */ /* */ public String getHaid() /* */ { /* 167 */ return this.haid; /* */ } /* */ /* */ public void setHaid(String hid) /* */ { /* 172 */ this.haid = hid; /* */ } /* */ /* */ public String getCategory() { /* 176 */ return this.category; /* */ } /* */ /* */ public void setCategory(String cat) { /* 180 */ this.category = cat; /* */ } /* */ /* */ public String getAppname() /* */ { /* 185 */ return this.appname; /* */ } /* */ /* */ public void setAppname(String ent) /* */ { /* 190 */ this.appname = ent; /* */ } /* */ /* */ /* */ public String generateToolTip(CategoryDataset arg0, int series, int arg2) /* */ { /* 196 */ String Name = null; /* 197 */ DefaultIntervalCategoryDataset ds1 = (DefaultIntervalCategoryDataset)arg0; /* 198 */ String id = "10000012"; /* 199 */ String query = "select RESOURCENAME from AM_ManagedObject where AM_ManagedObject.RESOURCEID=" + id + ""; /* */ try /* */ { /* 202 */ this.rs = AMConnectionPool.executeQueryStmt(query); /* 203 */ if (this.rs.next()) /* */ { /* 205 */ Name = this.rs.getString(1); /* */ } /* */ /* */ } /* */ catch (Exception e) /* */ { /* 211 */ e.printStackTrace(); /* */ } /* 213 */ return "Resource " + Name; /* */ } /* */ /* */ /* */ /* */ /* */ public String generateLink(Object dataset, int series, Object category) /* */ { /* 221 */ String id = (String)category; /* */ /* 223 */ String query = "select AM_ManagedObject.Resourcename,AM_ManagedObject.ResourceID from ManagedObject,AM_PARENTCHILDMAPPER,AM_ManagedObject where AM_PARENTCHILDMAPPER.childID=" + id + " and ManagedObject.name=AM_ManagedObject.RESOURCENAME and AM_ManagedObject.RESOURCEID=AM_PARENTCHILDMAPPER.CHILDID and ManagedObject.Type ='Node'"; /* */ try /* */ { /* 226 */ this.rs = AMConnectionPool.executeQueryStmt(query); /* 227 */ if (this.rs.next()) /* */ { /* 229 */ String Name = this.rs.getString(1); /* 230 */ int resId = this.rs.getInt(2); /* 231 */ id = "HostResource.do?name=" + Name + "&haid=" + this.haid + "&resourceid=" + resId + "#Cpu Utilization"; /* */ } /* */ } /* */ catch (Exception e) /* */ { /* 236 */ e.printStackTrace(); /* */ } /* */ /* 239 */ return id; /* */ } /* */ } /* Location: C:\Program Files (x86)\ManageEngine\AppManager12\working\WEB-INF\lib\AdventNetAppManagerWebClient.jar!\com\adventnet\appmanager\snapshot\bean\HostCpuGraph.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
Markdown
UTF-8
844
3.390625
3
[]
no_license
# helpers.js A collection of small JavaScript helper functions for various use cases. All of these little snippets solve problems that are very common, but don't have a widespread decent implementation. --- __baseURL__ Grabs only the base of any given URL. You can also hide the TLD. ```js baseURL('http://www.maxvoltar.com/archive/more-beats') ``` __readingtime__ Returns the estimated time to complete reading of a text in a human readable format. ```js readingtime(2720, 'Reading this takes {time}.', 270) ``` __smoothscroll__ Scrolls the body element smoothly to the top using only Vanilla JS. ```js smoothscroll() ``` __wordcount__ Counts the words in any given string of text and counts the words correctly. You can define the output using a placeholder. ```js wordcount('Hello, it\'s me', 'This is {count} words long.') ```
C#
UTF-8
1,198
3.859375
4
[]
no_license
using System; namespace HexadecimalToDecimal { class HexadecimalToDecimal { static void Main() { Console.Write("Hexadecimal = "); string hex = Console.ReadLine(); long result = 0; for (int i = 0, j = 0, k=hex.Length-1; i < hex.Length; i++,k--) { if (hex[i]=='A') { j = 10; } else if (hex[i]=='B') { j = 11; } else if (hex[i]=='C') { j = 12; } else if (hex[i]=='D') { j = 13; } else if (hex[i]=='E') { j = 14; } else if (hex[i]=='F') { j = 15; } else { j = Convert.ToInt32(hex[i].ToString()); } result += (long)(j*Math.Pow(16, k)); } Console.WriteLine("Decimal = {0}",result); } } }
C++
UTF-8
899
3.265625
3
[]
no_license
#include "Point.h" Point::Point(const Point & pt) { *this=pt; } Point& Point::operator=(const Point & pt) { _x=pt._x; _y=pt._y; num=pt.num; return *this; } const int Point::get_num(void) const { return num; } const double Point::get_x(void) const { return _x; } const double Point::get_y(void) const { return _y; } bool Point::operator==(const Point& pt) { return _x==pt._x&&_y==pt._y; } Point& Point::operator-(const Point& pt) { _x=pt.get_x()-_x; _y=pt.get_y()-_y; return *this; } Point& Point::operator+(const Point& pt) { _x=pt.get_x()+_x; _y=pt.get_y()+_y; return *this; } Point& Point::set_point(const Point& pt) { *this=pt; } bool Point::operator<(const Point& p) { return (_x<p._x)||(_x==p._x&&_y<p._y); } const double Point::operator[](int x) { if(x==0) return get_x(); return get_y(); }
JavaScript
UTF-8
2,084
2.84375
3
[]
no_license
"use strict" let cu_name_input = document.getElementById("cu_name"); let cu_abbrev_input = document.getElementById("cu_abbrev"); let cu_page_input = document.getElementById("cu_page"); let add_info_input = document.getElementById("additional_info"); let sub_btn = document.getElementById('sub_btn'); function validate_cu_name(){ if (/^[A-Z, a-z, 0-9]+\s*$/g.test(cu_name_input.value)) return true else return false } function validate_cu_abbrev(){ if (/^[A-Z, a-z, 0-9]+$/g.test(cu_abbrev_input.value)) return true else return false } function validate_cu_page(){ if (/^\S+\.\S+$/.test(cu_page_input.value)) return true else return false } let cu_name_ready = false; let cu_abbrev_ready = false; let cu_page_ready = false; let cu_name_errors = document.getElementById("cu_name_errors"); let cu_abbrev_errors = document.getElementById("cu_abbrev_errors"); let cu_page_errors = document.getElementById("cu_page_errors"); cu_name_input.onkeyup = () => { cu_name_ready = validate_cu_name(); if (!cu_name_ready) cu_name_errors.innerHTML = "<p style=\"color:red\">The CU name must contain only letters or digits.</p>" else cu_name_errors.innerHTML = ""; if (cu_name_input && cu_abbrev_ready && cu_page_ready) sub_btn.disabled = false; else sub_btn.disabled = true; }; cu_abbrev_input.onkeyup = () => { cu_abbrev_ready = validate_cu_abbrev(); if (!cu_abbrev_ready) cu_abbrev_errors.innerHTML = "<p style=\"color:red\">The CU abbrev must contain only letters or digits.</p>" else cu_abbrev_errors.innerHTML = ""; if (cu_name_input && cu_abbrev_ready && cu_page_ready) sub_btn.disabled = false; else sub_btn.disabled = true; }; cu_page_input.onkeyup = () => { cu_page_ready = validate_cu_page(); if (!cu_page_ready) cu_page_errors.innerHTML = "<p style=\"color:red\">The CU page must be an URL.</p>" else cu_page_errors.innerHTML = ""; if (cu_name_input && cu_abbrev_ready && cu_page_ready) sub_btn.disabled = false; else sub_btn.disabled = true; }; sub_btn.addEventListener('submit', () => { add_info_input.value = escapeHtml(add_info_input.value); });
Python
UTF-8
918
2.671875
3
[]
no_license
import requests import json import random from PIL import Image import os #minecraft block data mc_resp = requests.get('http://minecraft-ids.grahamedgecombe.com/items.json') block_data = json.loads(mc_resp.text) print(block_data) for icon in os.listdir('items'): pass image = Image.open('items/17-1.png') rgb_im = image.convert('RGB') pixels = [] for i in range(0, 32): for j in range(0, 32): pixel = rgb_im.getpixel((i, j)) if pixel != (0,0,0): r, g, b = pixel pixels.append([r, g, b]) pixels.extend(["N", "N", "N"]) data = { 'model':"default", 'input':pixels } url = "http://colormind.io/api/" resp = requests.post(url=url, data=json.dumps(data)) scheme = json.loads(resp.text) out = open('out.html', 'w') for px in scheme['result']: hex = '#%02x%02x%02x' % tuple(px) out.write(f"<p style='background-color:{hex}'>h</p>") out.close() print(scheme)
JavaScript
UTF-8
452
3.421875
3
[]
no_license
/** * @param {string} s * @return {string[]} */ var findRepeatedDnaSequences = function (s) { if (s.length <= 10) { return []; } var arr = new Set(); var i = 0; var strings = {}; while (i <= s.length - 10) { const target = s.substr(i, 10); if (strings[target]) { arr.add(target); } else { strings[target] = true; } i++; } // return [...arr]; }; findRepeatedDnaSequences('AAAAAAAAAAAAAAAAAA');
C++
UTF-8
24,408
2.703125
3
[]
no_license
#include "Parser.h" Parser::Parser(std::ostream& _errorStream) : errorStream(_errorStream) {}; std::pair<ParseEnum::EResult, std::map<std::string, Airport*> > Parser::parseFile(const char* fileName) { TiXmlDocument xmlFile; std::map<std::string, Airport*> allAirports; if (!xmlFile.LoadFile(fileName)) { errorStream << "Error loading file: " << xmlFile.ErrorDesc() << std::endl; xmlFile.Clear(); return std::pair<ParseEnum::EResult, std::map<std::string, Airport*> >(ParseEnum::kAborted, allAirports); } if (xmlFile.FirstChildElement() == NULL) { errorStream << "Error loading file: root missing" << std::endl; xmlFile.Clear(); return std::pair<ParseEnum::EResult, std::map<std::string, Airport*> >(ParseEnum::kAborted, allAirports); } ParseEnum::EResult parseResult = ParseEnum::kSuccess; Airport* lastAirport = NULL; for (TiXmlElement* object = xmlFile.FirstChildElement(); object != NULL; object = object->NextSiblingElement()) { std::string objectName = object->Value(); if (objectName == "AIRPORT") { std::string airportName; std::string airportIATA; std::string airportCallsign; unsigned int airportGates = 0; bool invalidAirport = false; std::map<std::string, std::string> airportMap = convertXmlNodeToMap(object); if (airportMap.find("name") != airportMap.end()) { airportName = airportMap.at("name"); } else { invalidAirport = true; errorStream << objectName << ": 'name' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airportMap.find("iata") != airportMap.end()) { airportIATA = airportMap.at("iata"); } else { invalidAirport = true; errorStream << objectName << ": 'iata' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airportMap.find("callsign") != airportMap.end()) { airportCallsign = airportMap.at("callsign"); } else { invalidAirport = true; errorStream << objectName << ": 'callsign' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airportMap.find("gates") != airportMap.end()) { int gatesAsInt = 0; int* ptr = &gatesAsInt; REQUIRE(ptr != NULL, "wtf"); if (tryCastStringToInt(airportMap.at("gates"), ptr) && gatesAsInt > 0) { airportGates = static_cast<unsigned int>(gatesAsInt); } else { invalidAirport = true; errorStream << objectName << ": 'gates' attribute is not an unsigned positive integer. " << getRowAndColumnStr(object) << std::endl; } } else { invalidAirport = true; errorStream << objectName << ": 'gates' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (allAirports.find(airportIATA) != allAirports.end()) { invalidAirport = true; errorStream << objectName << ": duplicate airport IATA. " << getRowAndColumnStr(object) << std::endl; } if (invalidAirport) { parseResult = ParseEnum::kPartial; } else { Airport* newAirport = new Airport(airportName, airportIATA, airportCallsign, airportGates); allAirports[airportIATA] = newAirport; lastAirport = newAirport; } } else if (objectName == "RUNWAY") { std::string runwayName = ""; unsigned int runwayLength = 0; RunwayEnums::EType runwayType = RunwayEnums::kInvalidType; Airport* runwayAirport = NULL; bool invalidRunway = false; std::map<std::string, std::string> runwayMap = convertXmlNodeToMap(object); TiXmlElement* taxiRouteNode = object->FirstChildElement("TAXIROUTE"); std::vector<std::pair<bool, std::string> > taxirouteMap; if (taxiRouteNode != NULL) { taxirouteMap = extractTaxiRoute(taxiRouteNode); } else { invalidRunway = true; errorStream << objectName << ": 'taxiroute' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (runwayMap.find("name") != runwayMap.end()) { runwayName = runwayMap.at("name"); } else { invalidRunway = true; errorStream << objectName << ": 'name' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (runwayMap.find("length") != runwayMap.end()) { int lengthAsInt = 0; if (tryCastStringToInt(runwayMap.at("length"), &lengthAsInt) && lengthAsInt > 0) { runwayLength = static_cast<unsigned int>(lengthAsInt); } else { invalidRunway = true; errorStream << objectName << ": 'length' attribute is not an unsigned positive integer. " << getRowAndColumnStr(object) << std::endl; } } else { invalidRunway = true; errorStream << objectName << ": 'length' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (runwayMap.find("airport") != runwayMap.end()) { if (allAirports.find(runwayMap.at("airport")) != allAirports.end()) { runwayAirport = allAirports.at(runwayMap.at("airport")); } else { invalidRunway = true; errorStream << objectName << ": referenced airport does not exist, make sure to declare runways after the referenced airport. " << getRowAndColumnStr(object) << std::endl; } } else { invalidRunway = true; errorStream << objectName << ": 'airport' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (runwayMap.find("type") != runwayMap.end()) { RunwayEnums::EType tempType = RunwayEnums::StringToTypeEnum(runwayMap.at("type").c_str()); if (tempType != RunwayEnums::kInvalidType) { runwayType = tempType; } else { invalidRunway = true; errorStream << objectName << ": 'type' attribute does not contain a valid option. " << getRowAndColumnStr(object) << std::endl; } } else { invalidRunway = true; errorStream << objectName << ": 'type' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (invalidRunway) { parseResult = ParseEnum::kPartial; } else { Runway* newRunway = new Runway(runwayName, runwayLength, runwayType); newRunway->setAirport(runwayAirport); runwayAirport->addRunway(newRunway); runwayAirport->addLocation(newRunway); //adding all locations first for (unsigned int i = 0; i < taxirouteMap.size(); i++) { std::pair<bool, std::string> currentNode = taxirouteMap[i]; std::string nodeName = currentNode.second; if (runwayAirport->getLocationByName(nodeName) == NULL) { //if currentNode.first is true, node is a crossing of a runway if (!currentNode.first && i % 2 == 0) { Location* newLocation = new Location(nodeName); newLocation->setAirport(runwayAirport); runwayAirport->addLocation(newLocation); } else { invalidRunway = true; errorStream << objectName << ": Runways added in wrong order, this one has defined runways before they were added. " << getRowAndColumnStr(object) << std::endl; break; } } } if (!invalidRunway) { for (unsigned int i = 0; i < taxirouteMap.size(); i++) { std::pair<bool, std::string> currentNode = taxirouteMap[i]; std::string nodeName = currentNode.second; bool start_index = (i == 0); bool end_index = ((i + 1) == taxirouteMap.size()); Location* previousLocation = NULL; Location* currentLocation = runwayAirport->getLocationByName(nodeName); Location* nextLocation = NULL; if (!start_index) { previousLocation = runwayAirport->getLocationByName(taxirouteMap[i - 1].second); previousLocation->setNextLocation(currentLocation); } if (!end_index) { nextLocation = runwayAirport->getLocationByName(taxirouteMap[i + 1].second); } else { nextLocation = newRunway; } nextLocation->setPreviousLocation(currentLocation); currentLocation->setPreviousLocation(previousLocation); currentLocation->setNextLocation(nextLocation); } } } } else if (objectName == "AIRPLANE") { std::string airplaneNumber = ""; std::string airplaneCallsign = ""; std::string airplaneModel = ""; unsigned int airplaneFuelCapacity = 0; unsigned int airplanePassengerCapacity = 0; AirplaneEnums::EStatus airplaneStatus = AirplaneEnums::kStatus_InvalidStatus; AirplaneEnums::EType airplaneType = AirplaneEnums::kType_InvalidType; AirplaneEnums::ESize airplaneSize = AirplaneEnums::kSize_InvalidSize; AirplaneEnums::EEngine airplaneEngine = AirplaneEnums::kEngine_InvalidEngine; bool invalidAirplane = false; std::map<std::string, std::string> airplaneMap = convertXmlNodeToMap(object); if (airplaneMap.find("number") != airplaneMap.end()) { airplaneNumber = airplaneMap.at("number"); } else { invalidAirplane = true; errorStream << objectName << ": 'number' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("callsign") != airplaneMap.end()) { airplaneCallsign = airplaneMap.at("callsign"); } else { invalidAirplane = true; errorStream << objectName << ": 'callsign' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("model") != airplaneMap.end()) { airplaneModel = airplaneMap.at("model"); } else { invalidAirplane = true; errorStream << objectName << ": 'model' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("fuel") != airplaneMap.end()) { int fuelCapacityAsInt = 0; if (tryCastStringToInt(airplaneMap.at("fuel"), &fuelCapacityAsInt) && fuelCapacityAsInt > 0) { airplaneFuelCapacity = static_cast<unsigned int>(fuelCapacityAsInt); } else { invalidAirplane = true; errorStream << objectName << ": 'fuel' attribute is not an unsigned positive integer. " << getRowAndColumnStr(object) << std::endl; } } else { invalidAirplane = true; errorStream << objectName << ": 'fuel' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("passengers") != airplaneMap.end()) { int passengerCapacityAsInt = 0; if (tryCastStringToInt(airplaneMap.at("passengers"), &passengerCapacityAsInt) && passengerCapacityAsInt > 0) { airplanePassengerCapacity = static_cast<unsigned int>(passengerCapacityAsInt); } else { invalidAirplane = true; errorStream << objectName << ": 'passengers' attribute is not an unsigned positive integer. " << getRowAndColumnStr(object) << std::endl; } } else { invalidAirplane = true; errorStream << objectName << ": 'passengers' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("status") != airplaneMap.end()) { AirplaneEnums::EStatus tempStatus = AirplaneEnums::StringToStatusEnum(airplaneMap.at("status").c_str()); if (tempStatus == AirplaneEnums::kStatus_Approaching || tempStatus == AirplaneEnums::kStatus_StandingAtGate) { airplaneStatus = tempStatus; } else { invalidAirplane = true; errorStream << objectName << ": 'status' attribute does not contain a valid option. " << getRowAndColumnStr(object) << std::endl; } } else { invalidAirplane = true; errorStream << objectName << ": 'status' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("type") != airplaneMap.end()) { AirplaneEnums::EType tempType = AirplaneEnums::StringToTypeEnum(airplaneMap.at("type").c_str()); if (tempType != AirplaneEnums::kType_InvalidType) { airplaneType = tempType; } else { invalidAirplane = true; errorStream << objectName << ": 'type' attribute does not contain a valid option. " << getRowAndColumnStr(object) << std::endl; } } else { invalidAirplane = true; errorStream << objectName << ": 'type' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("size") != airplaneMap.end()) { AirplaneEnums::ESize tempSize = AirplaneEnums::StringToSizeEnum(airplaneMap.at("size").c_str()); if (tempSize != AirplaneEnums::kSize_InvalidSize) { airplaneSize = tempSize; } else { invalidAirplane = true; errorStream << objectName << ": 'size' attribute does not contain a valid option. " << getRowAndColumnStr(object) << std::endl; } } else { invalidAirplane = true; errorStream << objectName << ": 'size' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (airplaneMap.find("engine") != airplaneMap.end()) { AirplaneEnums::EEngine tempType = AirplaneEnums::StringToEngineEnum(airplaneMap.at("engine").c_str()); if (tempType != AirplaneEnums::kEngine_InvalidEngine) { airplaneEngine = tempType; } else { invalidAirplane = true; errorStream << objectName << ": 'engine' attribute does not contain a valid option. " << getRowAndColumnStr(object) << std::endl; } } else { invalidAirplane = true; errorStream << objectName << ": 'engine' required attribute is missing. " << getRowAndColumnStr(object) << std::endl; } if (invalidAirplane) { parseResult = ParseEnum::kPartial; } else if (lastAirport != NULL) { unsigned int altitude = (airplaneStatus == AirplaneEnums::kStatus_Approaching ? 10000 : 0); Airplane* newAirplane = new Airplane(airplaneNumber, airplaneCallsign, airplaneModel, 0, altitude, airplaneFuelCapacity, airplaneFuelCapacity, airplanePassengerCapacity, airplanePassengerCapacity, airplaneStatus, airplaneType, airplaneSize, airplaneEngine); newAirplane->setAirport(lastAirport); lastAirport->addAirplane(newAirplane); if (airplaneStatus == AirplaneEnums::kStatus_StandingAtGate) { AirplaneVector::iterator it_freeGate = std::find(lastAirport->getGates().begin(), lastAirport->getGates().end(), static_cast<Airplane*>(NULL)); if (it_freeGate != lastAirport->getGates().end()) { *it_freeGate = newAirplane; newAirplane->setGate(std::distance(lastAirport->getGates().begin(), it_freeGate)); } else { errorStream << objectName << ": no free gate for new airplane. " << getRowAndColumnStr(object) << std::endl; delete newAirplane; } } } else { errorStream << objectName << ": No airport defined before this airplane. " << getRowAndColumnStr(object) << std::endl; } } else { errorStream << "Invalid object '" << objectName << "'. " << getRowAndColumnStr(object) << std::endl; parseResult = ParseEnum::kPartial; } } for (AirportMap::const_iterator it_airport = allAirports.begin(); it_airport != allAirports.end(); it_airport++) { Airport* airport = it_airport->second; for (AirplaneMap::iterator it_airplane = airport->getAirplanes().begin(); it_airplane != airport->getAirplanes().end(); ) { Airplane* airplane = it_airplane->second; if (airport->getFreeCompatibleRunway(airplane) == NULL) { errorStream << "Airplane has nowhere to land: " << airplane->getCallsign() << " (" << airplane->getNumber() << ") " << std::endl; airplane->printInfo(errorStream); parseResult = ParseEnum::kPartial; for (RunwayMap::iterator it_runway = airport->getRunways().begin(); it_runway != airport->getRunways().end(); it_runway++) { it_runway->second->printInfo(errorStream); } }; AirplaneEnums::EType airplaneType = airplane->getType(); AirplaneEnums::ESize airplaneSize = airplane->getSize(); AirplaneEnums::EEngine airplaneEngine = airplane->getEngine(); unsigned int offset = 00; if (airplaneType == AirplaneEnums::kType_Private) { if (airplaneSize == AirplaneEnums::kSize_Small) { offset = 01; } else if (airplaneSize == AirplaneEnums::kSize_Medium) { if (airplaneEngine == AirplaneEnums::kEngine_Jet) { offset = 01000; } } } else if (airplaneType == AirplaneEnums::kType_Airline) { if (airplaneSize == AirplaneEnums::kSize_Medium) { if (airplaneEngine == AirplaneEnums::kEngine_Propeller) { offset = 02000; } else if (airplaneEngine == AirplaneEnums::kEngine_Jet) { offset = 03000; } } else if (airplaneSize == AirplaneEnums::kSize_Large) { if (airplaneEngine == AirplaneEnums::kEngine_Jet) { offset = 04000; } } } else if (airplaneType == AirplaneEnums::kType_Military) { if (airplaneSize == AirplaneEnums::kSize_Small) { if (airplaneEngine == AirplaneEnums::kEngine_Jet) { offset = 05000; } } else if (airplaneSize == AirplaneEnums::kSize_Large) { if (airplaneEngine == AirplaneEnums::kEngine_Propeller) { offset = 05000; } } } else if (airplaneType == AirplaneEnums::kType_Emergency) { if (airplaneSize == AirplaneEnums::kSize_Small) { if (airplaneEngine == AirplaneEnums::kEngine_Propeller) { offset = 06000; } } } if (offset == 00) { errorStream << "Invalid airplane combination: " << airplane->getCallsign() << " (" << airplane->getNumber() << ") " << std::endl; airplane->printInfo(errorStream); parseResult = ParseEnum::kPartial; delete it_airplane->second; airport->getAirplanes().erase(it_airplane++); } else { airplane->setSquawk(offset + std::distance(airport->getAirplanes().begin(), it_airplane)); it_airplane++; } } } xmlFile.Clear(); return std::pair<ParseEnum::EResult, std::map<std::string, Airport*> >(parseResult, allAirports); } std::map<std::string, std::string> Parser::convertXmlNodeToMap(TiXmlElement* object) { std::map<std::string, std::string> xmltomap; for (TiXmlElement* elem = object->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { std::string elemName = elem->Value(); TiXmlNode* elemChildElement = elem->FirstChildElement(); TiXmlNode* elemChildNode = elem->FirstChild(); if (elemChildElement == NULL) { if (elemChildNode != NULL) { if (xmltomap.find(elemName) == xmltomap.end()) { xmltomap[elemName] = elemChildNode->Value(); } else { errorStream << object->Value() << ": Duplicate node found. " << getRowAndColumnStr(elem) << std::endl; } } else { xmltomap[elemName] = ""; errorStream << object->Value() << ": Empty node found. " << getRowAndColumnStr(elem) << std::endl; } } else { if (elemName != "TAXIROUTE") { errorStream << object->Value() << ": Unrecognized child element. " << getRowAndColumnStr(elem) << std::endl; } } } return xmltomap; } std::vector<std::pair<bool, std::string> > Parser::extractTaxiRoute(TiXmlElement* object) { std::vector<std::pair<bool, std::string> > taxiroute; std::set<std::string> duplicateChecker; for (TiXmlElement* elem = object->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { std::string elemName = elem->Value(); TiXmlNode* elemChildNode = elem->FirstChild(); if (elemChildNode != NULL) { TiXmlText* elemChildNodeAsText = elemChildNode->ToText(); if (elemChildNodeAsText != NULL) { std::string locationName = elemChildNodeAsText->Value(); if (duplicateChecker.insert(locationName).second) { if (elemName == "taxipoint") { taxiroute.push_back(std::pair<bool, std::string>(false, locationName)); } else if (elemName == "crossing") { taxiroute.push_back(std::pair<bool, std::string>(true, locationName)); } else { errorStream << object->Value() << ": Unrecognized node name. " << getRowAndColumnStr(elemChildNodeAsText) << std::endl; } } else { errorStream << object->Value() << ": Duplicate crossing/taxipoint found. " << getRowAndColumnStr(elemChildNodeAsText) << std::endl; } } else { errorStream << object->Value() << ": Node does not contain text. " << getRowAndColumnStr(elemChildNode) << std::endl; } } else { errorStream << object->Value() << ": Node does not contain anything. " << getRowAndColumnStr(elem) << std::endl; } } return taxiroute; }
C#
UTF-8
2,016
2.890625
3
[]
no_license
using Chambers.Partners.Domain.Factories; using Chambers.Partners.Domain.Providers; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Chambers.Partners.Domain.Services { public class GameService : IGameService { private IGameFactory _factory; private ICardGameProvider _provider; public GameService( IGameFactory factory, ICardGameProvider provider ) { _factory = factory; _provider = provider; } public async Task<int> GetNextGameId() { return await _provider.GetNextGameIdentityAsync(); } public async Task<BlackJackGame> StartBlackJack(int playerId) { var game = await _factory.CreateBlackJackGame(playerId); game.DealCardToPlayer(2); await _provider.InsertOrUpdateAsync(game); return game; } public async Task<BlackJackGame> Hit(int gameId, int playerId) { var game = await _provider.GetAsync(gameId); if (game == null) throw new UnauthorizedAccessException("The game does not exist"); if (game.Player.Identity != playerId) throw new UnauthorizedAccessException("The player is not valid for this game"); game.DealCardToPlayer(1); await _provider.InsertOrUpdateAsync(game); return game; } public async Task<BlackJackGame> Stick(int gameId, int playerId) { var game = await _provider.GetAsync(gameId); if (game == null) throw new UnauthorizedAccessException("The game does not exist"); if (game.Player.Identity != playerId) throw new UnauthorizedAccessException("The player is not valid for this game"); game.Stick(); await _provider.InsertOrUpdateAsync(game); return game; } } }
Ruby
UTF-8
628
3.140625
3
[]
no_license
#--- # Excerpted from "Programming Ruby", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/ruby3 for more book information. #--- while line = gets next if line =~ /^\s*#/ # skip comments break if line =~ /^END/ # stop at end # substitute stuff in backticks and try again redo if line.gsub!(/`(.*?)`/) { eval($1) } # process line ... end
C++
UTF-8
4,006
3.03125
3
[]
no_license
/* * File: parser.cpp * Author: wutingyi * * Created on September 27, 2016, 1:29 PM */ #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <typeinfo> #include <iomanip> #include <cstring> #include <fstream> #include "Rparser.hpp" #include "Node.hpp" #include "Resistor.hpp" using namespace std; #define MAX_NODE_NUMBER 5000 int maxNodeNumber, maxResistors; void maxVal(int inputMaxNodeNumber, int inputMaxResistors){ if (inputMaxNodeNumber <= 0 || inputMaxResistors <= 0) { cout << "Error: maxVal arguments must be greater than 0" << endl; } else { maxNodeNumber = inputMaxNodeNumber; maxResistors =inputMaxResistors; cout << "New network: max node number is " << maxNodeNumber << "; max resistors is " << maxResistors << endl; //TODO: loop through both pointer array and free the memeory nodes = new Node * [maxNodeNumber]; for (int i = 0; i < MAX_RESISTORS_PER_NODE; i++){ nodes[i] = new Node[MAX_RESISTORS_PER_NODE]; } resistors = new Resistor * [maxResistors]; } } void insertR(string name, double resistance, int nodeID1, int nodeID2, int rIndex){ bool resExist = false; for (int i = 0;(resistors[i]) != NULL && i < maxResistors ; i++) { if(name == resistors[i]->getName()) { resExist = true; i = maxResistors; } } if (nodeID1 < 0 || nodeID2 < 0 || nodeID1 > maxNodeNumber || nodeID2 > maxNodeNumber) { cout << "Error: node "; if (nodeID1 < 0 || nodeID1 > maxNodeNumber) { cout << nodeID1; } else { cout << nodeID2; } cout << " is out of permitted range 0-" << maxNodeNumber << endl; } //print if resistor array is full else if (rIndex == maxResistors){ cout << "Error: resistor array is full" << endl; } //print if resistor array is full else if (!nodes[nodeID1]->canAddResistor(rIndex)|| !nodes[nodeID2]->canAddResistor(rIndex)) { cout << "Error: node is full" << endl; } /* else if (resExist) { cout << "Error: resistor " << name << " already exists" << endl; }*/ //print if both input NodeIDs are the same else if (nodeID1 == nodeID2) { cout << "Error: both terminals of resistor connect to node " << nodeID1 << endl; } //print regular output else { cout << "Inserted: resistor " << name << " "; cout << fixed << setprecision(2) << resistance; cout << " Ohms " << nodeID1 << " -> " << nodeID2 << endl; int endpoints_[2]; endpoints_[0] = nodeID1; endpoints_[1] = nodeID2; //add 1 resistor to resistor array with 2 entries in node array resistors[rIndex] = new Resistor(rIndex, name, resistance, &endpoints_[2]); rIndex+=1; } } void modifyR(string name, double resistance){ //print regular modifyR output cout << "Modified: resistor " << name << " to "; cout << fixed << setprecision(2) << resistance << " Ohms " << endl; } void printR(string name){ //print if name of resistor typed is 'all' if (name == "all") { cout << "Print: all resistors" << endl; } //print regular output else { cout << "Print: resistor " << name << endl; } } void printNode(int nodeID){ //print if the two nodeIDs are out of the correct range if (nodeID < 0 || nodeID > maxNodeNumber) { cout << "Error: node " << nodeID << " is out of permitted range 0-" << maxNodeNumber << endl; } //print regular output else { cout << "Connections at node " << nodeID << ": " << nodes[nodeID]->getNumRes() <<endl; } } void deleteR(){ cout << "Deleted: all resistors" << endl; }
C
UTF-8
166
2.765625
3
[]
no_license
#include<stdio.h> #include<conio.h> void main() { int input1,input2; scanf("%d%d",&input1,&input2); for(i=input1;i<input2;i++) { if(i%2!=0) { printf("\t%d",i); } } }
Java
UTF-8
16,898
2.140625
2
[]
no_license
/** * */ package controllers.vm; import helpervm.OfferingHelper; import helpervm.VMHelper; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; import models.vm.OfferingModel; import models.vm.VMModel; import models.vm.VMModel.VMStatus; import org.ats.common.ssh.SSHClient; import org.ats.component.usersmgt.group.Group; import org.ats.jenkins.JenkinsMaster; import org.ats.jenkins.JenkinsSlave; import org.ats.knife.Knife; import play.Logger; import azure.AzureClient; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.Session; import com.microsoft.windowsazure.core.OperationStatusResponse; import com.microsoft.windowsazure.management.compute.models.RoleInstance; import com.mongodb.BasicDBObject; /** * @author <a href="mailto:haithanh0809@gmail.com">Nguyen Thanh Hai</a> * * Sep 19, 2014 */ public class VMCreator { public static void createCompanySystemVM(Group company) throws Exception { AzureClient azureClient = VMHelper.getAzureClient(); String normalName = new StringBuilder().append(company.getString("name")).append("-system").toString(); String name = normalizeVMName(new StringBuilder(normalName).append("-").append(company.getId()).toString()); Future<OperationStatusResponse> response = azureClient.createSystemVM(name); Logger.info("Submited request to create system vm"); while (!response.isDone()) { System.out.print('.'); Thread.sleep(3000); } OperationStatusResponse status = response.get(); RoleInstance vm = azureClient.getVirutalMachineByName(name); VMModel vmModel = VMHelper.getVMByName(name); vmModel.put("public_ip", vm.getIPAddress().getHostAddress()); VMHelper.updateVM(vmModel); Logger.info("Create system vm " + name + " has been " + status.getStatus()); List<OfferingModel> list = OfferingHelper.getEnableOfferings(); Collections.sort(list, new Comparator<OfferingModel>() { @Override public int compare(OfferingModel o1, OfferingModel o2) { return o2.getMemory() - o1.getMemory(); } }); OfferingModel defaultOffering = list.get(0); OfferingHelper.addDefaultOfferingForGroup(company.getId(), defaultOffering.getId()); //add to reverse proxy final String vmSystemName = name; final String vmSystemIp = vm.getIPAddress().getHostAddress(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { //add guacamole to reverse proxy Logger.debug("VMName:" + vmSystemName + " ip:" + vmSystemIp ); Session session = SSHClient.getSession("127.0.0.1", 22, VMHelper.getSystemProperty("default-user"), VMHelper.getSystemProperty("default-password")); ChannelExec channel = (ChannelExec) session.openChannel("exec"); String command = "sudo -S -p '' /etc/nginx/sites-available/manage_location.sh " + vmSystemIp + " " + vmSystemName + " 0"; Logger.info("Command add to reverse proxy:" + command); channel.setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); out.write((VMHelper.getSystemProperty("default-password") + "\n").getBytes()); out.flush(); channel.disconnect(); //restart service nginx channel = (ChannelExec) session.openChannel("exec"); command = "sudo -S -p '' service nginx restart"; Logger.info("Command restart service nginx:" + command); channel.setCommand(command); out = channel.getOutputStream(); channel.connect(); out.write((VMHelper.getSystemProperty("default-password") + "\n").getBytes()); out.flush(); SSHClient.printOut(System.out, channel); channel.disconnect(); //add jenkin to reverse proxy if (SSHClient.checkEstablished(vmSystemIp, 22, 300)) { session = SSHClient.getSession(vmSystemIp, 22, VMHelper.getSystemProperty("default-user"), VMHelper.getSystemProperty("default-password")); channel = (ChannelExec) session.openChannel("exec"); channel = (ChannelExec) session.openChannel("exec"); command = "sudo -S -p '' /etc/guacamole/change_prefix_jenkin.sh " + vmSystemName; Logger.info("Command add to reverse proxy:" + command); channel.setCommand(command); out = channel.getOutputStream(); channel.connect(); out.write((VMHelper.getSystemProperty("default-password") + "\n").getBytes()); out.flush(); SSHClient.printOut(System.out, channel); channel.disconnect(); //restart jenkins service channel = (ChannelExec) session.openChannel("exec"); command = "sudo -S -p '' service jenkins restart"; Logger.info("Command restart service jenkins:" + command); channel.setCommand(command); out = channel.getOutputStream(); channel.connect(); out.write((VMHelper.getSystemProperty("default-password") + "\n").getBytes()); out.flush(); SSHClient.printOut(System.out, channel); channel.disconnect(); } session.disconnect(); VMModel vmModel = VMHelper.getVMByName(vmSystemName); vmModel.setStatus(VMStatus.Ready); VMHelper.updateVM(vmModel); } catch (Exception e) { throw new RuntimeException(e); } } }); thread.start(); } public static void destroyVM(VMModel vm) throws Exception { String vmId = vm.getId(); //remote node of chef server VMModel jenkins = VMHelper.getVMsByGroupID(vm.getGroup().getId(), new BasicDBObject("jenkins", true)).get(0); VMHelper.getKnife(jenkins).deleteNode(vm.getName()); //remove node of jenkins server try { String subfix = jenkins.getName() + "/jenkins"; new JenkinsSlave( new JenkinsMaster(jenkins.getPublicIP(), "http", subfix, 8080), vm.getPublicIP()).release(); } catch (IOException e) { Logger.debug("Could not release jenkins node ", e); } //remove node from guacamole boolean isGui = vm.getBoolean("gui"); Session session = SSHClient.getSession(jenkins.getPublicIP(), 22, jenkins.getUsername(), jenkins.getPassword()); ChannelExec channel = (ChannelExec) session.openChannel("exec"); String command = ""; if (isGui) { try { channel = (ChannelExec) session.openChannel("exec"); command = "sudo -S -p '' /etc/guacamole/manage_con.sh " + vm.getPublicIP() + " 5900 '" + VMHelper.getSystemProperty("default-password") + "' vnc 1"; channel.setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); out.write((jenkins.getPassword() + "\n").getBytes()); out.flush(); channel.disconnect(); } catch (Exception e) { Logger.error("Exception when run:" + e.getMessage()); } Logger.info("Command run add connection guacamole: " + command); } else { try { channel = (ChannelExec) session.openChannel("exec"); command = "sudo -S -p '' /etc/guacamole/manage_con.sh " + vm.getPublicIP() + " 22 '" + VMHelper.getSystemProperty("default-password") + "' ssh 1"; channel.setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); out.write((jenkins.getPassword() + "\n").getBytes()); out.flush(); channel.disconnect(); } catch (Exception e) { Logger.error("Exception when run:" + e.getMessage()); } Logger.info("Command run add connection guacamole: " + command); } //delete virtual machine from azure AzureClient azureClient = VMHelper.getAzureClient(); azureClient.deleteVirtualMachineByName(vmId); Logger.info("Destroying vm " + vmId); } public static String createNormalGuiVM(Group company) throws Exception { return createNormalVM(company, "Gui", "cats-ui-image"); } public static String createNormalNonGuiVM(Group company) throws Exception { return createNormalVM(company, "Non-Gui", "cats-non-ui-image"); } public static Map<String, ConcurrentLinkedQueue<String>> QueueHolder = new HashMap<String, ConcurrentLinkedQueue<String>>(); public static String createNormalVM(Group company, final String subfix, String template, final String ...recipes) throws Exception { AzureClient azureClient = VMHelper.getAzureClient(); OfferingModel offering = OfferingHelper.getDefaultOfferingOfGroup(company.getId()).getOffering(); final VMModel jenkins = VMHelper.getVMsByGroupID(company.getId(), new BasicDBObject("system", true).append("jenkins", true)).get(0); //create instance String normalName = getAvailableName(company, subfix, 0); final String name = normalizeVMName(new StringBuilder(normalName).append("-").append(company.getId()).toString()); QueueHolder.put(name, new ConcurrentLinkedQueue<String>()); Future<OperationStatusResponse> response = azureClient.createVM(name, template, offering.getId()); Logger.info("Submited request to create test vm"); while (!response.isDone()) { System.out.print('.'); Thread.sleep(3000); } OperationStatusResponse status = response.get(); Logger.info("Create " + subfix + " vm " + name + " has been " + status.getStatus()); //get vm by name final RoleInstance vm = azureClient.getVirutalMachineByName(name); VMModel vmModel = VMHelper.getVMByName(name); if (vmModel == null) { vmModel = new VMModel(name, name, company.getId(), template, template, vm.getIPAddress().getHostAddress(), VMHelper.getSystemProperty("default-user"), VMHelper.getSystemProperty("default-password")); vmModel.put("gui", "Non-Gui".equals(subfix) ? false : true); vmModel.put("system", false); vmModel.put("offering_id", offering.getId()); vmModel.setStatus(VMStatus.Initializing); vmModel.put("normal_name", normalName); VMHelper.createVM(vmModel); } else { vmModel.put("public_ip", vm.getIPAddress().getHostAddress()); VMHelper.updateVM(vmModel); } //Run recipes Thread thread = new Thread() { @Override public void run() { ConcurrentLinkedQueue<String> queue = QueueHolder.get(name); String ip = vm.getIPAddress().getHostAddress(); try { queue.add("Checking SSHD on " + ip); if (SSHClient.checkEstablished(ip, 22, 300)) { queue.add("Connection is established"); Session session = SSHClient.getSession(ip, 22, VMHelper.getSystemProperty("default-user"), VMHelper.getSystemProperty("default-password")); //sudo ChannelExec channel = (ChannelExec) session.openChannel("exec"); //create jenkins slave Logger.debug("Ip Jenkins Master: "+jenkins.getPublicIP()); String jenkins_subfix = jenkins.getName() + "/jenkins"; JenkinsMaster master = new JenkinsMaster(jenkins.getPublicIP(), "http", jenkins_subfix, 8080); Logger.debug("Ip new vm: " + ip); Map<String, String> env = new HashMap<String, String>(); if ("Gui".equals(subfix)) env.put("DISPLAY", ":0"); JenkinsSlave slave = new JenkinsSlave(master, ip, env); if (slave.join()) { queue.add("Create slave " + ip + " sucessfully"); } else { queue.add("Can not create slave" + ip); } //run Jmeter if("Non-Gui".equals(subfix)) { String command = "nohup jmeter-start > jmeter-server.log 2>&1 &"; channel.setCommand(command); channel.connect(); queue.add("Execute command: " + command); SSHClient.printOut(queue, channel); channel.disconnect(); } //Point jenkins ip to cloud-ats.cloudapp.net channel = (ChannelExec) session.openChannel("exec"); String command = "sed 's/127.0.1.1/" + jenkins.getPublicIP() + "/' /etc/hosts > /tmp/hosts"; channel.setCommand(command); channel.connect(); queue.add("Executed command: " + command); channel.disconnect(); //replace /etc/hosts channel = (ChannelExec) session.openChannel("exec"); command = "sudo -S -p '' cp /tmp/hosts /etc/hosts"; channel.setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); out.write((VMHelper.getSystemProperty("default-password") + "\n").getBytes()); out.flush(); //disconnect session session.disconnect(); Logger.debug("Starting bootstrap node"); Knife knife = VMHelper.getKnife(jenkins); knife.bootstrap(ip, name, VMHelper.getSystemProperty("default-user"), VMHelper.getSystemProperty("default-password"), queue, recipes); //register guacamole if("Gui".equals(subfix)){ command = "sudo -S -p '' /etc/guacamole/manage_con.sh " + ip + " 5900 '"+VMHelper.getSystemProperty("default-password") + "' vnc 0"; } else if ("Non-Gui".equals(subfix)) { command = "sudo -S -p '' /etc/guacamole/manage_con.sh " + ip + " 22 '"+VMHelper.getSystemProperty("default-password") + "' ssh 0"; } session = SSHClient.getSession(jenkins.getPublicIP(), 22, jenkins.getUsername(), jenkins.getPassword()); channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); out = channel.getOutputStream(); channel.connect(); out.write((VMHelper.getSystemProperty("default-password") + "\n").getBytes()); out.flush(); channel.disconnect(); session.disconnect(); queue.add("Command run add connection guacamole: "+ command); //Update vm status to Ready VMModel vmModel = VMHelper.getVMByName(name); vmModel.setStatus(VMStatus.Ready); VMHelper.updateVM(vmModel); } else { queue.add("Cloud not establish connection in 120s"); } } catch (Exception e) { Logger.debug("Has an error when create vm", e); queue.add("setup.vm.error"); } finally { queue.add("log.exit"); } } }; // thread.start(); return name; } public static String getAvailableName(Group company, String subfix, int index) throws Exception { AzureClient azureClient = VMHelper.getAzureClient(); String normalName = new StringBuilder(company.getString("name")).append("-").append(subfix).append("-").append(index).toString(); String name = normalizeVMName(new StringBuilder(normalName).append("-").append(company.getId()).toString()); RoleInstance vm = azureClient.getVirutalMachineByName(name); if (vm == null) return normalName; return getAvailableName(company, subfix, index + 1); } /** * Instance name can not be longer than 63 characters. * Only ASCII letters a~z, A~Z, digits 0~9, hyphen are allowed. Must start with a letter and end with a letter or a digit. */ public static String normalizeVMName(String name) { StringBuilder sb = new StringBuilder(); char[] chars = name.toCharArray(); for (int i = 0; i < chars.length; i++) { char ch = chars[i]; if (ch >= 'a' && ch <= 'z') sb.append(ch); else if (ch >= 'A' && ch <= 'Z') sb.append(ch); else if (ch >= '0' && ch <= '9') sb.append(ch); else if (ch == '-' && i != 0 && i != 62 && i != chars.length -1) sb.append(ch); else { if (i == 0) sb.append('a'); else if (i == 62) sb.append('a'); else if (i == chars.length -1) sb.append('z'); else sb.append('-'); } } name = sb.length() > 63 ? sb.substring(0, 63) : sb.toString(); return name; } }
Java
UTF-8
1,948
2.4375
2
[]
no_license
package com.city.oa.controller; import com.city.oa.dto.CommonResult; import com.city.oa.model.Photo; import com.city.oa.service.PhotoService; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; @RestController @RequestMapping("/photo") public class PhotoController { @Resource PhotoService service; @PostMapping("/add/{id}") public CommonResult<String> addPhotoForId(@PathVariable("id")int id, MultipartFile file) { if (file==null||file.isEmpty()) { return new CommonResult(444,"上传失败,请选择文件",null); } String date = service.upload(id, file); return new CommonResult(200,"上传成功",date); } @PostMapping("/modify/{id}") CommonResult<String> modifyPhotoForId(@PathVariable("id") int id,MultipartFile file){ System.out.println(file.getSize()); if (file==null||file.isEmpty()) { return new CommonResult(444,"上传失败,请选择文件",null); } service.delete(id); String date = service.upload(id, file); return new CommonResult(200,"修改成功",date); } @GetMapping("/delete/{id}") public CommonResult<String> deletePhotoForId(@PathVariable("id")int id) { service.delete(id); return new CommonResult(200,"删除成功","ok"); } @GetMapping("/get/{id}") void getPhotoById(@PathVariable("id") Integer id, HttpServletResponse response)throws Exception{ Photo photo = service.getPhotoById(id); if(photo!=null&&photo.getPhotoType()!=null) { response.setContentType(photo.getPhotoType()); OutputStream out=response.getOutputStream(); out.write(photo.getPhoto()); out.flush(); out.close(); } } }
Java
UTF-8
582
1.84375
2
[]
no_license
package session1; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class searchingELement { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver","D://chromedriver.exe"); ChromeDriver d=new ChromeDriver(); d.get("http://www.newtours.demoaut.com"); d.manage().window().maximize(); d.findElement(By.linkText("REGISTER")).click(); d.findElement(By.name("country")).sendKeys("INDIA"); } }
Markdown
UTF-8
11,230
3.125
3
[]
no_license
![](https://p3.ssl.qhimg.com/t01f8755aedb0dd9f8b.png) > 天街小雨润如酥,草色遥看近却无。最是一年春好处,绝胜烟柳满皇都。 —— 唐.韩愈 《早春呈水部张十八员外二首》 ### 引子 几个月之前,chunpu小编曾经在《[震惊! 滑动验证码竟然能这样破解](https://mp.weixin.qq.com/s/NDIEaAhMHdrC3l9DV8z00g)》一文中给大家展示了使用支持WebDriver标准的Firefox破解滑动验证码的示例,脑洞之大,构思之巧,笔法幽默,叹为观止,也极大的燃起了笔者对此的兴趣。 这篇文章就带大家使用目前较为流行的Puppeteer完成这件事情。 当我们把WebDriver和Puppeteer放在一起的时候,还是有必要说明一下这二者的区别。 [WebDriver标准](https://www.w3.org/TR/webdriver1/),可以远程的操控目标浏览器。标准是语言无关、平台无关的。 有一种叫Selenium的框架,实现了WebDriver协议。Selenium通过各种浏览器的driver来驱动相应的浏览器,可以支持Python、Java、C#、JavaScript等语言的编程,同时还可以通过Selenium Server 实现集群测试。 Puppeteer是Google出品的NodeJS包。使用Node脚本通过DevTools Protocol协议,直接对Chrome浏览器进行操作。由于有Chrome官方的背景,Puppeteer和Chrome浏览器配合得异常完美。由于几乎直接操作浏览器,也使得操作的效率高于Selenium。Puppeteer官方给出了下面这张图,表述了Puppeteer中各个部分的关系。 ![](https://p3.ssl.qhimg.com/t01dae7ef9a392bb1da.png) 随着Puppeteer项目的发展,Puppeteer也正在向着跨浏览器方向发展。比如[Puppeteer-firefox](https://github.com/GoogleChrome/puppeteer/tree/master/experimental/puppeteer-firefox),目前正在实验阶段。对于使用其他语言操控Puppeteer,[官方暂时没有计划](https://github.com/GoogleChrome/puppeteer/issues/575#issuecomment-325397258),不过对于python,有一个非官方的实现[pypuppeteer](https://pypi.org/project/pyppeteer/)。 因此,就目前的技术体系来看,如果需要多语言、带集群支持、多浏览器支持,请选择Selenium;如果需要更快速的执行、更易上手的API,或者无需考虑多浏览器,请考虑Puppeteer。 ### 分析滑动验证码 验证码之所以存在,其实就是要区别出“人”和“机器”。特别的,对于滑动验证码,需要根据滑动的动作判断出操作者是人与否。这显然是与自动化测试是矛盾的。因此解决这个问题的关键点在于两点: 1. 准确地识别出验证码需要滑到的位置。 2. 以符合人类规律的形式把滑块滑到正确的位置 《震惊》一文中给出了一种方法,这里我们给出基于Puppeteer的一种可行做法。 笔者这里把识别过程分为三步: 1. 识别拖动终点地址 1. 拖动 1. 验证结果并区别对待 在这之前,我们先用Puppeteer把目标页面打开 ```JavaScript const URL = "http://www.geetest.com/type/" let browser const init = async () => { if (browser) { return; } browser = await puppeteer.launch({ "headless": false, "args": ["--start-fullscreen"] }); } const configPage = async (page) => { await page.setViewport({ width: 1280, height: 1040 }); } const toRightPage = async (page) => { await page.goto(URL) await page.evaluate(_ => { let rect = document.querySelector(".products-content") .getBoundingClientRect() window.scrollTo(0, rect.top - 30) }) await page.waitFor(1000) await page.click(".products-content li:nth-child(2)") } ~(async (page) => { await configPage(page) await toRightPage(page) })() ``` Puppeteer的大多数方法都是异步的,为了代码更加易读,官方建议更多使用await/async来操作。上面这一段代码的含义是:使用Puppeteer打开页面,全屏化,打开相应的TAB。并滚动至相应的位置。 如果无需看到跳出的Chrome,可以把`"headless": false`改为true。就更像一个命令行程序了。当然在这个例子里我们还是要看到浏览器执行效果的。 为了看到浏览器元素结构,可以在调试时候,打开devtools。方法是在lanch方法中设置`devtools: true` #### 识别拖动终点地址 首先要做到的是,识别拖动终点的位置。通过分析页面看到,拖动目标是一个黑色的缺口。这个缺口实际上是勾画在一个`canvas.geetest_canvas_bg`元素上。 ![](https://p3.ssl.qhimg.com/t01a38af8c532c0f57b.png) 为了识别出缺口的初始位置,我们需要得到一张没有缺口的图像。实际上,这张图片位于另一个canvas元素`canvas.geetest_canvas_fullbg`上。 理论上,Puppeteer可以进行对页面、元素等进行截图。然后分析图片的色彩数据。这时候,因为`canvas.geetest_canvas_fullbg`本身处于不可见状态,需要调用脚本将其变为可见,然后也可以得到它: ![](https://p0.ssl.qhimg.com/t01a89fff8cdb95da33.png) 不过,今时今地我们来偷个懒。因为页面上的元素就是canvas,而canvas本身就有`getImageData`方法。特别懒的笔者决定直接从页面的canvas吐出数据。这里,我们可以把方法封装起来,然后通过Puppeteer提供的注入方法,把这个方法直接注入到页面里。 ```javascript const injectedScript = ` const getCanvasValue = (selector) => { let canvas = document.querySelector(selector) let ctx = canvas.getContext('2d') let [width, height] = [canvas.width, canvas.height] let rets = [...Array(height)].map(_ => [...Array(width)].map(_ => 0)) for (let i = 0; i < height; ++i) { for (let j = 0; j < width; ++j) { rets[i][j] = Object.values(ctx.getImageData(j,i,1,1).data) } } return rets } ` ``` 此时调用Puppeteer提供的注入方法`addScriptTag`就可以在上下文中加入这个方法。 ```JavaScript await page.addScriptTag({content: injectedScript}) ``` 当然这依然是异步方法。后面我们就可以在页面中通过调用注入的`getCanvasValue`方法来获取所选canvas的颜色值了。 这当然是投机取巧的办法,如果目标对象不是canvas,就只好老老实实的截图获取,同时,对于不可见的元素,也可以通过`addScriptTag`的方法,注入JavaScript以改变可见性,以便正确地截图。 仔细观察原图和带缺口的图,发现只要取得两个图片像素值的差集,最左边的坐标就是拖动目的地。这里,带缺口的图上面有一个浅色的干扰图。可以在对比“相等”时候,增加一些阀值,定义“相等”为容许有一定范围内的差异。 ```JavaScript const THRESHOLD = 70 const _equals = (a, b) => { if (a.length !== b.length) { return false } for (let i = 0; i < a.length; ++i) { let delta = Math.abs(a[i] - b[i]) if (delta > THRESHOLD) { return false } } return true } const _differentSet = (a1, a2) => { let rets = [] a1.forEach((el, y) => { el.forEach((el2, x) => { if (!_equals(el2, a2[y][x])) { rets.push({ x, y, v: el2, v2: a2[y][x] }) } }) }) return rets } ``` 这时,取得差集的x最小值即可。 ```JavaScript const _getLeftest = (array) => { return array.sort((a, b) => { if (a.x < b.x) { return -1 } else if (a.x == b.x) { if (a.y <= b.y) { return -1 } return 1 } return 1 }).shift() } ``` 终点有了,起点即为0,因为我们拖动的对象为:`.geetest_slider_button`。这个圆钮始终位于左侧起始位置。 ![](https://p0.ssl.qhimg.com/t017b5df79f12e0bd34.png) 因此,识别任务完成:从0拖动到识别出的目标点的横坐标。 #### 拖动 Puppeteer不直接提供`drag`方法。不过提供了对mouse的控制方法。可以通过调用mouse的方法,模拟拖动。同时由于`boundingBox`方法获取的是圆钮左上角的坐标,需要适当的往内部移几个像素,否则鼠标“抓”不到圆钮。 ```JavaScript let slider = await page.waitFor(".geetest_slider_button") let sliderInfo = await slider.boundingBox() let m = page.mouse await m.move(sliderInfo.x + 5, sliderInfo.y + 6) await m.down() // 假装我是拖动代码 await m.up() ``` 下面需要模拟拖动。 这里可以随机分段,也可以模拟匀加速直线运动。但需要注意,一定不要使用匀速运动,并且速度不要太快,时间要稍长一些。 以模拟匀加速直线运动为例, 匀加速直线运动的公式为:`S = v0t + 1/2*a*t*t` 其中,S为位移,v0为初速度,t为时间,a为加速度。 因为我们的初速度为0,上式可以简化为:`S = 1/2*a*t*t`。 我们不需要真的用setInterval来解决,可以用generator来模拟每次调用,并假设每次调用都过了0.2秒,这样可以把每次位移的距离一次性算出来。 ```JavaScript let _moveTrace = function* (dis){ let trace = [] let t0 = 0.2 let curr = 0 let step = 0 let a = 0.8 while (curr < dis) { let t = t0 * (++step) curr = parseFloat((1 / 2 * a * t * t).toFixed(2)) trace.push(curr) } for (let i = 0; i < trace.length; ++i) { yield trace[i] } } ``` 使用时候,我们用generator的方式调用之,使用for...of,当generator结束返回,for...of也自动中止了。同时,为了真实性,可以做一些对y的随机指定(实际y是不会动的)。横坐标x也可以做一些超过再退回的扰动设置。 ```JavaScript let gen = _moveTrace(dest.x) for (let ret of gen) { await m.move(sliderInfo.x + ret, sliderInfo.y + 6 + _getY(-5, 40)) } await m.move(sliderInfo.x + dest.x, sliderInfo.y + 6 + _getY(-5, 40)) ``` 此时,拖动的任务基本完成。 #### 验证结果并区别对待 由于这些测试可能会有一定程度的误差,也会造成一些失败率。为了真正“自动”起来,需要对识别和拖动结果作出一些判断,对于错误的,重新启动测试。对于多次犯错的,重新刷新页面。 ```JavaScript let isSuccess = await page.evaluate(_ => { if (!!document.querySelector(".geetest_success_animate")) { return true } return false }) ``` 好了,Puppeteer这个任务的细节基本完成。 保存, 执行。 > 笔者放下鼠标,端起桌上的肥宅快乐水, 看着 Puppeteer 操作起了浏览器“木偶”。打开网页,点击按钮, 拖动滑块,滑块曲折前行,虽然有挫折,但是依然百折不回...摩擦摩擦, 似魔鬼的步伐, 似老奶奶颤巍巍的手。终于, 极验又一次显示出一个清爽绿色的横幅, 仿佛在向我们招手: 欢迎你, 人类。 ![](https://p3.ssl.qhimg.com/t015abee4711f6bb2a6.gif)
C#
UTF-8
843
2.53125
3
[ "MIT" ]
permissive
namespace SassSharp.Model.Nodes { internal class MixinNode : ScopeNode { private readonly VariableNode[] _args; public MixinNode(string name, VariableNode[] args) { Name = name; _args = args; } public string Name { get; set; } public void Initialize(IncludeNode includeNode) { SetContent(includeNode); var args = includeNode.Arguments; for (var i = 0; i < args.Count; i++) { SetVariable(new VariableNode(_args[i].Name, args[i])); } } public override void SetVariable(VariableNode node) { _variables[node.Name] = node; } public override string ToString() { return $"@mixin {Name}"; } } }
Python
UTF-8
676
3.5625
4
[ "MIT" ]
permissive
''' Scraped from http://quotes.toscrape.com ''' from bs4 import BeautifulSoup import requests URL = 'http://quotes.toscrape.com/page/' i = 1 def get_soup(url): res = requests.get(url) soup = BeautifulSoup(res.text,'lxml') return soup def quotes(soup): global i all_quotes = soup.find_all('div',{'class':'quote'}) for quote_box in all_quotes: quote = quote_box.find('span',{'class':'text'}).text author = quote_box.find('small',{'class':'author'}).text print("{:<4} {}\n-{:>5}\n\n".format(str(i)+')',quote,author)) i +=1 def main(): pages = 10 for p in range(1,pages+1): soup = get_soup(URL + str(p)) quotes(soup) if __name__ == '__main__': main()
PHP
UTF-8
849
2.875
3
[]
no_license
<?php namespace srag\CustomInputGUIs\Certificate\LearningProgressPie; /** * Class CountLearningProgressPie * * @package srag\CustomInputGUIs\Certificate\LearningProgressPie * * @author studer + raimann ag - Team Custom 1 <support-custom1@studer-raimann.ch> */ class CountLearningProgressPie extends AbstractLearningProgressPie { /** * @var int[] */ protected $count = []; /** * @param array $count * * @return self */ public function withCount(array $count): self { $this->count = $count; return $this; } /** * @inheritdoc */ protected function parseData(): array { if (count($this->count) > 0) { return $this->count; } else { return []; } } /** * @inheritdoc */ protected function getCount(): int { return array_reduce($this->count, function (int $sum, int $count): int { return ($sum + $count); }, 0); } }
Java
UTF-8
986
2.09375
2
[]
no_license
package net.slipp.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import net.slipp.model.Question; import net.slipp.model.User; import net.slipp.repository.QuestionRepository; @Controller @RequestMapping("/questions") public class QuestionController { @Autowired private QuestionRepository questionRepository; @GetMapping("/form") public String form() { return "/qna/form"; } @PostMapping("") public String create(HttpSession session, String title, String contents) { User sessionUser = (User) session.getAttribute("sessionedUser"); Question newQuestion = new Question(sessionUser, title, contents); questionRepository.save(newQuestion); return "redirect:/"; } }
JavaScript
UTF-8
356
3.5
4
[]
no_license
for (let i = 0; i < 99; i++){ console.log("counting up to 99") } for (let i = 99; i >= 0; i--){ console.log("counting down from 99") } for (let i = 0; i < 98; i += 2){ console.log("even ascending") } for (let i = 98; i >= 0; i -= 2){ console.log("even descending") } for (let i = 99; i >= 0; i -= 2){ console.log("odd descending") }
Swift
UTF-8
1,574
3.265625
3
[]
no_license
// // DesignCodeNeumorphism.swift // learn_Neumorphism_SwiftUI // // Created by Ashish Tyagi on 04/09/20. // Copyright © 2020 Ashish Tyagi. All rights reserved. // import SwiftUI let color = Color(red: 232/255, green: 238/255, blue: 246/255) struct DesignCodeNeumorphism: View { var body: some View { Group { Button("Hello world") { } .foregroundColor(Color.primary) .padding() .background( ZStack { RoundedRectangle(cornerRadius: 12, style: .continuous) .shadow( color: .white, radius: 12, x: -6, y: -8 ) .shadow( color: Color.black.opacity(0.8), radius: 12, x: 6, y: 8 ) .blendMode(.overlay) .padding(2) RoundedRectangle(cornerRadius: 12, style: .continuous) .foregroundColor(color) } ) } .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center) .background(color).edgesIgnoringSafeArea(.all) } } struct DesignCodeNeumorphism_Previews: PreviewProvider { static var previews: some View { DesignCodeNeumorphism() } }
JavaScript
UTF-8
2,964
3
3
[]
no_license
import React, { Component } from 'react'; import axios from 'axios'; import { FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap'; export default class GivePoints extends Component { constructor(props) { super(props); //bind this context this.givePoints = this.givePoints.bind(this); this.changeHandler = this.changeHandler.bind(this); this.state={ userList: [], points: '', user: '', reason: '' } } componentWillMount () { this.getUsers(); } //make changes to state when user fills out form changeHandler (e) { const key = e.target.id this.setState({ [key]: e.target.value }) } //gets users to populate give points list -- called on component will mount getUsers () { axios.get('/users') .then((users) => { this.setState({ userList: users.data }) }) } //adds points to database and refreshes points board on success via getPoints on app.jsx givePoints (e) { //don't refresh page to prevent re-rendering all components e.preventDefault(); axios.post('/addPoints', { user_id: this.state.user, points: this.state.points, reason: this.state.reason }) .then((response) => { //get scores - this allows us to update scores while only rerendering one component this.props.onSubmit(); //clear input fields this.setState({ points: '', user: '', reason: '' }) }) } //form uses changeHandler function above to log inputs to state render () { return( <div className="give_points"> <h3>Has someone earned more points?</h3> <form> <FormGroup> <ControlLabel>Give this many points</ControlLabel> <FormControl id="points" type="number" placeholder="Number of Points" value={this.state.points} onChange={this.changeHandler} /> </FormGroup> <FormGroup> <ControlLabel>To:</ControlLabel> <FormControl id="user" componentClass="select" placeholder="select" value={this.state.user} onChange={this.changeHandler}> <option key="blank" value="blank">Select A Player</option> {this.state.userList.map((user) => { return <option key={user.id} value={user.id}>{user.name}</option> })} </FormControl> </FormGroup> <FormGroup> <ControlLabel>For:</ControlLabel> <FormControl id="reason" type="text" placeholder="Reason" value={this.state.reason} onChange={this.changeHandler} /> </FormGroup> <Button type="submit" onClick={this.givePoints}> Submit </Button> </form> </div> ) } }
Java
UTF-8
1,523
2.609375
3
[]
no_license
package com.company; public class Creature { public int getHitpoints() { return hitpoints; } public void setHitpoints(int hitpoints) { this.hitpoints = hitpoints; } public int getStrength() { return strength; } public void setStrength(int strength) { this.strength = strength; } public int getAgility() { return agility; } public void setAgility(int agility) { this.agility = agility; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } private String name; private int level, hitpoints, strength, agility; /*public Creature(String ParName,String ParRole, int ParLevel, int ParExp, int ParHp, int ParStrengh, int ParAgility) { this.hitpoints = ParHp; this.role = ParRole; this.exp = ParExp; this.strength = ParStrengh; this.agility = ParAgility; this.name = ParName; this.level = ParLevel; }*/ /*public Creature(String ParName) { this.name = ParName; this.level = STARTINGLEVEL; this.exp = 0; }*/ /*public void statCheck() { if(this.getExp() > ) { } }*/ }
Markdown
UTF-8
2,544
2.703125
3
[]
no_license
# Exercise 4.4.2 Explore the dataset with Tableau Start Tableau ![start-tableau.png](../resources/start-tableau.png) In "Connect To a Server" select "PostgreSQL": ![tableau-connect-postgress.png](../resources/tableau-connect-postgress.png) In the connection dialog, specify **publicisglobalemeaptrsd.platform-query.adobe.io** as the "Server" and **80** as the "Port", you can find your user name and password to connect to Adobe Platform Query Service in the Platform UI, "Credentials" section of the Queries menu. ![query-service-credentials.png](../resources/query-service-credentials.png) Sign In: ![tableau-connection-dialog.png](../resources/tableau-connection-dialog.png) Click search (1) and enter your **ldap** into the search field, identify you table from the result set and drag (3) it onto the location named "Drag tables here". When finished, click on "Sheet 1" (3). ![tableau-drag-table.png](../resources/tableau-drag-table.png) To visualize our data on the map we need to convert longitude and latitude to dimensions. In "measures" select "Latitude" (1) and open the field's dropdown and select "Convert to Dimension" (2). Do the same for the "Longitude" measure. ![tableau-convert-dimension.png](../resources/tableau-convert-dimension.png) Drag the "Longitude" measure to the "Columns" and the "Latitude" measure to "Rows". Automatically the map of "Belgium" will appear with little dots representing the cities in out data set. ![tableau-drag-lon-lat.png](../resources/tableau-drag-lon-lat.png) Select "Measure Names" (1), open the dropdown and select "Add to Sheet" (2): ![tableau-select-measure-names.png](../resources/tableau-select-measure-names.png) You will now have a map, with dots of various sizes. The size indicates the number of call center interactions for that specific city. To vary the size of the dots, navigate to the right panel and open "Measure Values" (using the drop down icon). From the drop down list select "Edit Sizes". Play around with different sizes. ![tableau-vary-size-dots.png](../resources/tableau-vary-size-dots.png) To further display the data per "Call Topic), drag (1) the "Call Topic" dimension onto "Pages". Navigate through the different "call topics" using the "Call Topic" (2) on the right side of the screen: ![tableau-call-topic-navigation.png](../resources/tableau-call-topic-navigation.png) Congratulations! You have finished the Adobe Experience Platform Query Service Module. [Go Back to Module 4](../README.md) [Go Back to All Modules](../../README.md)
Python
UTF-8
2,382
3.109375
3
[ "Python-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
permissive
from pcc.AST.compiled_object import CompiledObjectType, CompiledObject from pcc.AST.statement import Statement from pcc.AST.expression import Expression class CompoundStatement(Statement): def __init__(self, depth): super(CompoundStatement, self).__init__(depth) def __str__(self): string = self._depth * ' ' + 'Compound: \n' for arg in self.statement_sequence: string += str(arg) if isinstance(arg, Expression): string += '\n' return string def get_return_type(self): """Get the return type. Returns: str: the return type """ return self.parent_node.get_return_type() def compile(self, assembler): """Compile this statement Args: assembler (Assembler): the assembler to use Returns: CompiledObject: the compiled version of this statement """ value = bytearray() relocation_objects = [] for statement in self.statement_sequence: compiled_object = statement.compile(assembler) if compiled_object is None: continue reloc_objects = compiled_object.relocation_objects for relocation_object in reloc_objects: additional_offset = len(value) relocation_object.offset += additional_offset relocation_objects.append(relocation_object) value += compiled_object.value size = len(value) compiled_object = CompiledObject('compoundStatement', size, value, CompiledObjectType.code, relocation_objects) return compiled_object def add_stack_variable(self, current_list): """Add all stack variable to the list Args: current_list(list[StackVariable]): the current list """ for statement in self.statement_sequence: statement.add_stack_variable(current_list) def get_stack_variable(self, variable_name): """Get the stack variable by name. Args: variable_name (str): the name of the variable Returns: StackVariable: the stack variable if found, else None """ return self.parent_node.get_stack_variable(variable_name)
Python
UTF-8
530
2.578125
3
[]
no_license
from flask import Flask, render_template import time, json, threading app = Flask(__name__) alive = 0 data = {} @app.route("/") def index(): return render_template("index.html") @app.route("/keep_alive", methods=["GET"]) def keep_alive(): global alive, data alive += 1 keep_alive_count = str(alive) data['keep_alive'] = keep_alive_count parsed_json = json.dumps(data) print(str(parsed_json)) return str(parsed_json) if __name__ == "__main__": app.run(host="127.0.0.1", port = 80)
Markdown
UTF-8
3,800
2.859375
3
[ "BSD-3-Clause" ]
permissive
# Stalis Stream Service [![Go Report Card](https://goreportcard.com/badge/github.com/Stalis/sittme-test-excercise)](https://goreportcard.com/report/github.com/Stalis/sittme-test-excercise) ## Описание SSS - заготовка микросервиса, предназначенного для потоковых трансляций данных на любые устройства и сервисы ## Запуск Для простого запуска необходимо перейти в корневую директорию репозитория и ввести команду ``` go run . <run-args> ``` Для конфигурирования используются следующие параметры запуска: ``` -host string Host IP address or DNS name (default "localhost") -path string Path for binding service (default "/") -port int Http server port (default 8080) -read-timeout duration Timeout for reading data -stream-timeout duration Timeout for finish stream after interrupted (default 5s) -tls-cert string Path to TLS certificate (default "cert.pem") -tls-key string Path to TLS key file (default "key.pem") -use-tls Enables HTTPS by TLS certificate -write-timeout duration Timeout for writing data ``` ## API В качестве API используется формат JSON REST по протоколу http ### Создание трансляции Для создания трансляции необходимо создать пустой POST-запрос на адрес сервиса. Ответ будет в таком формате: ```json { "type": "stream", "id": "<id трансляции>", "attributes": { "created": "<дата и время создания трансляции>", "state": "created", } } ``` ### Получение информации о трансляции Для этого нужно сделать GET-запрос с одним аргументом `id`, в котором нужно передать id созданной трансляции. Ответ будет такой же, как в предыдущем пункте ### Изменение состояния трансляции Для изменения состояния нужно сделать PUT-запрос с двумя параметрами: - `id` - id трансляции - `state` - желаемое состояние Состояния могут указываться как текстом(независимо то регистра), так и цифрами: - `"Created"` == 0 - `"Active"` == 1 - `"Interrupted"` == 2 - `"Finished"` == 3 При этом невозможно установить состояние `Created`, но из него можно установить состояние `Active`, а из него уже либо `Finished`, либо `Interrupted`. Из `Interrupted` можно перейти в `Active` в течение `-stream-timeout` или в `Finished`. По истечению `-stream-timeout` состояние меняется на `Finished` ## Удаление трансляции Для удаления трансляции необходимо сделать DELETE-запрос с одним аргументом `id` - id трансляции, которую необходимо удалить. Особого формата ответа не предусмотрено ## Ошибки При ошибках в работе сервера над запросом клиента, сервер возвращает следующий JSON-объект: ```json { "type": "error", "error": "<текст с информацией по ошибке>" } ```
SQL
UTF-8
1,050
3.078125
3
[]
no_license
DROP TABLE IF EXISTS `sf_comment`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sf_comment` ( `id` int(11) NOT NULL AUTO_INCREMENT, `commentable_model` varchar(30) DEFAULT NULL, `commentable_id` int(11) DEFAULT NULL, `comment_namespace` varchar(50) DEFAULT NULL, `title` varchar(100) DEFAULT NULL, `text` text, `author_id` int(11) DEFAULT NULL, `author_name` varchar(50) DEFAULT NULL, `author_email` varchar(100) DEFAULT NULL, `author_website` varchar(255) DEFAULT NULL, `created_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `comments_index` (`comment_namespace`,`commentable_model`,`commentable_id`), KEY `object_index` (`commentable_model`,`commentable_id`), KEY `author_index` (`author_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; LOCK TABLES `sf_comment` WRITE; /*!40000 ALTER TABLE `sf_comment` DISABLE KEYS */; /*!40000 ALTER TABLE `sf_comment` ENABLE KEYS */; UNLOCK TABLES;
Java
UTF-8
1,532
1.84375
2
[]
no_license
package com.mydataway.demo1; import com.mydataway.utils.SpringContextHolder; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration; /** * @author xuxueli 2018-10-28 00:38:13 */ @SpringBootApplication @EnableFeignClients(basePackages = {"com.mydataway.*","com.xxl.*"}) @EnableDiscoveryClient @ComponentScan(basePackages = {"com.mydataway.utils","com.mydataway.demo1.*"}) //@EnableCircuitBreaker public class Demo1Application { public static void main(String[] args) { SpringApplication.run(Demo1Application.class, args); } @Bean public SpringContextHolder springContextHolder() { return new SpringContextHolder(); } @Bean public ServletWebServerFactory webServerFactory() { TomcatServletWebServerFactory fa = new TomcatServletWebServerFactory(); fa.addConnectorCustomizers(connector -> connector.setProperty("relaxedQueryChars", "[]{}")); return fa; } }
C++
UTF-8
1,627
3.4375
3
[]
no_license
#include "IOManager.h" IOManager::IOManager() { } IOManager::~IOManager() { } /************************************************* The write function is used to write the log information to the output file. The parameters are a string, which is the log information, and the path of the output file. *************************************************/ void IOManager::write(string line, const char* path) { //Open output file ofstream outputFile; outputFile.open(path, ios_base::app); try { if (!outputFile) { cout << "Unable to open file.\n"; throw "No file found."; } } catch (char const* str) { cout << "Exception: " << str << endl; } outputFile << line; outputFile.close(); } /************************************************* The read function is used to read the information from the input file. The parameter is the path of the input file, and the function returns a string *************************************************/ string IOManager::read(const char* path) { //Open input file ifstream inputFile; inputFile.open(path); try { if (!inputFile) { cout << "Unable to open file.\n"; throw "No file found."; } } catch (char const* str) { cout << "Exception: " << str << endl; } string returnValue; while (!inputFile.eof()) { string input; getline(inputFile, input); returnValue.append(input); returnValue.append("\n"); } inputFile.close(); return returnValue; }
Markdown
UTF-8
3,578
2.53125
3
[]
no_license
SerialDV ======== **Warning** Since kernel 4.4.52 the default for FTDI devices (that is in the ftdi_sio kernel module) is not to set it as low latency. This results in the ThumbDV dongle not working anymore because its response is too slow to sustain the normal AMBE packets flow. The solution is to force low latency by changing the variable for your device (ex: /dev/ttyUSB0) as follows: `echo 1 | sudo tee /sys/bus/usb-serial/devices/ttyUSB0/latency_timer` **SerialDV** is inspired from the [OpenDV project](https://github.com/dl5di/OpenDV.git) but retains only the minimal interface to encode and decode audio with AMBE3000 based devices in packet mode over a serial link. For details on the packet interface of AMBE3000 chip download the documentation on [DVSI website](http://www.dvsinc.com/products/a3000.htm) <h1>Introduction</h1> **SerialDV** is designed with the following assumptions - One object controls one device in one thread. It is up to you to control the device in a separate thread or create a pool of threads for a pool of devices with load balancing. No fancy stuff here because fancy stuff depends too much on the environment. - The library manages the atomic operations of decoding one AMBE frame or encoding one audio frame in query/reply pairs or transactions. Each query is returned a complete reply or an error. There is no queuing mechanism whatsoever. - AMBE3000 chip has many modes and features the scope of this library is to provide an easy to use interface for the most popular digital voice modes i.e. D-Star and the DMR likes (DMR, YSF, P25, ...). Some more may be added in the future if the need arises. - It will work for both encoding and decoding <h1>Hardware</h1> This library can control the serial interface to the AMBE3000 chip in packet mode. There are several devices or hardware blocks that implement it. A popular and easy to use one because it works with the well known serial oved UDP using a FTDI chip is the [ThumbDV dongle](http://nwdigitalradio.com/thumbdv-and-dv3000-resource-page/). It can be purchased in the US or from several UK resellers. In Linux systems the FTDI driver will create a TTY device like `/dev/ttyUSB0` that you will use as the serial device name. <h1>Build and install</h1> As with all cmake based projects you have to create a build directory in your cloned copy of this repository and cd into it. Then to install in your own path say `/opt/install/serialdv`use the following cmake comamnd: `cmake -Wno-dev -DCMAKE_INSTALL_PREFIX=/opt/install/serialdv ..` Then to `make` and `make install` That's it! <h1>Usage</h1> <h2>Test program</h2> A test program `dvtest` is created in the `bin` subdirectory of the install directory. This program takes a raw audio samples file as input (S16LE 8 kS/s) encodes it then decodes it and writes the result to an output file with the same format (S16LE 8 kS/s). Standard input and/or standard output can be used for piped commands with the `-` special filename. Ex: `dvtest -D /dev/ttyUSB0 -f 1 -i ../samples/hts1a.raw -o test.raw` Then you can play back the file with sox package installed: `play -r 8k -e signed-integer -b 16 test.raw` The full list of parameters can be accessed with the on-line help: `dvtest -h` In the `samples` subdirectory of the source tree some sample audio files taken from the Codec2 project are provided: - `forig.raw`: female voice - `morig.raw`: male voice - `hts1a.raw`: another male voice - `vk5qi.raw`: amateur radio call test (VK5QI). This is a slightly longer sample with a male voice.
Java
UTF-8
1,096
2.734375
3
[]
no_license
package ladder; import ladder.domain.LadderCompensation; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LadderCompensationTest { LadderCompensation ladderCompensation = new LadderCompensation("꽝,5000,꽝,500"); @ParameterizedTest @DisplayName("유효하지 않은 인덱스의 보상을 부를 경우 실패") @ValueSource(ints = {4, 5, 6}) void FailIfGetCompensationIndexInvalid(int input) { assertThatThrownBy(() -> ladderCompensation.getCompensation(input)) .isInstanceOf(IllegalArgumentException.class); } @Test @DisplayName("게임 보상의 수가 실제 입력과 같은지 확인") void IsNumberOfCompensationSizeEqualWithInput() { int actual = ladderCompensation.getNumberOfCompensation(); assertThat(actual).isEqualTo(4); } }
Java
UTF-8
17,161
2.390625
2
[]
no_license
package net.markmakinen.duckclient; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import net.markmakinen.duckclient.backend.BackendClient; import net.markmakinen.duckclient.backend.GotSightingsListener; import net.markmakinen.duckclient.backend.GotSpeciesListener; import net.markmakinen.duckclient.backend.SightingSaveListener; import net.markmakinen.duckclient.model.Sighting; import net.markmakinen.duckclient.model.Species; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormat; import java.util.ArrayList; import java.util.Comparator; /** * The Main Activity of the Application */ public class MainActivity extends AppCompatActivity { private SightingArrayAdapter saa; // Custom ArrayAdapter for Sightings private BackendClient bc; // Backend client instance private SwipeRefreshLayout refreshLayout; // Layout containing the ListView private boolean userRefresh = false; // True if the refresh was done by the user private ArrayList<Species> allowedSpecies; // List of allowed species; comes from the backend private boolean currentSortingAscending = false; // Defaults to descending; greater dates are on top of the listing private ListView sightingListView; // ListView containing the Sightings @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DuckClient.backendURI == null) finish(); // Close the app if the backend URI was invalid setContentView(R.layout.activity_main); allowedSpecies = new ArrayList<>(); // Floating Action Button FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.actionButton); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showCreateNewSightingDialog(allowedSpecies); } }); // Floating sorting button FloatingActionButton fabSort = (FloatingActionButton)findViewById(R.id.sortActionButton); fabSort.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { currentSortingAscending = !currentSortingAscending; sortSightings(currentSortingAscending); } }); // Initialize SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout)findViewById(R.id.activity_main); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // User wants to refresh the list userRefresh = true; refreshSightings(); } }); // Initialize Sighting ListView saa = new SightingArrayAdapter(this, new ArrayList<Sighting>()); sightingListView = (ListView)findViewById(R.id.sightingListView); sightingListView.setAdapter(saa); sightingListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Sighting sighting = saa.getItem(i); Log.d("DuckClient", "User clicked Sighting: " + sighting.getSightingId() + ", " + sighting.getDescription()); showSightingInfoDialog(sighting); } }); // Create a new BackendClient instance bc = new BackendClient(DuckClient.backendURI); // Get species from the server refreshSightings(); } /** * Sorts the Sighting listing by datetime ascending or descending * @param ascending true if sorting must be ascending, false if descending */ private void sortSightings(final boolean ascending) { saa.sort(new Comparator<Sighting>() { @Override public int compare(Sighting a, Sighting b) { if (ascending) return a.getDateTime().compareTo(b.getDateTime()); return b.getDateTime().compareTo(a.getDateTime()); } }); sightingListView.startLayoutAnimation(); } /** * Refreshes the Sighting listing */ private void refreshSightings() { if (refreshLayout == null || bc == null) return; // Run this on the UI thread so we can use this method from other threads runOnUiThread(new Runnable() { @Override public void run() { refreshLayout.setRefreshing(true); bc.getSpecies(new GotSpeciesListener() { @Override public void gotSpecies(ArrayList<Species> species) { Log.i("DuckClient", "Got " + species.size() + " species!"); // Set allowed species allowedSpecies = species; // Get sightings bc.getSightings(new GotSightingsListener() { @Override public void gotSightings(ArrayList<Sighting> sightings) { // Populate the Sighting ListView Log.i("DuckClient", "Got " + sightings.size() + " sightings!"); saa.clear(); saa.addAll(sightings); sortSightings(currentSortingAscending); refreshLayout.setRefreshing(false); if (userRefresh) Snackbar.make(refreshLayout, R.string.sightings_updated, Snackbar.LENGTH_SHORT).show(); userRefresh = false; } // Couldn't get sightings @Override public void gotError(String msg) { refreshLayout.setRefreshing(false); String snackMsg = getResources().getString(R.string.sightings_get_failed, msg); Snackbar.make(refreshLayout, snackMsg, Snackbar.LENGTH_LONG).show(); userRefresh = false; } }); } // Couldn't get species @Override public void gotError(String msg) { Log.e("DuckClient", "Species getting failed with error: " + msg); refreshLayout.setRefreshing(false); String snackMsg = getResources().getString(R.string.species_get_failed, msg); Snackbar.make(refreshLayout, snackMsg, Snackbar.LENGTH_LONG).show(); userRefresh = false; } }); } }); } /** * Create and display Sighting info dialog * @param sighting Sighting to show */ private void showSightingInfoDialog(Sighting sighting) { // Use custom layout LayoutInflater inflater = LayoutInflater.from(MainActivity.this); View view = inflater.inflate(R.layout.dialog_sighting_info, null); // Set date and description TextView dateView = (TextView)view.findViewById(R.id.sightingInfoDatetime); TextView descView = (TextView)view.findViewById(R.id.sightingInfoDescription); dateView.setText(sighting.getDateTimeText()); descView.setText(sighting.getDescription()); // Create AlertDialog and display it AlertDialog dialog = new AlertDialog.Builder(MainActivity.this) .setTitle(sighting.getCountAndSpeciesText()) .setView(view) .setPositiveButton(android.R.string.ok, null) .create(); dialog.show(); } /** * Create and display Sighting creation dialog */ private void showCreateNewSightingDialog(ArrayList<Species> allowedSpecies) { // Use custom layout LayoutInflater inflater = LayoutInflater.from(MainActivity.this); View view = inflater.inflate(R.layout.dialog_new_sighting, null); final Sighting newSighting = new Sighting(); // Get Views final Spinner speciesSpinner = (Spinner)view.findViewById(R.id.newSightingSpeciesSpinner); TextView dateTimeHeader = (TextView)view.findViewById(R.id.newSightingDateTimeHeader); final TextView dateView = (TextView)view.findViewById(R.id.newSightingDate); final TextView timeView = (TextView)view.findViewById(R.id.newSightingTime); final EditText countView = (EditText)view.findViewById(R.id.newSightingCount); final EditText descView = (EditText)view.findViewById(R.id.newSightingDescription); // Populate species spinner ArrayAdapter<Species> speciesAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, allowedSpecies); speciesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); speciesSpinner.setAdapter(speciesAdapter); // Populate Date and Time fields LocalDateTime now = LocalDateTime.now(); newSighting.setDateTime(now.toDateTime().withZone(DateTimeZone.UTC)); dateView.setText(DateTimeFormat.fullDate().print(now)); timeView.setText(DateTimeFormat.fullTime().print(now)); NewSightingDateTimeClickHandler dateTimeHandler = new NewSightingDateTimeClickHandler(new SightingDateTimeSetListener() { @Override public void dateTimeSet(DateTime selected) { LocalDateTime selectedLocal = selected.withZone(DateTimeZone.getDefault()).toLocalDateTime(); dateView.setText(DateTimeFormat.fullDate().print(selectedLocal)); timeView.setText(DateTimeFormat.fullTime().print(selectedLocal)); newSighting.setDateTime(selected); } }); // Set click handler for the date and time fields // This is needed so we can display a date and a time picker. dateTimeHeader.setOnClickListener(dateTimeHandler); dateView.setOnClickListener(dateTimeHandler); timeView.setOnClickListener(dateTimeHandler); countView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) {} @Override public void onTextChanged(CharSequence text, int start, int before, int count) { if (text.length() == 0) { countView.setError(getResources().getString(R.string.new_sighting_count_empty)); } else if (Integer.parseInt(text.toString()) == 0) { countView.setError(getResources().getString(R.string.new_sighting_count_zero)); } } }); // Create dialog AlertDialog dialog = new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.new_sighting_title) .setView(view) .setPositiveButton(R.string.save_new_sighting, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // Set Sighting values // Species Species selSpecies = (Species)speciesSpinner.getSelectedItem(); newSighting.setSpecies(selSpecies); // Count int count; try { count = Integer.parseInt(countView.getText().toString()); } catch (NumberFormatException e) { Snackbar.make(refreshLayout, R.string.new_sighting_count_empty, Snackbar.LENGTH_LONG).show(); return; } newSighting.setCount(count); // Description String desc = descView.getText().toString(); newSighting.setDescription(desc); // Save the created Sighting bc.saveSighting(newSighting, new SightingSaveListener() { @Override public void saveCompleted() { Log.i("DuckClient", "New Sighting saved!"); Snackbar.make(refreshLayout, R.string.new_sighting_save_successful, Snackbar.LENGTH_LONG).show(); // Update ListView refreshSightings(); } @Override public void saveFailed(String msg) { Log.e("DuckClient", "New Sighting save failed!"); String snackMsg = getResources().getString(R.string.new_sighting_save_failed, msg); Snackbar.make(refreshLayout, snackMsg, Snackbar.LENGTH_LONG).show(); } }); } }) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.show(); } /** * Interface for NewSightingDateTimeClickHandler * dateTimeSet gets called when the user has selected both date and time */ interface SightingDateTimeSetListener { void dateTimeSet(DateTime selected); } /** * Handler for Sighting creation dialog date and time field onClick */ class NewSightingDateTimeClickHandler implements View.OnClickListener { DateTime selected; SightingDateTimeSetListener listener; boolean selectionComplete = false; /** * Constructor * @param listener Listener to notify when user has chosen a date and a time */ public NewSightingDateTimeClickHandler(SightingDateTimeSetListener listener) { this.listener = listener; } @Override public void onClick(View view) { final DateTime now = DateTime.now(); // Create and show DatePickerDialog selectionComplete = false; DatePickerDialog dpd = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, final int year, final int month, final int dayOfMonth) { // When the user has chosen a date, he/she will choose a time TimePickerDialog tpd = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int hours, int minutes) { // Create a DateTime from the selected date and time // month+1 because DatePickerDialog uses month numbering from 0 to 11, where 0 is January and 11 is December selected = new DateTime(year, month+1, dayOfMonth, hours, minutes, DateTimeZone.getDefault()); selected = selected.withZone(DateTimeZone.UTC); // Use UTC instead of local timezone Log.i("onTimeSet", "Datetime: " + selected.toString()); selectionComplete = true; if (listener != null) listener.dateTimeSet(selected); // Notify the listener } }, now.getHourOfDay(), now.getMinuteOfHour(), true); if (!selectionComplete) { selectionComplete = true; tpd.show(); } } }, now.getYear(), now.getMonthOfYear()-1, now.getDayOfMonth()); dpd.show(); } } }
PHP
UTF-8
3,096
2.703125
3
[ "MIT" ]
permissive
<?php namespace Devlabs91\GenericOtaHotelApiService\EnumType; /** * This class stands for GlobalIndicatorType EnumType * Meta informations extracted from the WSDL * - documentation: Specifies the global travel area. * @subpackage Enumerations */ class GlobalIndicatorType { /** * Constant for value 'AP' * @return string 'AP' */ const VALUE_AP = 'AP'; /** * Constant for value 'AT' * @return string 'AT' */ const VALUE_AT = 'AT'; /** * Constant for value 'CT' * @return string 'CT' */ const VALUE_CT = 'CT'; /** * Constant for value 'DO' * @return string 'DO' */ const VALUE_DO = 'DO'; /** * Constant for value 'EH' * @return string 'EH' */ const VALUE_EH = 'EH'; /** * Constant for value 'FE' * @return string 'FE' */ const VALUE_FE = 'FE'; /** * Constant for value 'PA' * @return string 'PA' */ const VALUE_PA = 'PA'; /** * Constant for value 'PN' * @return string 'PN' */ const VALUE_PN = 'PN'; /** * Constant for value 'PO' * @return string 'PO' */ const VALUE_PO = 'PO'; /** * Constant for value 'RU' * @return string 'RU' */ const VALUE_RU = 'RU'; /** * Constant for value 'RW' * @return string 'RW' */ const VALUE_RW = 'RW'; /** * Constant for value 'SA' * @return string 'SA' */ const VALUE_SA = 'SA'; /** * Constant for value 'TS' * @return string 'TS' */ const VALUE_TS = 'TS'; /** * Constant for value 'WH' * @return string 'WH' */ const VALUE_WH = 'WH'; /** * Return true if value is allowed * @uses self::getValidValues() * @param mixed $value value * @return bool true|false */ public static function valueIsValid($value) { return ($value === null) || in_array($value, self::getValidValues(), true); } /** * Return allowed values * @uses self::VALUE_AP * @uses self::VALUE_AT * @uses self::VALUE_CT * @uses self::VALUE_DO * @uses self::VALUE_EH * @uses self::VALUE_FE * @uses self::VALUE_PA * @uses self::VALUE_PN * @uses self::VALUE_PO * @uses self::VALUE_RU * @uses self::VALUE_RW * @uses self::VALUE_SA * @uses self::VALUE_TS * @uses self::VALUE_WH * @return string[] */ public static function getValidValues() { return array( self::VALUE_AP, self::VALUE_AT, self::VALUE_CT, self::VALUE_DO, self::VALUE_EH, self::VALUE_FE, self::VALUE_PA, self::VALUE_PN, self::VALUE_PO, self::VALUE_RU, self::VALUE_RW, self::VALUE_SA, self::VALUE_TS, self::VALUE_WH, ); } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } }
Java
UTF-8
2,034
2.34375
2
[]
no_license
package com.example.restaurant.controllers; import javax.ws.rs.PathParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.example.restaurant.models.OrderRequest; import com.example.restaurant.models.OrderResponse; import com.example.restaurant.services.OrderService; import com.example.restaurant.utils.Constants; @RequestMapping("/restaurant") @RestController public class OrderController { @Autowired private OrderService orderService; @RequestMapping(path = "/order", method = RequestMethod.POST) public ResponseEntity<OrderResponse> placeOrder(@RequestBody OrderRequest request) { OrderResponse response = orderService.placeOrder(request); return ResponseEntity.status(HttpStatus.CREATED).header(Constants.LOCATION_HEADER, "/order/" + response.getOrderId()) .body(response); } @RequestMapping(path = "/order/${orderId}", method = RequestMethod.PUT) public ResponseEntity<OrderResponse> updateOrder(@PathParam(value = "orderId") String orderId, @RequestBody OrderRequest request) { return ResponseEntity.status(HttpStatus.OK).body(orderService.updateOrder(orderId, request)); } @ResponseStatus(HttpStatus.OK) @RequestMapping(path = "/order/${orderId}", method = RequestMethod.DELETE) public void cancelOrder(@PathParam(value = "orderId") String orderId) { orderService.cancelOrder(orderId); } @RequestMapping(path = "/order/${orderId}", method = RequestMethod.GET) public ResponseEntity<OrderResponse> getOrderDetails(@PathParam(value = "orderId") String orderId) { return ResponseEntity.status(HttpStatus.OK).body(orderService.getOrderDetails(orderId)); } }
Markdown
UTF-8
1,741
2.578125
3
[]
no_license
## iOS Music App - Get music of your mood This is a iOS Music App written in Swift 2.0. It returns a list of songs depending on user's mood. This app is built with MVVM architectural pattern. ## Screenshots ![alt tag](https://github.com/akzuki/FSecure_Songs/blob/master/Screenshots/screenshot.gif) ## Descriptions - Every row shows a background image, a song name and artist name - Clicking on a song will show that song's detail including song image, song name, artist name and song lyrics - Supports both portrait and landscape mode ## How to build 1) Clone the repository ```bash $ git clone https://github.com/akzuki/FSecure_Songs.git ``` 2) Open the workspace in Xcode ```bash $ open "FSecure_Songs.xcworkspace" ``` 3) Compile and run the app in your devices ## Code style This project is following the [GitHub Swift Styleguide](https://github.com/github/swift-style-guide) ## Project Structure ``` FSecure_Songs ├──Core ├──Protocols ├──Network ├──Screens │ ├──Intro │ │ ├──Helper │ │ ├──ViewModel │ │ ├──ViewController │ ├──Main │ │ ├──View │ │ ├──Model │ │ ├──ViewModel │ │ ├──ViewController │ ├──Detail │ │ ├──ViewModel │ │ ├──ViewController ├──Storyboard │ ├──Main.storyboard ``` ## Libraries used - [TTGEmojiRate](https://github.com/zekunyan/TTGEmojiRate) - [AlamofireObjectMapper](https://github.com/tristanhimmelman/AlamofireObjectMapper) - [SDWebImage](https://github.com/rs/SDWebImage) - [EZLoadingActivity](https://github.com/goktugyil/EZLoadingActivity) ## Backend The backend is using NodeJS and PostgresqlDB.
Java
UTF-8
1,322
2.125
2
[]
no_license
package com.example.dimitare.ridecelldemo.utils; import android.annotation.SuppressLint; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.example.dimitare.ridecelldemo.ViewModelHolder; import static android.support.v4.util.Preconditions.checkNotNull; public class ActivityUtils { @SuppressLint("RestrictedApi") public static void addFragmentToActivity (@NonNull FragmentManager fragmentManager, @NonNull ViewModelHolder fragment, String frameId) { checkNotNull(fragmentManager); checkNotNull(fragment); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(fragment, frameId); transaction.commit(); } @SuppressLint("RestrictedApi") public static void addFragmentToActivity (@NonNull FragmentManager fragmentManager, @NonNull Fragment fragment, int frameId) { checkNotNull(fragmentManager); checkNotNull(fragment); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(frameId, fragment); transaction.commit(); } }
Markdown
UTF-8
1,938
3.3125
3
[]
no_license
# 幂等性是什么意思 [参考文章](https://www.cnblogs.com/javalyy/p/8882144.html) >HTTP/1.1中对幂等性的定义是:一次和多次请求某一个资源对于资源本身应该具有同样的结果(网络超时等问题除外)。也就是说,其任意多次执行对资源本身所产生的影响均与一次执行的影响相同。 简单来说,就是每次调用服务,同一方法不管重复操作同一资源多少次,产生的结果应该是相同的,比如删除一条记录,同一用户不管重复请求多少次,服务端应该都只进行过一次删除操作 ## 常见场景 支付、分布式等场景,比如对一份订单的支付操作,用户短时间重复发起几次支付订单的操作,服务端支付的结果都是一样的,只会进行一次支付。分布式环境下,有可能出现服务端执行成功,但是返回结果时出现意外,导致客户端以为服务端操作失败而发起的重复请求。 ## SQL里的幂等性 以SQL为例,有下面三种场景,只有第三种场景需要开发人员使用其他策略保证幂等性: ``` SELECT col1 FROM tab1 WHER col2=2无论执行多少次都不会改变状态,是天然的幂等。 UPDATE tab1 SET col1=1 WHERE col2=2无论执行成功多少次状态都是一致的,因此也是幂等操作。 UPDATE tab1 SET col1=col1+1 WHERE col2=2每次执行的结果都会发生变化,这种不是幂等的。 ``` ## 常见幂等和防重策略 保证幂等性:需要定义唯一操作号这样的变量来记录当前的操作,然后每一次请求前都需要检查这个操作号id来确保操作只进行了一次 幂等性防重:为了保持幂等性,就需要将并行请求转变为串行方式来处理,通常就是加锁来实现,防止第一次操作还未写入操作号id时就被其它请求抢过执行权,导致其它请求误以为操作id未空而进行重复的操作
Java
UTF-8
192
1.664063
2
[]
no_license
package javaPropertiesFile; public class Run { public static void main(String[] args) { String data = JProperties.getProData("password"); System.out.println(data); } }
Java
UTF-8
895
2.515625
3
[]
no_license
package ec.edu.epn.Project; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class NeuronalRedTest { private NeuronalRed neuronalRed; @Before public void SetUpNeuronalRed() { System.out.println("Set up Red Neuronal"); neuronalRed = new NeuronalRed(); } @Test public void Trained_model_when_system_on_then_ok (){ assertEquals(1, neuronalRed.EntrenarModelo()); } @Test public void Tested_model_when_system_on_then_ok (){ assertEquals(1, neuronalRed.TestearModelo(1)); } @Test public void Created_model_when_system_on_then_ok (){ assertEquals(9, neuronalRed.crearKernel()); } @Test public void Detected_gesture_when_system_on_then_ok (){ assertEquals("G", neuronalRed.determinarGesto(6.25,1)); } }
Java
UTF-8
1,573
3.34375
3
[]
no_license
package com.javarush.test.level18.lesson10.home04; /* Объединение файлов Считать с консоли 2 имени файла В начало первого файла записать содержимое второго файла так, чтобы получилось объединение файлов Закрыть потоки. Не использовать try-with-resources */ /* c:\11.txt c:\2.txt c:\3.txt */ import java.io.*; public class Solution { public static void main(String[] args) throws IOException { // считывание названия файлов BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String fileNameOne = br.readLine(); String fileNameTwo = br.readLine(); br.close(); // потоки для чтения и считывание в буфер FileInputStream fileOne = new FileInputStream(fileNameOne); FileInputStream fileTwo = new FileInputStream(fileNameTwo); int sizeOne = fileOne.available(); int sizeTwo = fileTwo.available(); byte[] buffer1 = new byte[sizeOne]; byte[] buffer2 = new byte[sizeTwo]; fileOne.read(buffer1); fileTwo.read(buffer2); fileOne.close(); fileTwo.close(); // открываем первый файл для записи FileOutputStream fileOutputOne = new FileOutputStream(fileNameOne); fileOutputOne.write(buffer2); fileOutputOne.write(buffer1); fileOutputOne.close(); } }
Java
UTF-8
15,294
1.835938
2
[]
no_license
package com.yongyida.robot.hardware.test.item.led; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import com.yongyida.robot.communicate.app.common.response.BaseResponseControl; import com.yongyida.robot.communicate.app.common.send.SendClient; import com.yongyida.robot.communicate.app.common.send.SendResponseListener; import com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl; import com.yongyida.robot.communicate.app.utils.LogHelper; import com.yongyida.robot.hardware.test.R; import com.yongyida.robot.hardware.test.data.ModelInfo; import com.yongyida.robot.hardware.test.item.TestBaseActivity; import com.yongyida.robot.hardware.test.item.led.dialog.MoreColorDialog; import com.yongyida.robot.hardware.test.view.HorizontalListView; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Effect.BREATH; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Effect.BREATH_FAST; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Effect.BREATH_LOW; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Effect.BREATH_MIDDLE; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Effect.HORSE_RACE; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Effect.LED_OFF; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Effect.LED_ON; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Position.ARM; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Position.CHEST; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Position.EAR; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Position.LEFT_ARM; import static com.yongyida.robot.communicate.app.hardware.led.send.data.LedSendControl.Position.RIGHT_ARM; /** * Created by HuangXiangXiang on 2018/3/2. */ public class TestLedActivity extends TestBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, CompoundButton.OnCheckedChangeListener, AdapterView.OnItemLongClickListener { private static final String TAG = TestLedActivity.class.getSimpleName() ; private static LedSendControl.Position[] POSITION_VALUE ; private static String [] POSITION_NAME ; static{ String model = ModelInfo.getInstance().getModel(); if(model.contains("YQ110")){ POSITION_VALUE = new LedSendControl.Position[]{ CHEST} ; POSITION_NAME = new String[] { "胸部"} ; }else if(model.contains("Y138")) { POSITION_VALUE = new LedSendControl.Position[]{ CHEST, EAR, LEFT_ARM, RIGHT_ARM, ARM} ; POSITION_NAME = new String[] { "胸部","耳朵","左臂","右臂","双臂"} ; }else if(model.contains("Y165")) { POSITION_VALUE = new LedSendControl.Position[]{ LedSendControl.Position.EYE} ; POSITION_NAME = new String[] { "眼睛"} ; }else{ POSITION_VALUE = new LedSendControl.Position[]{LedSendControl.Position.LEFT_EAR, LedSendControl.Position.RIGHT_EAR, CHEST} ; POSITION_NAME = new String[]{"左耳朵","右耳朵", "胸部"} ; } } private static LedSendControl.Effect[] EFFECT_VALUE ; private static String [] EFFECT_NAME ; static{ String model = ModelInfo.getInstance().getModel(); if(model.contains("Y165")){ EFFECT_VALUE = new LedSendControl.Effect[]{LED_ON, LED_OFF} ; EFFECT_NAME = new String[]{"常亮","常灭"} ; }else if(model.contains("Y138")) { EFFECT_VALUE = new LedSendControl.Effect[]{LED_ON, LED_OFF, BREATH_LOW, BREATH_MIDDLE, BREATH_FAST, BREATH} ; EFFECT_NAME = new String[]{"常亮","常灭","呼吸灯(慢)","呼吸灯(中)", "呼吸灯(快)","呼吸[2000秒]"} ; }else { EFFECT_VALUE = new LedSendControl.Effect[]{LED_ON, LED_OFF, BREATH_LOW, BREATH_MIDDLE, BREATH_FAST, HORSE_RACE} ; EFFECT_NAME = new String[]{"常亮","常灭","呼吸灯(慢)","呼吸灯(中)", "呼吸灯(快)","跑马灯"} ; } } private HorizontalListView mLedPositionGvw; /** * 开关灯 */ private Switch mPowerSih; /** * 暗 */ private Button mBrightnessDarkBtn; /** * 亮 */ private Button mBrightnessBrightBtn; private LinearLayout mGeneralBrightnessLlt; /** * 白 */ private Button mColorWhiteBtn; /** * 红 */ private Button mColorRedBtn; /** * 绿 */ private Button mColorGreenBtn; /** * 蓝 */ private Button mColorBlueBtn; private Button mColorMoreBtn; private LinearLayout mGeneralColorLlt; private GridView mEffectGvw; private int width = 100 ; @Override protected View initContentView() { View view = LayoutInflater.from(this).inflate(R.layout.activity_test_led , null) ; mLedPositionGvw = (HorizontalListView) view.findViewById(R.id.led_position_gvw); mLedPositionGvw.setOnItemClickListener(this); mPowerSih = (Switch) view.findViewById(R.id.power_sih); mPowerSih.setOnCheckedChangeListener(this); mBrightnessDarkBtn = (Button) view.findViewById(R.id.brightness_dark_btn); mBrightnessDarkBtn.setOnClickListener(this); mBrightnessBrightBtn = (Button) view.findViewById(R.id.brightness_bright_btn); mBrightnessBrightBtn.setOnClickListener(this); mGeneralBrightnessLlt = (LinearLayout) view.findViewById(R.id.general_brightness_llt); mColorWhiteBtn = (Button) view.findViewById(R.id.color_white_btn); mColorWhiteBtn.setOnClickListener(this); mColorRedBtn = (Button) view.findViewById(R.id.color_red_btn); mColorRedBtn.setOnClickListener(this); mColorGreenBtn = (Button) view.findViewById(R.id.color_green_btn); mColorGreenBtn.setOnClickListener(this); mColorBlueBtn = (Button) view.findViewById(R.id.color_blue_btn); mColorBlueBtn.setOnClickListener(this); mColorMoreBtn = (Button) view.findViewById(R.id.color_more_btn); mColorMoreBtn.setOnClickListener(this); mGeneralColorLlt = (LinearLayout) view.findViewById(R.id.general_color_llt); mEffectGvw = (GridView) view.findViewById(R.id.effect_gvw); mEffectGvw.setOnItemClickListener(this); mEffectGvw.setOnItemLongClickListener(this); if(ModelInfo.getInstance().getModel().contains("Y165")){ mGeneralColorLlt.setVisibility(View.GONE); } ledControl.setEffectValue(breathTime); return view; } @Override protected String getTips() { return null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); float scale = getResources().getDisplayMetrics().scaledDensity ; width *= scale ; ledControl.setPosition(POSITION_VALUE[0]); ledControl.setEffect(EFFECT_VALUE[0]); mLedPositionGvw.setAdapter(mLedPositionAdapter); mEffectGvw.setAdapter(mEffectAdapter); ledControl.setPosition(POSITION_VALUE[0]); ledControl.setEffect(LedSendControl.Effect.NORMAL); ledControl.setColor(0xFF0000); } @Override protected void onDestroy() { super.onDestroy(); } // private void startTest(){ // // TestData testData = new TestData() ; // testData.setTest(true); // TouchSend touchSend = new TouchSend() ; // touchSend.setTestData(testData); // // SendClient.getInstance(this).sendInMainThread(TestData, null); // // } // // private void stopTest(){ // // TestData testData = new TestData() ; // testData.setTest(false); // TouchSend touchSend = new TouchSend() ; // touchSend.setTestData(testData); // // TouchClient.getInstance(this).sendInMainThread(touchSend, null); // } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.brightness_dark_btn) { } else if (i == R.id.brightness_bright_btn) { } else if (i == R.id.color_white_btn) { } else if (i == R.id.color_red_btn) { ledControl.setColor(0xFF0000); sendLedControl() ; } else if (i == R.id.color_green_btn) { ledControl.setColor(0x00FF00); sendLedControl() ; } else if (i == R.id.color_blue_btn) { ledControl.setColor(0x0000FF); sendLedControl() ; } else if (i == R.id.color_more_btn) { new MoreColorDialog(this, ledControl).show(); } else { } } private LedSendControl ledControl = new LedSendControl(); public void sendLedControl(){ SendClient.getInstance(this).send(null, ledControl,responseListener); } private SendResponseListener responseListener = new SendResponseListener(){ @Override public void onSuccess(BaseResponseControl baseResponseControl) { LogHelper.i(TAG, LogHelper.__TAG__() + "baseResponseControl : " + baseResponseControl); } @Override public void onFail(int result, String message) { LogHelper.i(TAG, LogHelper.__TAG__() + "result : " + result + ", message : " + message ); } } ; private int breathTime = 2000 ; @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { if(parent == mLedPositionGvw){ ledPositionCheckPosition = position ; mLedPositionAdapter.notifyDataSetChanged(); ledControl.setPosition(POSITION_VALUE[position]); sendLedControl() ; }else if(parent == mEffectGvw){ effectCheckPosition = position ; mEffectAdapter.notifyDataSetChanged(); ledControl.setEffect(EFFECT_VALUE[position]); sendLedControl() ; } } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { if(parent == mEffectGvw){ LedSendControl.Effect effect = EFFECT_VALUE[position] ; if(effect == BREATH) { final EditText editText = new EditText(this); editText.setText(String.valueOf(breathTime)); DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String text = editText.getText().toString(); try { breathTime = Integer.parseInt(text); } catch (Exception e) { } EFFECT_NAME[position] = "呼吸[" + breathTime + "秒]"; mEffectAdapter.notifyDataSetChanged(); ledControl.setEffect(EFFECT_VALUE[position]); ledControl.setEffectValue(breathTime); sendLedControl(); } }; AlertDialog.Builder builder = new AlertDialog.Builder(this) .setTitle("设置呼吸时间轮回") .setView(editText) .setNegativeButton("取消", null) .setPositiveButton("确定", onClickListener); builder.create().show(); } } return true; } private int ledPositionCheckPosition ; private BaseAdapter mLedPositionAdapter = new BaseAdapter() { @Override public int getCount() { return POSITION_NAME.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView textView ; if(convertView == null){ convertView = mLayoutInflater.inflate(R.layout.item_text, null) ; textView = convertView.findViewById(R.id.text_tvw) ; LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams(); layoutParams.width = width ; convertView.setTag(textView); }else{ textView = (TextView) convertView.getTag(); } textView.setBackgroundResource((ledPositionCheckPosition == position) ? R.drawable.item_select_bg :R.drawable.item_bg); textView.setText(POSITION_NAME[position]); // textView.requestLayout(); return convertView; } }; private int effectCheckPosition ; private BaseAdapter mEffectAdapter = new BaseAdapter() { @Override public int getCount() { return EFFECT_NAME.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView textView ; if(convertView == null){ convertView = mLayoutInflater.inflate(R.layout.item_text, null) ; textView = convertView.findViewById(R.id.text_tvw) ; convertView.setTag(textView); }else{ textView = (TextView) convertView.getTag(); } textView.setBackgroundResource((effectCheckPosition == position) ? R.drawable.item_select_bg :R.drawable.item_bg); textView.setText(EFFECT_NAME[position]); return convertView; } }; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // LedSendControl ledStatue = new LedSendControl(); // ledStatue.setPosition(POSITION_VALUE[ledPositionCheckPosition]); // // LedSendControl.Power power = isChecked ? LedSendControl.Power.POWER_ON : LedSendControl.Power.POWER_OFF ; // // ledStatue.setPower(power); // // LedClient.getInstance(this).sendLedStatueInMainThread(ledStatue); } /**隐藏功能*/ @Override protected void onTouchTitleLeft() { super.onTouchTitleLeft(); LedLibraryActivity.startActivity(this); } }
Go
UTF-8
1,242
2.953125
3
[]
no_license
package ingestion import ( "io" "net/http" "testing" "github.com/stretchr/testify/assert" ) func Test_jobService_Retrieve(t *testing.T) { setup() defer teardown() test := struct { wantJobs []Job wantErr bool }{ wantJobs: []Job{ Job{ ID: 146859, Name: "Auror", Status: "open", Public: true, }, Job{ ID: 150050, Name: "Professor", Status: "open", Public: true, }, Job{ ID: 147886, Name: "Caretaker", Status: "open", Public: false, }, }, } mux.HandleFunc("/v1/partner/jobs", func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { t.Fatalf("unexpected method: %s", r.Method) } w.WriteHeader(200) io.WriteString(w, ` [ { "id": 146859, "name": "Auror", "status": "open", "public": true }, { "id": 150050, "name": "Professor", "status": "open", "public": true }, { "id": 147886, "name": "Caretaker", "status": "open", "public": false } ] `) }) gotJobs, err := client.Jobs.Retrieve() switch test.wantErr { case true: assert.Error(t, err) case false: assert.NoError(t, err) } assert.Equal(t, test.wantJobs, gotJobs) }
Java
UTF-8
423
2.796875
3
[]
no_license
package rlnitsua.array; import java.util.ArrayList; import java.util.List; public class DestinationCity { public String destCity(List<List<String>> paths) { List<String> list = new ArrayList<>(); for (List<String> path : paths) { list.add(path.get(1)); } for (List<String> path : paths) { list.remove(path.get(0)); } return list.get(0); } }
C#
UTF-8
2,300
3.4375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _06StoreBoxes { class Program { static void Main(string[] args) { List<Box> boxes = new List<Box>(); double totalPrice = 0.00; while (true) { string command = Console.ReadLine(); string[] cmdArg = command.Split(); if (command == "end") { break; } string serialNumber = cmdArg[0]; string itemName = cmdArg[1]; int itemQuantity = int.Parse(cmdArg[2]); double itemPrice = double.Parse(cmdArg[3]); totalPrice = itemPrice * itemQuantity; Box box = new Box(serialNumber, itemName, itemQuantity, itemPrice, totalPrice); boxes.Add(box); command = Console.ReadLine(); } List<Box>sortedBox = boxes.OrderByDescending(boxes => boxes.TotalPrice).ToList(); foreach (Box box in sortedBox) { Console.WriteLine($"{box.SerialNumber}"); Console.WriteLine($"-- {box.Item} - ${box.PriceBox:F2}: {box.Quantity}"); Console.WriteLine($"-- ${box.TotalPrice:F2}"); } } } } class Item { } class Box { public Box(string serialNumber, string item, int quantity, double priceBox, double totalPrice) { SerialNumber = serialNumber; Item = new Item(); Quantity = quantity; PriceBox = priceBox; TotalPrice = totalPrice; } public string SerialNumber { get; set; } public Item Item { get; set; } public int Quantity { get; set; } public double PriceBox { get; set; } public double TotalPrice { get; set; } public override string ToString() { return $"{SerialNumber} {Item} {Quantity} {PriceBox} {TotalPrice}"; } } //{ boxSerialNumber}-- { boxItemName} – ${ boxItemPrice}: { boxItemQuantity}-- ${ boxPrice}
Markdown
UTF-8
1,670
3.015625
3
[]
no_license
# zkp_gui ![zkp](http://s8.hostingkartinok.com/uploads/images/2017/01/ffbdc53df65fa3a5a12839764e9358af.png "zkp") ## Приклад виконання протоколу ZK EC: Нехай `Е751(–1, 188)`; `G` = (1, 375); `Q` = (2, 373); `р` = 751, що відповідає кривій `у^2 = х^3 – х + 188`. Припустимо, що користувач А вибирає секретні ключі `k1` = 327, `k2` = 715 та обчислює відкритий ключ `Yа` = 327(1, 375) + 715(2, 373) = (139, 413). Абонент В вибирає секретне число kb = 496 та обчислює відкритий ключ Yb: `Yb` = 496[(1, 375) + (2, 373)] = (352, 686). ### Перший цикл протоколу. 1. Абонент А вибирає випадкові числа `r1 = 619`, `r2 = 157` та обчислює `γ`: `А → В`:`Yа` = (139, 413), `γ` = 619(1, 375) + 157(2, 373) = (605, 454). 2. `А ← В`: `Yb` = (352, 686), `х` = 191. 3. `А → В`: `у1` = (619 + 191 · 327) (352, 686 = (637, 301); `у2` = (157 + 191 · 715) (352, 686)  (653, 422); `у3` = (619 + 191 · 327) (2, 373) + (157 + 191 · 715) (1, 375)  = (43, 322). Абонент В виконує перевірку 107[(637, 301) + (653, 422)] – (43, 322) – 191(139, 413) =  γ – перевірка виконана. ![zkp_gui](http://s8.hostingkartinok.com/uploads/images/2017/01/42aaec2e01f1559748049320c806b29b.jpg "zkp_gui")
C++
UTF-8
20,139
3.21875
3
[]
no_license
/* Assignment: Project #4 Author: Matthew Bierman Course: CS 2336.004 (Computer Science II) Instructor: Mr. Jason Smith Date Due: November 16, 2016 at 11:59pm //TRIG FUNCTIONS */ #include <fstream> #include <sstream> #include <string> #include <stdlib.h> #include <cmath> #include <iomanip> #include "Node.h" #include "BinarySearchTree.h" using namespace std; // Converts a double to a string // Parameters: double // Return: string string dtos(double d) { stringstream ss; ss << d; return ss.str(); } // Solve indefinite integral // Parameters: string // Return: string string solveIndefinite(string str) { BinarySearchTree bst; string trigList = ""; while (str != "") { string temp = str.substr(0, str.find(' ')); if (temp.find('s') < temp.length()) // if part contains sine, { // cosine, or secant int coeff = 0; int insideCoeff = 0; if (temp[temp.find('s') + 1] == 'i') // if part is sine { if (temp.substr(0, temp.find('s')) == "") // if no coefficient coeff = 1; else if (temp.substr(0, temp.find('s')) == "-") // if coefficient of -1 coeff = -1; else // if coefficient something other than 1 or -1 coeff = atoi(temp.substr(0, temp.find('s')).c_str()); insideCoeff = atoi(temp.substr(temp.find('n') + 1, temp.find('x') - (temp.find('n') + 1)).c_str()); // gets inside coefficient if (insideCoeff == 0) // if no inside coefficient insideCoeff++; trigList += dtos(coeff) + "," + dtos(insideCoeff) + ",sin;"; // trig list is in the format <coeff>,<insideCoeff>,<trig>; } else if (temp[temp.find('s') + 1] == 'e') // if part is secant { if (temp.substr(0, temp.find('s')) == "") // if no coefficient coeff = 1; else if (temp.substr(0, temp.find('s')) == "-") // if coefficient of -1 coeff = -1; else // if coefficient something other than 1 or -1 coeff = atoi(temp.substr(0, temp.find('s')).c_str()); insideCoeff = atoi(temp.substr(temp.find('2') + 1, temp.find('x') - (temp.find('2') + 1)).c_str()); // gets inside coefficient if (insideCoeff == 0) // if no inside coefficient insideCoeff++; trigList += dtos(coeff) + "," + dtos(insideCoeff) + ",sec;"; // trig list is in the format <coeff>,<insideCoeff>,<trig>; } else // if part is cosine { if (temp.substr(0, temp.find('c')) == "") // if no coefficient coeff = 1; else if (temp.substr(0, temp.find('c')) == "-") // if coefficient of -1 coeff = -1; else // if coefficient something other than 1 or -1 coeff = atoi(temp.substr(0, temp.find('c')).c_str()); insideCoeff = atoi(temp.substr(temp.find('s') + 1, temp.find('x') - (temp.find('s') + 1)).c_str()); // gets inside coefficient if (insideCoeff == 0) // if no inside coefficient insideCoeff++; trigList += dtos(coeff) + "," + dtos(insideCoeff) + ",cos;"; // trig list is in the format <coeff>,<insideCoeff>,<trig>; } } else if (temp != "0") { int coeff = 0; int exp = 0; if (temp.find('x') > str.length()) // if no variable x exp = 0; else if (temp.find('^') > str.length()) // if no exponent exp = 1; else // if exponent something other than 1 or -1 exp = atoi(temp.substr(temp.find('^') + 1).c_str()); if (temp[0] == 'x') // if no coefficient coeff = 1; else // if coefficient something other than 1 or -1 coeff = atoi(temp.substr(0, temp.find('x')).c_str()); bst.insertNode(coeff, exp, bst.getRoot()); // add to binary search tree } if (str.find(' ') > str.length()) // if no other parts to the equation str = ""; // after current part, end loop else { str = str.substr(str.find(' ') + 1); // remove current part from equation if (str.substr(0, 2) == "+ ") // if next part of equation is positive, str = str.substr(2); // remove plus sign else if (str.substr(0, 3) == "- x") // if next part of equation is negative and str = "-1" + str.substr(2); // has no coefficient, add -1 to it else // if next part of equation is negative and str = "-" + str.substr(2); // has a coefficient, remove space between } // - and coefficient } string s = bst.inorderTraversal(bst.getRoot()); // get equation in order of exponent from least to greatest s = s.substr(0, s.length() - 3) + " + C"; // add constant for (unsigned int x = 0; x < s.length(); x++) { if (x < s.length() - 1 && s[x] == '1' && s[x + 1] == 'x' // converts all instances of 1x to x && s[x - 1] == ' ') s = s.substr(0, x) + s.substr(x + 1); if (s.substr(x, 2) == "/-") // moves negative to outside the coefficient if it is { // part of the denominator s = s.substr(0, x).substr(0, s.substr(0, x).find_last_of('(')) + "-(" + s.substr(s.substr(0, x).find_last_of('(') + 1, x - s.substr(0, x).find_last_of('(') - 1) + "/" + s.substr(x + 2); x = 0; } if (s.substr(x, 3) == "^1 ") // converts x^1 to x s = s.substr(0, x) + s.substr(x + 2); if (s.substr(x, 3) == "+ -") // converts <part> + -<part> to <part> - <part> s = s.substr(0, x) + "- " + s.substr(x + 3); if (s.substr(x, 4) == "+ (-") // moves negative to outside the coefficient if it is s = s.substr(0, x) + "- (" + s.substr(x + 4); // part of the numerator } if (s.substr(0, 3) == " + ") // removes a + if it is at the beginning of the entire s = s.substr(3); // equation for (unsigned int x = 0; x < s.length(); x++) { if (s.substr(x, 3) == "+ -") // converts <part> + -<part> to <part> - <part> s = s.substr(0, x) + "- " + s.substr(x + 3); if (s.substr(x, 2) == "(-") // moves negative to outside the coefficient if it is s = s.substr(0, x) + "-(" + s.substr(x + 2); // part of the numerator } return bst.appendTrig(s, trigList); // add anti-derivatives of trig functions to equation } // Solve definite integral // Parameters: string, int, int // Return: string double solveDefinite(string str, int a, int b) { double totalA = 0; // result of plugging a into the integral double totalB = 0; // result of plugging b into the integral str = str.substr(0, str.length() - 4); // removes + C from both equations because it will cancel if (a == b) // if integral has no range, integral equals 0 return 0; else { while (str.length() > 0 || str != "") { string temp; if (str.find(' ') < str.length()) // gets the first part of the equation temp = str.substr(0, str.find(' ')); else temp = str; double coeff = 0; if (temp[0] == 'x') // if part has a coefficient of 1 coeff++; else if (temp[0] == '-' && temp[1] == 'x') // if part has a coefficient of -1 coeff--; else { if (temp[0] == '(') // if part has a positive fraction coefficient temp = temp.substr(1, temp.find(')') - 1) + temp.substr(temp.find('x')); else if (temp[1] == '(') // if part has a negative fraction coefficient temp = "-" + temp.substr(2, temp.find(')') - 2) + temp.substr(temp.find('x')); else // converts coefficient into a fraction temp = temp.substr(0, temp.find('x')) + "/1" + temp.substr(temp.find('x')); coeff = atof(temp.substr(0, temp.find('/')).c_str()) // coefficient = numerator / denominator / atof(temp.substr(temp.find('/') + 1, temp.find('x') - temp.find('/')).c_str()); } int exp; if (temp.find('^') > temp.length()) // if no exponent, exponent is 1 exp = 1; else if (temp.find('x') > temp.length()) // if no variable x, exponent is 0 exp = 0; else exp = atoi(temp.substr(temp.find('^') + 1, // if exponent exists temp.find(' ') - (temp.find('^') + 1)).c_str()); totalA += coeff * pow(a, exp); // plugs in a for x and adds the result to totalA totalB += coeff * pow(b, exp); // plugs in a for x and adds the result to totalB if (str.find(' ') > str.length()) // if no other parts to the equation str = ""; // after current part, end loop else { str = str.substr(str.find(' ') + 1); // remove current part from equation if (str[0] == '+') // if next part of equation is positive, str = str.substr(2); // remove plus sign else // if next part of equation is negative, str = "-" + str.substr(2); // remove space between - and rest of equation } } return totalB - totalA; // definite integral = F(b) - F(a) } } int main() { ifstream inFile("integrals.txt"); // opens integrals.txt for input if (inFile) // if integrals.txt exists { ofstream outFile("answers.txt"); // opens answers.txt for output outFile << fixed << setprecision(3); // sets all results to 3 decimals while (!inFile.eof()) // for each line in the input until { // it reaches the end of the file string eq; getline(inFile, eq); // gets the entire line from the file for (unsigned int x = 0; x < eq.length(); x++) // removes any spaces from the equation { // (for continuity) if (eq[x] == ' ' && x > eq.find(' ') && x < (eq.length() - 3)) eq = eq.substr(0, x) + eq.substr(x + 1); } for (unsigned int x = 0; x < eq.length(); x++) // adds spaces between all parts of the { // equation (for continuity) if (x > eq.find(' ') && x < (eq.length() - 3)) { if (eq[x] == '+' && eq[x - 1] != ' ' && eq[x + 1] != ' ') // adds spaces if + sign is between parts eq = eq.substr(0, x) + " + " + eq.substr(x + 1); else if (eq.substr(x, 3) == "c^2") // Skips over - if currently on a secant x += 3; // function else if (eq[x] == '-' && eq[x - 1] != '^' && eq[x - 1] != ' ' // adds spaces if - between parts and not && eq[x + 1] != ' ' && (x - eq.find('s')) > 3) // part of an exponent or trig function eq = eq.substr(0, x) + " - " + eq.substr(x + 1); } } if (eq.substr(0, 2) == "| ") // if equation is an indefinite integral outFile << solveIndefinite(eq.substr(2).substr(0, eq.length() - 5)) // remove | and dx from equation << endl; else // if equation is a definite integral { // get values for a & b, then remove string indef = solveIndefinite(eq.substr(eq.find(' ') + 1, // a|b and dx from equation eq.find_last_of(' ') - (eq.find(' ') + 1))); outFile << indef.substr(0, indef.length() - 4) << ", " // outputs the anti-derivative (without a << eq.substr(0, eq.find(' ')) << " = " << solveDefinite(indef, // constant), then the range, then the atoi(eq.substr(0, eq.find('|')).c_str()), // value of the definite integral atoi(eq.substr(eq.find('|') + 1).substr(0, eq.find(' ')).c_str())) << endl; } } outFile.close(); } inFile.close(); return 0; }
Python
UTF-8
2,793
2.640625
3
[]
no_license
# -*- coding:utf-8 -*- import jieba.analyse from SubmarketMerge.tools.utils import load, dump, clear_brand, read from SubmarketMerge.component.readData import * class CutMethod(object): """Cut Method""" def __init__(self): """Init""" def cut(self): """Cut Function""" raise NotImplementedError class CutWithBrandMethod(CutMethod): """Cut Top Trending Searches And Title With Brand""" def __init__(self): self.threshold = { "title": Parameters.cutTitleWordsNum, "hot search": Parameters.cutHotSearchWordsNum } def cut(self): df = read("factItem")() title = "".join(list(df['title'])) cut_word = jieba.analyse.textrank(title, topK=self.threshold["title"]) title_words = set() for i, word in enumerate(list(cut_word)): title_words.add(word) dump(title_words, "titleHotWords") df = read("hotWords")() title = "".join(list(df['hotwords'])) cut_word = jieba.analyse.textrank(title, topK=self.threshold["hot search"]) search_words = set() for i, word in enumerate(list(cut_word)): search_words.add(word) dump(search_words, "searchHotWords") class CutWithoutBrandMethod(CutMethod): def __init__(self): self.threshold = { "title": Parameters.cutTitleWordsNum, "hot search": Parameters.cutHotSearchWordsNum } """Cut Top Trending Searches And Title Without Brand""" def cut(self): df = read("factItem")() for k, v in df.iterrows(): df.at[k, "title"] = clear_brand(v["title"], v["brand"]) title = "".join(list(df['title'])) cut_word = jieba.analyse.textrank(title, topK=self.threshold["title"]) title_words = set() for i, word in enumerate(list(cut_word)): title_words.add(word) dump(title_words, "titleHotWords") df = read("hotWords")() title = "".join(list(df['hotwords'])) cut_word = jieba.analyse.textrank(title, topK=self.threshold["hot search"]) search_words = set() for i, word in enumerate(list(cut_word)): search_words.add(word) dump(search_words, "searchHotWords") class UseLocalCutMethod(CutMethod): """Use Local Files As The Result Of Cut Method""" def __init__(self, method): self.threshold = { "title": Parameters.cutTitleWordsNum, "hot search": Parameters.cutHotSearchWordsNum } self.method = method def cut(self): try: load("titleHotWords") load("searchHotWords") except FileNotFoundError: self.method().cut() except Exception as e: raise e
Shell
UTF-8
942
2.984375
3
[ "MIT" ]
permissive
remote_url=$(git remote get-url origin) repo_name=$(basename -s .git $remote_url) repo_path=$(dirname $remote_url) author_handle=${repo_path##*:} author_handle=${author_handle##*/} executable_name=$(echo $repo_name | perl -pe 's/(^|-|_| |%20)(\w)/uc($2)/ge' ) author_name=$(git config user.name) author_email=$(git config user.email) for path in $(find . -type d -path "*EXECUTABLE-NAME*") do mv $path ${path//EXECUTABLE-NAME/$executable_name} done for path in $(find . -type f ! -path "./.*/*" ! -name "./generate.sh" ! -name ".DS_Store") do sed -i "" -e "s/AUTHOR-HANDLE/$author_handle/g" $path sed -i "" -e "s/AUTHOR-NAME/$author_name/g" $path sed -i "" -e "s/AUTHOR-EMAIL/$author_email/g" $path sed -i "" -e "s/EXECUTABLE-NAME/$executable_name/g" $path if [[ $path =~ "EXECUTABLE-NAME" ]] then mv $path ${path//EXECUTABLE-NAME/$executable_name} fi done swift test swift run open Package.swift rm -rf ./generate.sh
Python
UTF-8
701
3.828125
4
[ "MIT" ]
permissive
def pot(x, n): if (n == 0): return(1) if (n == 1): return(x) if (n % 2 == 0): half = pot(x, n / 2) return(half * half) else: half = pot(x, (n - 1) / 2) return(half * half * x) x, n = map(int, input().split()) print(pot(x, n)) def compare(x, n): start = time.time() print(x**n) default = time.time() - start print("Python default: ", default, "sec") # start = time.time() print(pot(x, n)) fast = time.time() - start print("Fast Exponentiation: ", fast, "sec") print("\nFast Exponentiation is: ", default - fast, "sec faster (", ((default - fast) / default) * 100, "%)")
Python
UTF-8
548
2.859375
3
[]
no_license
#!/usr/bin/env python # ========= Import required modules ===================== # for using system commands import sys # for using os commands like list directeries etc import os # for mathematical functions specially matriices import numpy as np # for general maths from math import * ans = 0 for i in range(100000,1000000): num = i count = 1 while num != 1: if num %2 == 0: num = num/2 else: num = 3*num + 1 count += 1 if count > ans: print i,count ans = count
C
UTF-8
2,989
3.046875
3
[]
no_license
#include <stm32f4xx.h> /* * @tasks Set SYSCLK 1/2 of maximal * Flash LEDs from 1 to 3 in endless loop * On button press change SYSCLK source from HSE to HSI and back */ #define SWITCH_DELAY ((uint32_t)2000000) typedef enum blink_mul_e { BLINK_MUL_FAST = 1, BLINK_MUL_LONG = 3, } blink_mul_t; void blink_led(GPIO_TypeDef* port, uint16_t pins, blink_mul_t multiplier); int main(void) { GPIO_InitTypeDef GPIO_InitStructure; /* Enable peripheral clock for LEDs and buttons port */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE); /* Init LEDs */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOA, &GPIO_InitStructure); /* Init buttons */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOE, &GPIO_InitStructure); /* Turn all the leds off */ GPIO_SetBits(GPIOA, GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10); /* Set SYSCLK based on PLL */ RCC_HSEConfig(RCC_HSE_ON); RCC_WaitForHSEStartUp(); RCC_SYSCLKConfig(RCC_SYSCLKSource_HSE); RCC_PLLCmd(DISABLE); RCC_PLLConfig(RCC_PLLSource_HSI, 8, 84, 2, 4); RCC_PLLCmd(ENABLE); RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); int8_t oscillator_selection = 0; while (1) { /* Select PLL source */ if (!GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_1)) { /* Click indicator R->G */ blink_led(GPIOA, GPIO_Pin_8, BLINK_MUL_LONG); blink_led(GPIOA, GPIO_Pin_9, BLINK_MUL_LONG); RCC_SYSCLKConfig(RCC_SYSCLKSource_HSI); RCC_PLLCmd(DISABLE); oscillator_selection = (oscillator_selection + 1) % 2; if (oscillator_selection) { RCC_PLLConfig(RCC_PLLSource_HSE, 8, 168, 2, 4); } else { RCC_PLLConfig(RCC_PLLSource_HSI, 8, 168, 2, 4); } RCC_PLLCmd(ENABLE); RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); } /* Flash LEDs */ blink_led(GPIOA, GPIO_Pin_8, BLINK_MUL_FAST); blink_led(GPIOA, GPIO_Pin_8 | GPIO_Pin_9, BLINK_MUL_FAST); blink_led(GPIOA, GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_10, BLINK_MUL_FAST); } } void blink_led(GPIO_TypeDef* port, uint16_t pins, blink_mul_t multiplier) { uint32_t k = 0; GPIO_ResetBits(port, pins); for (k = 0; k < SWITCH_DELAY * multiplier; ++k) ; GPIO_SetBits(port, pins); }
TypeScript
UTF-8
635
2.71875
3
[]
no_license
import { ActionTypes } from "./types"; import firebase from "firebase"; export interface Item { id: string; title: string; image: string; price: number; rating: number; } interface AddToBasketAction { type: ActionTypes.ADD_TO_BASKET; payload: Item; } interface RemoveFromBasketAction { type: ActionTypes.REMOVE_FROM_BASKET; payload: String; } interface SetUserAction { type: ActionTypes.SET_USER; payload: null | firebase.User; } interface EmptyBasketAction { type: ActionTypes.EMPTY_BASKET; } export type Action = | AddToBasketAction | RemoveFromBasketAction | SetUserAction | EmptyBasketAction;
Java
UTF-8
108
1.6875
2
[]
no_license
package com.ustglobal.atmmachine; public class machine { void slot(ATM a) { a.card(); a.info(); } }
Java
UTF-8
3,665
2.6875
3
[]
no_license
package uk.co.gossfunkel.citadel.net; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import uk.co.gossfunkel.citadel.Game; import uk.co.gossfunkel.citadel.entity.mob.OnlinePlayer; import uk.co.gossfunkel.citadel.net.packets.Packet; import uk.co.gossfunkel.citadel.net.packets.Packet.PacketTypes; import uk.co.gossfunkel.citadel.net.packets.Packet00Login; import uk.co.gossfunkel.citadel.net.packets.Packet01Disconnect; import uk.co.gossfunkel.citadel.net.packets.Packet02Move; import uk.co.gossfunkel.citadel.net.packets.Packet10LoginResponse; public class GameClient implements Runnable { private InetAddress ip; private DatagramSocket socket; private Game game; private boolean running = false; public GameClient(Game game, String ip) { this.game = game; try { socket = new DatagramSocket(); this.ip = InetAddress.getByName(ip); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { //TODO tell the user that they put an unusable address in. // in future, add a checker to ip before this is constructed e.printStackTrace(); } socket.connect(this.ip, 1042); running = true; } @Override public void run() { while (running) { byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, data.length); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); } System.out.println("SERVER> " + new String(packet.getData())); parsePacket(packet.getData(), packet.getAddress(), packet.getPort()); } } public void exit() { running = false; Packet01Disconnect p = new Packet01Disconnect(game.username()); p.writeData(this); } private void parsePacket(byte[] data, InetAddress address, int port) { String message = new String(data).trim(); PacketTypes type; try { type = Packet.lookupPacket(Integer.parseInt(message.substring(0, 2))); } catch (NumberFormatException e) { type = PacketTypes.INVALID; } switch (type) { case LOGIN: Packet00Login packet = new Packet00Login(data); OnlinePlayer player = new OnlinePlayer(packet.x(), packet.y(), game, game.getTimer(), ((Packet00Login)packet).username(), address, port, game.getLevel()); if (player != null) game.getLevel().addEntity(player); break; case LOGINRESPONSE: Packet10LoginResponse packet10 = new Packet10LoginResponse(data, this, address, port); game.addPlayerList(packet10.getPlayers()); game.addSettList(packet10.getSettlements()); break; case DISCONNECT: Packet01Disconnect packet1 = new Packet01Disconnect(data); System.out.println(packet1.username() + " has left."); game.getLevel().removeOnlinePlayer(packet1.username()); break; case MOVE: Packet02Move packet2 = new Packet02Move(data); handleMovement(packet2); break; case INVALID: default: break; } } private void handleMovement(Packet02Move packet) { game.getLevel().movePlayer(packet.username(), packet.x(), packet.y()); } public void sendData(byte[] data) { DatagramPacket packet = new DatagramPacket(data, data.length, ip, 1042); try { socket.send(packet); } catch (IOException e) { e.printStackTrace(); } } public OnlinePlayer makePlayer(int x, int y, String usnm, InetAddress ip, int port) { return new OnlinePlayer(x, y, game, game.getTimer(), usnm, ip, port, game.getLevel()); } }
C#
UTF-8
164
2.53125
3
[]
no_license
namespace AutofacPresentation { public class BadSpeaker : ISpeaker { public string Say() { return @"Bye:\"; } } }
Python
UTF-8
3,227
2.703125
3
[]
no_license
import requests import json from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup as bs from splinter import Browser import pandas as pd import os import time import pymongo def init_browser(): executable_path = {'executable_path' : '/usr/local/bin/chromedriver'} return Browser('chrome', **executable_path, headless=False) def scrape(): browser = init_browser() mars_dict = {} url = 'https://mars.nasa.gov/news/' browser.visit(url) html = browser.html soup = bs(html, 'html.parser') #Finding the latest news title and assigning to a variable content = soup.find("div", class_='content_page') titles = content.find_all("div", class_='content_title') news_title = (titles[0].text.strip()) news_title #Finding the latezt news Paragraph text and assigning to a variable article_text = content.find_all("div", class_='article_teaser_body') news_p = article_text[0].text news_p #visting Nasa website url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars' browser.visit(url) #finding the full image button path and click full_image = browser.find_by_id("full_image") full_image.click() #finding the more info button path and click more_info = browser.links.find_by_partial_text("more info") more_info.click() html = browser.html img_soup = bs(html, 'html.parser') #assigning the url to a variable img_path = img_soup.select_one('figure.lede a img').get("src") img_path featured_img_url = f"https://www.jpl.nasa.gov{img_path}" featured_img_url #Visiting Mars Facts webpage url_facts = 'https://space-facts.com/mars/' browser.visit(url_facts) html = browser.html soup = bs(html, 'html.parser') #reading the table mars_facts_tables = pd.read_html(url_facts) df_facts_table = mars_facts_tables[0] df_facts_table.columns = ["Description", "Mars"] mars_html_table = df_facts_table.to_html(index=False) mars_html_table.replace('\n', '') #Visiting astrogeology webpage url_facts = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars' browser.visit(url_facts) html = browser.html soup = bs(html, 'html.parser') #finding the links large_photos = soup.find_all('div', class_='item') hemi_main_url = 'https://astrogeology.usgs.gov' #appending url string to a dictionary as well as the title hemi_ima_url = [] for i in large_photos: title = i.find('h3').text partial_img_url = i.find('a', class_='itemLink product-item')['href'] browser.visit(hemi_main_url + partial_img_url) partial_img_html = browser.html soup = bs( partial_img_html, 'html.parser') img_url = hemi_main_url + soup.find('img', class_='wide-image')['src'] hemi_ima_url.append({"title" : title, "img_url" : img_url}) hemi_ima_url #creating a dictionary mars_dict={ "news_title_test": news_title, "news_p": news_p, "featured_img_url": featured_img_url, "fact_table": mars_html_table, "hemisphere_images": hemi_ima_url } return mars_dict
C++
UTF-8
2,087
3
3
[ "BSL-1.0" ]
permissive
#ifndef NEOPIXEL_UNO_HPP #define NEOPIXEL_UNO_HPP #include "hwlib.hpp" #include "neopixel.hpp" /// @file /// \brief /// implementations for Adafruit ws2812 for Arduino Uno /// \details /// This class is an implemtation of the abstract neopixel class /// /// This implementation can be used for the Arduino Uno /// /// The adafruit ws2812 led ring is a LED ring that is controlled by one data pin. /// /// The chip runs on 5V, and I suggest you use an external power supply, because each LED consumes around 60mA when its on full brightness. /// /// An Arduino's Max current on Vcc and GND is 200 mA, so you can link a total off 5 LEDs if you plan to use them on full white brightness. /// /// This class takes a maximum of 100 chained leds. This can be upgraided by making the array bigger. /// /// <b>The Data pin has to be connected to pin D8!</b> /// /// It needs to be pin D8 because the class writes directly to the right register. /// /// references: /// - <A HREF="https://cdn-shop.adafruit.com/datasheets/WS2812.pdf"> /// WS2812 data sheet</A> (pdf) class neopixel_uno : public neopixel { public: /// \brief /// Constructor for the Uno implementation of ws2812 /// \details /// This constructor creates an interface for the D8 pin, so the LEDS can be controlled by various functions. /// The LEDs can be flushed through this subclass. /// /// \param n_leds number of leds that are chained and needs to be controlled. neopixel_uno( const int &n_leds ): neopixel( n_leds ) { DDRB = DDRB | 0b00000001; PORTB = 0b00000000; hwlib::wait_ms(1); } /// \brief /// Flush buffer to LEDs /// \details /// This function writes only if something is changed in the array. /// /// If so, the array is written to the LEDs, and the bool something_changed is set to false. /// The idea of how to flush is from:\n\t /// kevindarrah.com/download/arduino_code/WS1812_V4_FOR_VIDEO.ino void flush( ) override; }; /// \example neopixel_example.cpp #endif // NEOPIXEL_UNO_HPP
Java
UTF-8
1,186
2.09375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) allesklar.com AG * All rights reserved. * * Author: juergi * Date: 09.06.12 * */ package com.jmelzer.data.model.ui; import com.jmelzer.data.model.ModelBase; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "view") public class View extends ModelBase { private static final long serialVersionUID = 2242732315432572152L; String name; String decription; private List<ViewTab> tabs = new ArrayList<ViewTab>(); @Column(unique = true) public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDecription() { return decription; } public void setDecription(String decription) { this.decription = decription; } @OneToMany(cascade = CascadeType.ALL) @JoinColumn(name = "tab_id") @OrderBy("position") public List<ViewTab> getTabs() { return tabs; } public void setTabs(List<ViewTab> tabs) { this.tabs = tabs; } public void addTab(ViewTab tab) { tabs.add(tab); } }
Go
UTF-8
667
3.265625
3
[ "MIT" ]
permissive
package main import "testing" func TestMostCommonWord(t *testing.T) { tcs := []struct { inParagraph string inBanned []string out string }{ {"Bob hit a ball, the hit BALL flew far after it was hit.", []string{"hit"}, "ball"}, {"a", []string{""}, "a"}, {"a b a", []string{""}, "a"}, {"a b a", []string{"a"}, "b"}, {"c a b a c d", []string{"a"}, "c"}, {"!c; a. b, a' !ca?c d;", []string{"a"}, "c"}, } for idx, tc := range tcs { out := mostCommonWord(tc.inParagraph, tc.inBanned) if out != tc.out { t.Errorf("%d. mostCommonWord(%q, %v) = %q. Expected: %q", idx, tc.inParagraph, tc.inBanned, out, tc.out) } } }
PHP
UTF-8
979
2.59375
3
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php namespace Kirby\Panel\Collections; use Exception; use Kirby\Panel\Event; use Kirby\Panel\Models\User; class Users extends \Users { public function __construct() { parent::__construct(); $this->map(function($user) { return new User($user->username()); }); } public function topbar($topbar) { $topbar->append(purl('users'), l('users')); } public function create($data) { $event = panel()->user()->event('create:action'); if($data['password'] !== $data['passwordconfirmation']) { throw new Exception(l('users.form.error.password.confirm')); } unset($data['passwordconfirmation']); // set the event data $event->target->data = $data; // check for permissions $event->check(); // create the user $user = parent::create($data); // trigger the create hook kirby()->trigger($event, $user); // return the new user object return new User($user->username()); } }
Java
UTF-8
1,716
1.929688
2
[]
no_license
package com.teratech.achat.jaxrs.ifaces.operations; import com.megatimgroup.generic.jax.rs.layer.ifaces.GenericService; import com.teratech.achat.model.operations.DemandePrix; import com.teratech.achat.model.operations.ReponseFournisseur; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Interface du service JAX-RS * @since Tue Feb 27 14:29:40 GMT+01:00 2018 * */ public interface DemandePrixRS extends GenericService<DemandePrix, Long> { @PUT @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @Path("confirme") public DemandePrix confirmer(@Context HttpHeaders headers,DemandePrix entity); @PUT @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @Path("envoye") public DemandePrix envoyer(@Context HttpHeaders headers,DemandePrix entity); @PUT @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @Path("engage") public DemandePrix engage(@Context HttpHeaders headers,DemandePrix entity); @PUT @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @Path("annule") public DemandePrix annule(@Context HttpHeaders headers,DemandePrix entity); @PUT @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @Path("imprime") public List<ReponseFournisseur> imprimer(@Context HttpHeaders headers,DemandePrix dmde); }
Markdown
UTF-8
778
2.6875
3
[]
no_license
# Yape ## Proyecto final Sprint5 Yape es la nueva aplicación del Banco de Crédito del Perú, con la que tendrás la libertad de usar tu dinero como quieras, ya que pagar con ella es más rápido, sin pretextos y fácil. Solo con Yape podrás convertir tus planes en experiencias únicas, sin números de cuenta ni token. ## Requerimientos 1. Trabajar con componentes 2. Usar la data del API 3. Seguir el diseño al 100% 4. Estructura con buenas prácticas (HTML,CSS,JS) ## Librerias externas He utilizado las siguientes librerias y framework: - Bootstrap ([http://getbootstrap.com/](http://getbootstrap.com/)) - OwlCarousel ([https://owlcarousel2.github.io/OwlCarousel2/](https://owlcarousel2.github.io/OwlCarousel2/)) - Jquery ([https://jquery.com/](https://jquery.com/))
C#
UTF-8
1,987
3.125
3
[ "MIT" ]
permissive
namespace _1.Logger.Core { using _1.Logger.Factories; using _1.Logger.Interfaces; using System; public class Controller { private FactoryAppender factoryAppender; public Controller() { this.factoryAppender = new FactoryAppender(); } public void Run() { var numberOfAppenders = int.Parse(Console.ReadLine()); var appenders = new IAppender[numberOfAppenders]; for (int i = 0; i < numberOfAppenders; i++) { IAppender appender = this.factoryAppender.Create(Console.ReadLine()); appenders[i] = appender; } var logger = new Models.LoggerModels.Logger(appenders); var messageInfoLine = Console.ReadLine(); while (messageInfoLine != "END") { var messageTokens = messageInfoLine.Split('|'); var reportLevel = messageTokens[0]; var date = messageTokens[1]; var msg = messageTokens[2]; switch (reportLevel) { case "INFO": logger.Info(date, msg); break; case "WARNING": logger.Warn(date, msg); break; case "ERROR": logger.Error(date, msg); break; case "CRITICAL": logger.Critical(date, msg); break; case "FATAL": logger.Fatal(date, msg); break; } messageInfoLine = Console.ReadLine(); } Console.WriteLine("Logger info"); foreach (var appender in logger.GetAppenders()) { Console.WriteLine(appender); } } } }
Java
UTF-8
1,529
2.3125
2
[]
no_license
package com.example.rabbtmq.parent.consumer; import com.example.rabbtmq.parent.common.TagConstant; import com.example.rabbtmq.parent.provider.ChannelUtil; import com.rabbitmq.client.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.concurrent.TimeoutException; @Configuration public class DirectConsumer { @Autowired private ChannelUtil channelUtil; @Bean(name = "directConsumer2") public Consumer directConsumer2()throws Exception { //创建通道 Channel channel = channelUtil.createDirectChannel(); //队列声明 channel.queueDeclare(TagConstant.DIRECT_QUEUE_NAME, false, false, false, null); DefaultConsumer consumer = new DefaultConsumer(channel) { //获取到达的消息 @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { super.handleDelivery(consumerTag, envelope, properties, body); String msg = new String(body, "utf-8"); System.out.println("================================direct consumer:" + msg); } }; //监听队列 channel.basicConsume(TagConstant.DIRECT_QUEUE_NAME, true, consumer); return consumer; } }
Go
UTF-8
9,952
2.546875
3
[ "MIT" ]
permissive
package spider import ( "database/sql" "github.com/esrrhs/go-engine/src/loggo" _ "github.com/mattn/go-sqlite3" "net/url" "sync" "time" ) type DB struct { gdb *sql.DB lock sync.Mutex gInsertStmt *sql.Stmt gSizeStmt *sql.Stmt gLastStmt *sql.Stmt gFindStmt *sql.Stmt gDeleteStmt *sql.Stmt } type JobDB struct { gdb *sql.DB src string lock sync.Mutex gInsertJobStmt *sql.Stmt gSizeJobStmt *sql.Stmt gPeekJobStmt *sql.Stmt gDeleteJobStmt *sql.Stmt gHasJobStmt *sql.Stmt } type DoneDB struct { gdb *sql.DB src string lock sync.Mutex gInsertDoneStmt *sql.Stmt gSizeDoneStmt *sql.Stmt gDeleteDoneStmt *sql.Stmt gHasDoneStmt *sql.Stmt } func Load(dsn string, conn int) *DB { loggo.Info("mysql Load start") gdb, err := sql.Open("mysql", dsn) if err != nil { loggo.Error("open mysql fail %v", err) return nil } err = gdb.Ping() if err != nil { loggo.Error("open mysql fail %v", err) return nil } gdb.SetConnMaxLifetime(0) gdb.SetMaxIdleConns(conn) gdb.SetMaxOpenConns(conn) ret := new(DB) ret.gdb = gdb _, err = gdb.Exec("CREATE DATABASE IF NOT EXISTS spider") if err != nil { loggo.Error("CREATE DATABASE fail %v", err) return nil } _, err = gdb.Exec("CREATE TABLE IF NOT EXISTS spider.link_info(" + "url VARCHAR(200) NOT NULL ," + "title VARCHAR(200) NOT NULL," + "name VARCHAR(200) NOT NULL," + "time DATETIME NOT NULL," + "PRIMARY KEY(url)," + "INDEX `time`(`time`) USING BTREE" + ");") if err != nil { loggo.Error("CREATE TABLE fail %v", err) return nil } stmt, err := gdb.Prepare("insert IGNORE into spider.link_info(title, name, url, time) values(?, ?, ?, NOW())") if err != nil { loggo.Error("Prepare mysql fail %v", err) return nil } ret.gInsertStmt = stmt stmt, err = gdb.Prepare("select count(*) as ret from spider.link_info") if err != nil { loggo.Error("HasDone Prepare mysql fail %v", err) return nil } ret.gSizeStmt = stmt stmt, err = gdb.Prepare("select title,name,url from spider.link_info order by time desc limit 0, ?") if err != nil { loggo.Error("Prepare mysql fail %v", err) return nil } ret.gLastStmt = stmt stmt, err = gdb.Prepare("select title,name,url from spider.link_info where name like ? or title like ? limit 0,?") if err != nil { loggo.Error("Prepare mysql fail %v", err) return nil } ret.gFindStmt = stmt stmt, err = gdb.Prepare("delete from spider.link_info where (TO_DAYS(NOW()) - TO_DAYS(time))>=30") if err != nil { loggo.Error("Prepare mysql fail %v", err) return nil } ret.gDeleteStmt = stmt //// go DeleteOldSpider(ret) num := GetSize(ret) loggo.Info("mysql size %v", num) return ret } func LoadJob(src string) *JobDB { loggo.Info("sqlite3 Load Job start %v", src) dstURL, _ := url.Parse(src) host := dstURL.Host gdb, err := sql.Open("sqlite3", "./spider_job_"+host+".db") if err != nil { loggo.Error("open sqlite3 Job fail %v", err) return nil } ret := new(JobDB) ret.gdb = gdb ret.src = src gdb.Exec("CREATE TABLE IF NOT EXISTS [link_job_info](" + "[src] TEXT NOT NULL," + "[url] TEXT NOT NULL," + "[deps] INT NOT NULL," + "[time] DATETIME NOT NULL," + "PRIMARY KEY([url]) ON CONFLICT IGNORE);") stmt, err := gdb.Prepare("insert into link_job_info(src, url, deps, time) values(?, ?, ?, DATETIME())") if err != nil { loggo.Error("Prepare Job sqlite3 fail %v", err) return nil } ret.gInsertJobStmt = stmt stmt, err = gdb.Prepare("select count(*) from link_job_info where src = ?") if err != nil { loggo.Error("HasDone Job Prepare sqlite3 fail %v", err) return nil } ret.gSizeJobStmt = stmt stmt, err = gdb.Prepare("delete from link_job_info where src = ? and url = ?") if err != nil { loggo.Error("Prepare Job sqlite3 fail %v", err) return nil } ret.gDeleteJobStmt = stmt stmt, err = gdb.Prepare("select url, deps from link_job_info where src = ? limit 0, ?") if err != nil { loggo.Error("Prepare Job sqlite3 fail %v", err) return nil } ret.gPeekJobStmt = stmt stmt, err = gdb.Prepare("select url from link_job_info where src = ? and url = ?") if err != nil { loggo.Error("Prepare Job sqlite3 fail %v", err) return nil } ret.gHasJobStmt = stmt num := GetJobSize(ret) loggo.Info("sqlite3 Job size %v %v", src, num) return ret } func LoadDone(src string) *DoneDB { loggo.Info("sqlite3 Load Done start %v", src) dstURL, _ := url.Parse(src) host := dstURL.Host gdb, err := sql.Open("sqlite3", "./spider_done_"+host+".db") if err != nil { loggo.Error("open sqlite3 Done fail %v", err) return nil } ret := new(DoneDB) ret.gdb = gdb ret.src = src gdb.Exec("CREATE TABLE IF NOT EXISTS [link_done_info](" + "[src] TEXT NOT NULL," + "[url] TEXT NOT NULL," + "[time] DATETIME NOT NULL," + "PRIMARY KEY([url]) ON CONFLICT IGNORE);") //// stmt, err := gdb.Prepare("insert into link_done_info(src, url, time) values(?, ?, DATETIME())") if err != nil { loggo.Error("Prepare sqlite3 fail %v", err) return nil } ret.gInsertDoneStmt = stmt stmt, err = gdb.Prepare("select count(*) from link_done_info where src = ?") if err != nil { loggo.Error("HasDone Prepare sqlite3 fail %v", err) return nil } ret.gSizeDoneStmt = stmt stmt, err = gdb.Prepare("delete from link_done_info where src = ?") if err != nil { loggo.Error("Prepare sqlite3 fail %v", err) return nil } ret.gDeleteDoneStmt = stmt stmt, err = gdb.Prepare("select url from link_done_info where src = ? and url = ?") if err != nil { loggo.Error("Prepare sqlite3 fail %v", err) return nil } ret.gHasDoneStmt = stmt //// num := GetDoneSize(ret) loggo.Info("sqlite3 size %v %v", src, num) return ret } func PopSpiderJob(db *JobDB, n int) ([]string, []int) { var ret []string var retdeps []int db.lock.Lock() rows, err := db.gPeekJobStmt.Query(db.src, n) if err != nil { loggo.Error("PopSpiderJob Query sqlite3 fail %v %v", db.src, err) db.lock.Unlock() return ret, retdeps } defer rows.Close() db.lock.Unlock() for rows.Next() { var url string var deps int err = rows.Scan(&url, &deps) if err != nil { loggo.Error("PopSpiderJob Scan sqlite3 fail %v %v", db.src, err) } ret = append(ret, url) retdeps = append(retdeps, deps) } for i, url := range ret { db.lock.Lock() db.gDeleteJobStmt.Exec(db.src, url) db.lock.Unlock() loggo.Info("PopSpiderJob %v %v %v", db.src, url, retdeps[i]) } return ret, retdeps } func DeleteSpiderDone(db *DoneDB) { db.lock.Lock() db.gDeleteDoneStmt.Exec(db.src) db.lock.Unlock() } func InsertSpiderJob(db *JobDB, url string, deps int) { db.lock.Lock() _, err := db.gInsertJobStmt.Exec(db.src, url, deps) if err != nil { loggo.Error("InsertSpiderJob insert sqlite3 fail %v %v", url, err) } db.lock.Unlock() loggo.Info("InsertSpiderJob %v ", url) } func InsertSpiderDone(db *DoneDB, url string) { db.lock.Lock() _, err := db.gInsertDoneStmt.Exec(db.src, url) if err != nil { loggo.Error("InsertSpiderDone insert sqlite3 fail %v %v", url, err) } db.lock.Unlock() loggo.Info("InsertSpiderDone %v ", url) } func DeleteOldSpider(db *DB) { for { db.lock.Lock() db.gDeleteStmt.Exec() db.lock.Unlock() loggo.Info("DeleteOldSpider %v", GetSize(db)) time.Sleep(time.Hour) } } func InsertSpider(db *DB, title string, name string, url string) { db.lock.Lock() _, err := db.gInsertStmt.Exec(title, name, url) if err != nil { loggo.Error("InsertSpider insert sqlite3 fail %v %v", url, err) } db.lock.Unlock() loggo.Info("InsertSpider %v %v %v", title, name, url) } func HasJob(db *JobDB, url string) bool { db.lock.Lock() var surl string err := db.gHasJobStmt.QueryRow(db.src, url).Scan(&surl) if err != nil { db.lock.Unlock() return false } db.lock.Unlock() return true } func HasDone(db *DoneDB, url string) bool { db.lock.Lock() var surl string err := db.gHasDoneStmt.QueryRow(db.src, url).Scan(&surl) if err != nil { db.lock.Unlock() return false } db.lock.Unlock() return true } func GetSize(db *DB) int { db.lock.Lock() var ret int err := db.gSizeStmt.QueryRow().Scan(&ret) if err != nil { loggo.Error("GetSize fail %v", err) } db.lock.Unlock() return ret } func GetJobSize(db *JobDB) int { db.lock.Lock() var ret int err := db.gSizeJobStmt.QueryRow(db.src).Scan(&ret) if err != nil { loggo.Error("GetJobSize fail %v %v", db.src, err) } db.lock.Unlock() return ret } func GetDoneSize(db *DoneDB) int { db.lock.Lock() var ret int err := db.gSizeDoneStmt.QueryRow(db.src).Scan(&ret) if err != nil { loggo.Error("GetDoneSize fail %v %v", db.src, err) } db.lock.Unlock() return ret } type FindData struct { Title string Name string URL string } func Last(db *DB, n int) []FindData { var ret []FindData retmap := make(map[string]string) db.lock.Lock() rows, err := db.gLastStmt.Query(n) if err != nil { loggo.Error("Last Query sqlite3 fail %v", err) db.lock.Unlock() return ret } defer rows.Close() for rows.Next() { var title string var name string var url string err := rows.Scan(&title, &name, &url) if err != nil { loggo.Error("Last Scan sqlite3 fail %v", err) } _, ok := retmap[url] if ok { continue } retmap[url] = name ret = append(ret, FindData{title, name, url}) } db.lock.Unlock() return ret } func Find(db *DB, str string, max int) []FindData { var ret []FindData db.lock.Lock() rows, err := db.gFindStmt.Query("%"+str+"%", "%"+str+"%", max) if err != nil { loggo.Error("Find Query sqlite3 fail %v", err) db.lock.Unlock() return ret } defer rows.Close() for rows.Next() { var title string var name string var url string err = rows.Scan(&title, &name, &url) if err != nil { loggo.Error("Find Scan sqlite3 fail %v", err) } ret = append(ret, FindData{title, name, url}) } db.lock.Unlock() return ret }
Java
UTF-8
823
1.9375
2
[]
no_license
package com.eat.better.service; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.eat.better.entity.User; import com.eat.better.service.dto.user.UserDTOGet; import com.eat.better.service.dto.user.UserDTOPost; import com.eat.better.service.exception.CreateUpdateException; import com.eat.better.service.exception.DeleteException; import com.eat.better.service.exception.ReadException; public interface UserService { void saveAndFlush(UserDTOPost dto) throws CreateUpdateException; UserDTOGet findOne(Long id) throws ReadException; List<UserDTOGet> findAll() throws ReadException; void delete(Long id) throws DeleteException; Page<User> findBy(String searchValue, Pageable pageable) throws ReadException; }
TypeScript
UTF-8
537
2.75
3
[]
no_license
import {Request} from 'express'; /** * Custom request object that includes body and session objects unlike native express Request * @author Jānis Radiņš */ export interface CustomRequest extends Request { /** * Once body-parser is added there's body property in request but no signature of it in incoming Request */ body?: {[name:string]:any}, /** * expressSession session data object with some custom glue for particular use case */ session?: { authKey?:string, [name:string]:any } }
C++
UTF-8
1,581
3.046875
3
[]
no_license
#ifndef __TIME_SERIES_MOD_H__ #define __TIME_SERIES_MOD_H__ #include <vector> #include <algorithm> // std::find_if #include <math.h> class TimeSeriesMod { protected: struct Tpv{ Tpv() = delete; Tpv(double _t, double _pRes, double _pSys, double _pO2, double _lvol, bool _valveA, bool _valveB, bool _valveC, bool _valveD) : t(_t), pRes(_pRes), pSys(_pSys), pO2(_pO2), lvol(_lvol), valveA(_valveA), valveB(_valveB), valveC(_valveC), valveD(_valveD) {}; double t; double pRes; double pSys; double pO2; double lvol; bool valveA; bool valveB; bool valveC; bool valveD; }; typedef std::vector<Tpv> TpvVector_t; TpvVector_t ts; public: typedef TpvVector_t::iterator iterator; typedef TpvVector_t::const_iterator const_iterator; iterator begin() { return ts.begin();} iterator end() { return ts.end(); } Tpv &back() { return ts.back(); } void push_back(const Tpv &tpv); void push_back(double t, double pRes, double pSys, double pO2, double lvol, bool valveA, bool valveB, bool valveC, bool valveD) { ts.push_back(Tpv(t, pRes, pSys, pO2, lvol, valveA, valveB, valveC, valveD )); }; iterator findTime(double time, double precision) { auto it = std::find_if( ts.begin(), ts.end(), [time, precision](const Tpv& e){ return (fabs(e.t - time) < precision); }); return(it); }; private: }; #endif
C++
UTF-8
2,801
2.875
3
[ "BSD-2-Clause" ]
permissive
/** * Copyleft (c) 2014 * @Author: Ke, Xianda * @Date: 2014-08-31 * * implement a stl::vector like container: xtl:vetcor * * * * */ /** * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * **/ #ifndef _XTL_VECTOR_H #define _XTL_VECTOR_H 1 #include "xtl_memory.h" #include "xtl_allocate.h" #include "xtl_iterator.h" namespace xtl { template <typename T, typename Alloc = xtl::allocator<T> > class vector { public: typedef T value_type; typedef T& reference; typedef const T& const_reference; typedef T* pointer; typedef const T* const_pointer; typedef T* iterator; typedef size_t size_type; typedef Alloc allocator_type; //todo: reverse_iterator //reverse_iterator //const_reverse_iterator vector() : m_start(nullptr), m_finish(nullptr), m_end_of_storage(nullptr), m_size(0) {} explicit vector(size_type n, const value_type& val = value_type()) { this->m_start = allocator_type::allocate (n); this->m_finish = this->m_start + n; this->m_end_of_storage = this->m_start + n; this->m_size = n; xtl::uninitialized_fill_n(this->m_start, n, val); } vector (iterator from_itr, iterator to_itr) { typename iterator_traits<iterator>::difference_type n; n = distance (from_itr, to_itr); this->m_start = allocator_type::allocate (n); this->m_finish = this->m_start + n; this->m_end_of_storage = this->m_start + n; this->m_size = n; iterator curr = m_start; while (from_itr != to_itr) { copy_construct (curr++, *from_itr++); } } vector (const vector& v) { size_type n = v.size (); this->m_start = allocator_type::allocate (n); this->m_finish = xtl::unititialized_copy (v.begin(), v.end(), m_start); this->m_end_of_storage = this->m_finish; this->m_size = n; } #if __cplusplus >= 201103L //todo: move constructor. c++11 #endif //C++ 11 ~vector() { //todo xtl::destory(m_start, m_finish); allocator_type::deallocate(m_start); } iterator begin () const { return this->m_start; } iterator end () const { //const_iterator return this->m_finish; } size_type size () const { return m_size; } protected: iterator m_start; iterator m_finish; iterator m_end_of_storage; size_type m_size; }; } #endif /*_XTL_VECOTR_H*/
Java
UTF-8
673
3.53125
4
[]
no_license
package Collection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListConcept { public static void main(String[] args) { /*List<String> list=new ArrayList<>(); list.add("amrit"); list.add("samar"); list.add("preeti"); Iterator iterator=list.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); }*/ try { int a=10; int b=20; int c=0; c=a/0; } catch(ArithmeticException e1) { System.out.println("It's a "+e1); } catch(Exception e) { System.out.println("This is not possible 2nd time"); } } }
Python
UTF-8
832
3.375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Dec 13 20:18:35 2019 @author: Arnab Das """ import numpy as np x1n = [1,2,3,4] x2n = [5,6,7,8] xn = x1n + np.multiply(1j,x2n) print("xn: "+str(xn)) """DFT """ N = len(xn) dft = [] for k in range(N): mult = 0 mult1 = 0 for n in range(N): exp = np.exp((-1j*2*np.pi*n*k)/N) mult += np.dot(xn[n],exp) dft.append(np.around(mult)) print("Xk: "+str(dft)) """X*(N-k)""" result_dft = [] result_dft.append(np.conjugate(dft[0])) for i in range(1,N,1): result_dft.append(np.conjugate(dft[N-i])) print("X*[N-K]: "+str(result_dft)) """X1k ans X2k""" a = np.add(dft,result_dft) sum1 = np.multiply(a,0.5) b = np.subtract(result_dft,dft) sum2 = np.multiply(b,0.5j) print("X1k: "+str(sum1)) print("X2k: "+str(sum2))
Python
UTF-8
1,416
3.09375
3
[]
no_license
from unionfind import UnionFind as uf import sys import random as r class Percolation: def __init__(self, n): self.grid= [[0 for i in range(n)] for j in range(n)] self.u = uf(n**2) def showGrid(self): for i in range(len(self.grid)): print(self.grid[i]) def isOpen(self, row, col): return self.grid[row][col] def open(self, row, col): self.grid[row][col]=1 self.union(row,col) #print(self.grid) def openSites(self): #print(self.grid) return sum(map(sum,self.grid)) def union(self,row,col): l=len(self.grid) i=row*l+col if(col+1<l): if(self.grid[row][col+1]==1): self.u.union(i, i+1) if(col-1>=0): if(self.grid[row][col-1]==1): self.u.union(i, i-1) if(row+1<l): if(self.grid[row+1][col]==1): self.u.union(i, i+l) def percolates(self): l=len(self.grid) size=l**2 for i in range(l): for j in range(size-l,size): if(self.u.find(i,j)): #self.showGrid() #print("Percolates", self.openSites()) return True #print("Does not percolate", self.openSites()) return False
Java
UTF-8
776
2.390625
2
[]
no_license
package com.apifest.oauth20; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.annotate.JsonUnwrapped; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; /** * Access token decorated with the CSRF state attribute. * * @author Edouard De Oliveira */ @JsonSerialize(include=Inclusion.NON_EMPTY) public class CSRFAccessToken { @JsonUnwrapped @JsonProperty("token") private AccessToken token; @JsonProperty("state") private String state; public CSRFAccessToken(AccessToken token, String state) { this.token = token; this.state = state; } protected AccessToken getToken() { return token; } protected String getState() { return state; } }
Java
UTF-8
511
2.046875
2
[]
no_license
package com.hank.library.util; import rx.Subscriber; public abstract class HttpSubscriber<T> extends Subscriber<T> { @Override public void onCompleted() { _complete(); } @Override public void onError(Throwable e) { _complete(); onError(e.getMessage()); } @Override public void onNext(T t) { onSuccess(t); } public abstract void onSuccess(T t); public abstract void onError(String msg); public abstract void _complete(); }
C
UTF-8
332
3.53125
4
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<math.h> int main(){ double a,b,c,t; printf("Digite os lados dos triangulo \n"); scanf("%lf, %lf", &a,&b); printf("Digite o valor do angulo \n"); scanf("%lf", &t); c=sqrt(pow(b,2)+pow(a,2)-2*a*b*cos(t)); printf("O terceiro lado e = %lf \n", c); return EXIT_SUCCESS; }
Python
UTF-8
589
2.828125
3
[]
no_license
import pyaudio import numpy as np CHUNK = 2**11 RATE = 44100 p=pyaudio.PyAudio() stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True, frames_per_buffer=CHUNK) while 1: #go for a few seconds data = np.fromstring(stream.read(CHUNK),dtype=np.int16) peak=np.average(np.abs(data))*2 bars="#"*int(50*peak/2**12) print("%05d %s"%(peak,bars)) stream.stop_stream() stream.close() p.terminate() # Source borrowed from: https://www.swharden.com/wp/2016-07-19-realtime-audio-visualization-in-python/ # Special thanks to author
Java
UTF-8
3,960
2.71875
3
[]
no_license
package com.jpmc.tutorial.service.impl.calculators; import com.jpmc.tutorial.exception.SimpleStockException; import com.jpmc.tutorial.exception.StockPriceCalculationException; import com.jpmc.tutorial.model.Side; import com.jpmc.tutorial.model.Stock; import com.jpmc.tutorial.model.StockType; import com.jpmc.tutorial.model.Trade; import com.jpmc.tutorial.model.builders.StockBuilder; import com.jpmc.tutorial.model.builders.TradeBuilder; import com.jpmc.tutorial.service.TradeService; import org.mockito.Matchers; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Date; import java.util.DoubleSummaryStatistics; import java.util.List; /** * Created by manish on 9/15/2015. */ public class StockPriceCalculatorTest { private TradeService tradeService; private StockPriceCalculator stockPriceCalculator; @Test public void shouldSuccessfullyCalculateStockPriceWhenLatestTradesAreValid() throws Exception { //Given List<Trade> validTrades = new ArrayList<>(); validTrades.add(TradeBuilder.getTradeBuilder().withPrice(10.0d) .withQuantity(40) .withSide(Side.BUY) .withTradeTime(new Date()) .withTickerSymbol("AEL").build()); validTrades.add(TradeBuilder.getTradeBuilder().withPrice(20.0d) .withQuantity(60) .withSide(Side.SELL) .withTradeTime(new Date()) .withTickerSymbol("AEL").build()); Double expectedStockPrice = 16.0d; Mockito.when(tradeService.getLatestTrades("ALE", 900)).thenReturn(validTrades); //When Double actualStockPrice = stockPriceCalculator.calculate("ALE"); //Then Assert.assertEquals(actualStockPrice, expectedStockPrice); } @Test(expectedExceptions = { StockPriceCalculationException.class }, expectedExceptionsMessageRegExp = "No Latest Trades for Stock price Calculation") public void shouldThrowAnExceptionWhenThereIsNoLatestTrades() throws Exception{ //Given List<Trade> validTrades = new ArrayList<>(); Mockito.when(tradeService.getLatestTrades("ALE", 900)).thenReturn(validTrades); //When stockPriceCalculator.calculate("ALE"); } @Test(expectedExceptions = { IllegalArgumentException.class }, expectedExceptionsMessageRegExp = "Quantity Value can not be negative or zero") public void shouldThrowAnExceptionWhenThereIsTradeWithInValidValue() throws Exception{ //Given List<Trade> validTrades = new ArrayList<>(); validTrades.add(TradeBuilder.getTradeBuilder().withPrice(20.0d) .withQuantity(0) .withSide(Side.SELL) .withTradeTime(new Date()) .withTickerSymbol("AEL").build()); Mockito.when(tradeService.getLatestTrades("ALE", 900)).thenReturn(validTrades); //When stockPriceCalculator.calculate("ALE"); } @Test(expectedExceptions = { IllegalArgumentException.class }, expectedExceptionsMessageRegExp = "Price Value can not be negative") public void shouldThrowAnExceptionWhenThereIsTradeWithInValidQuantityValue() throws Exception{ //Given List<Trade> validTrades = new ArrayList<>(); validTrades.add(TradeBuilder.getTradeBuilder().withPrice(-20.0d) .withSide(Side.SELL) .withQuantity(10) .withTradeTime(new Date()) .withTickerSymbol("AEL").build()); Mockito.when(tradeService.getLatestTrades("ALE", 900)).thenReturn(validTrades); //When stockPriceCalculator.calculate("ALE"); } @BeforeClass public void BeforeClass() { tradeService = Mockito.mock(TradeService.class); stockPriceCalculator = new StockPriceCalculator(tradeService); } }
JavaScript
UTF-8
633
2.5625
3
[]
no_license
import { useDispatch } from 'react-redux'; import { decrement, increment } from './redux/ducks/counter'; const Counter = () => { //const [count, setCount] = useState(3); const dispatch= useDispatch(); const handleIncrement=()=>{ dispatch(increment()); } const handleDecrement =() =>{ dispatch(decrement()); } return ( <div> <h3>Welcome to my counter :)</h3> <button onClick = {handleIncrement}> Increment</button> <button onClick = {handleDecrement}>Decrement</button> </div> ); } export default Counter;
Java
UTF-8
351
1.796875
2
[ "Apache-2.0" ]
permissive
package com.example.daniel.thesis_v10; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class hardGameActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hard_game); } }
PHP
UTF-8
781
3
3
[]
no_license
<?php interface Zwas_Cache_Interface { /** * Save data in cache * * @param string $id Access key for storing/fetching data * @param mixed $data Data to cache * @param integer $ttl Time to leave (seconeds) * @return boolean true if data stored succesfully, otherwise false */ public function store($id, $data, $ttl); /** * Fetch data from cache * * @param string $id Access key for storing/fetching data * @return mixed Return the cache data or null if cache is invalid (Pass ttl, key not exist etc.) */ public function fetch($id); /** * Check for cache if exist and valid * * @param string $id Access key for storing/fetching data * @return boolean true if the key exist and ttl is still valid */ public function exist($id); }
Python
UTF-8
960
4.1875
4
[ "MIT" ]
permissive
def mult(x, y): result_mult = 0 i = 0 while i < y: # Here I choose 'y' (witch is the base) to show how many times 'x' going to be sum with itself. i += 1 result_mult += x return result_mult def expo(): base = int(input("Type a base: ")) expo = int(input("Type an exponent: ")) if base < 0 or 0 > expo: print("Don't type any negative value, please try again.") else: result_expo = 1 if expo == 0: # If the exponent is equal 0 the result number going to be '1'. print(f"{base} ^ {expo} = {result_expo}".format(base,expo,result_expo)) else: i = 0 while i < expo: i += 1 result_expo = mult(result_expo, base) # result_expo is being multiplied by the base, it's the same thing as ( result_expo * base ) print(f"{base} ^ {expo} = {result_expo}".format(base,expo,result_expo)) expo()
Markdown
UTF-8
436
3.75
4
[]
no_license
# ReversibleNumbers Some positive integers n have the poperty that the sum [n + reverse(n)] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409 and 904 are reversible. Leading zeros are not allowed in either n or reverse(n). There are 120 reversible numbers below one thousand. How many reversible numbers are there below one billion (109)?
JavaScript
UTF-8
875
2.765625
3
[ "MIT" ]
permissive
function check() { var flexbox = false; var x = document.createElement('div'); x.style.display = 'box'; if (x.style.display == 'box') flexbox = true; x.style.display = '-webkit-box'; if (x.style.display == '-webkit-box') flexbox = true; x.style.display = '-moz-box'; if (x.style.display == '-moz-box') flexbox = true; x.style.display = '-ms-box'; if (x.style.display == '-ms-box') flexbox = true; x.style.display = '-o-box'; if (x.style.display == '-o-box') flexbox = true; var filereader = false; if (typeof FileReader !== 'undefined') filereader = true; var canvas = false; x = document.createElement('canvas'); if (typeof x.getContext !== 'undefined') canvas = true; if (!canvas || !filereader || !flexbox) { document.location.href = 'sorry.html'; } } check();
C#
ISO-8859-1
16,352
2.59375
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections; using System.Text; namespace BoletoNet { #region Enumerado public enum EnumCarteiras_Itau { EscritualEletronicaSimples = 112, EscritualEletronicaSimplesNossoNumeroLivre = 115, EscritualEletronicaCarne = 104, EscritualEletronicaDolar = 147, EscritualEletronicaCobrancaInteligente = 188, DiretaEletronicaEmissaoIntegralCarne = 108, DiretaEletronicaSemEmissaoSimples = 109, DiretaEletronicaSemEmissaoDolar = 150, DiretaEletronicaEmissaoParcialSimples = 121, DiretaEletronicaEmissaoInegralSimples = 180, SemRegistroSemEmissaoComProtestoEletronico = 175, SemRegistroSemEmissao15Digitos = 198, SemRegistroSemEmissao15DigitosIOF4 = 142, SemRegistroSemEmissao15DigitosIOF7 = 143, SemRegistroEmissaoParcialComProtestoBordero = 174, SemRegistroEmissaoParcialComProtestoEletronico = 177, SemRegistroEmissaoParcialSegurosIOF2 = 129, SemRegistroEmissaoParcialSegurosIOF4 = 139, SemRegistroEmissaoParcialSegurosIOF7 = 169, SemRegistroEmissaoIntegral = 172, SemRegistroEmissaoIntegralCarne = 102, SemRegistroEmissaoIntegral15PosicoesCarne = 107, SemRegistroEmissaoEntrega = 173, SemRegistroEmissaoEntregaCarne = 103, SemRegistroEmissaoEntrega15Posicoes = 196, } #endregion public class Carteira_Itau: AbstractCarteira, ICarteira { #region Construtores public Carteira_Itau() { try { this.Banco = new Banco(341); } catch (Exception ex) { throw new Exception("Erro ao carregar objeto", ex); } } public Carteira_Itau(int carteira) { try { this.carregar(carteira); } catch (Exception ex) { throw new Exception("Erro ao carregar objeto", ex); } } #endregion #region Metodos Privados private void carregar(int carteira) { try { this.Banco = new Banco_Itau(); switch ((EnumCarteiras_Itau)carteira) { case EnumCarteiras_Itau.EscritualEletronicaSimples: this.NumeroCarteira = (int)EnumCarteiras_Itau.EscritualEletronicaSimples; this.Codigo = "I"; this.Tipo = "E"; this.Descricao = "Escritural eletrnica simples"; break; case EnumCarteiras_Itau.EscritualEletronicaSimplesNossoNumeroLivre: this.NumeroCarteira = (int)EnumCarteiras_Itau.EscritualEletronicaSimplesNossoNumeroLivre; this.Codigo = "I"; this.Tipo = "E"; this.Descricao = "Escritural eletrnica simples - Faixa nosso nmero livre"; break; case EnumCarteiras_Itau.EscritualEletronicaCarne: this.NumeroCarteira = (int)EnumCarteiras_Itau.EscritualEletronicaCarne; this.Codigo = "I"; this.Tipo = "E"; this.Descricao = "Escritural eletrnica - Carn"; break; case EnumCarteiras_Itau.EscritualEletronicaDolar: this.NumeroCarteira = (int)EnumCarteiras_Itau.EscritualEletronicaDolar; this.Codigo = "E"; this.Tipo = "E"; this.Descricao = "Escritural eletrnica - Dlar"; break; case EnumCarteiras_Itau.EscritualEletronicaCobrancaInteligente: this.NumeroCarteira = (int)EnumCarteiras_Itau.EscritualEletronicaCobrancaInteligente; this.Codigo = "I"; this.Tipo = "E"; this.Descricao = "Escritural eletrnica - Cobrana inteligente"; break; case EnumCarteiras_Itau.DiretaEletronicaEmissaoIntegralCarne: this.NumeroCarteira = (int)EnumCarteiras_Itau.DiretaEletronicaEmissaoIntegralCarne; this.Codigo = "I"; this.Tipo = "D"; this.Descricao = "Direta eletrnica emisso integral - Carn"; break; case EnumCarteiras_Itau.DiretaEletronicaSemEmissaoSimples: this.NumeroCarteira = (int)EnumCarteiras_Itau.DiretaEletronicaSemEmissaoSimples; this.Codigo = "I"; this.Tipo = "D"; this.Descricao = "Direta eletrnica sem emisso - Simples"; break; case EnumCarteiras_Itau.DiretaEletronicaSemEmissaoDolar: this.NumeroCarteira = (int)EnumCarteiras_Itau.DiretaEletronicaSemEmissaoDolar; this.Codigo = "U"; this.Tipo = "D"; this.Descricao = "Direta eletrnica sem emisso - Dlar"; break; case EnumCarteiras_Itau.DiretaEletronicaEmissaoParcialSimples: this.NumeroCarteira = (int)EnumCarteiras_Itau.DiretaEletronicaEmissaoParcialSimples; this.Codigo = "I"; this.Tipo = "D"; this.Descricao = "Direta eletrnica emisso parcial - Simples"; break; case EnumCarteiras_Itau.DiretaEletronicaEmissaoInegralSimples: this.NumeroCarteira = (int)EnumCarteiras_Itau.DiretaEletronicaEmissaoInegralSimples; this.Codigo = "I"; this.Tipo = "D"; this.Descricao = "Direta eletrnica emisso integral - Simples"; break; case EnumCarteiras_Itau.SemRegistroSemEmissaoComProtestoEletronico: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroSemEmissaoComProtestoEletronico; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, sem emisso e com protesto eletrnico"; break; case EnumCarteiras_Itau.SemRegistroSemEmissao15Digitos: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroSemEmissao15Digitos; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro e sem emisso - 15 dgitos"; break; case EnumCarteiras_Itau.SemRegistroSemEmissao15DigitosIOF4: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroSemEmissao15DigitosIOF4; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro e sem emisso - 15 dgitos IOF 4%"; break; case EnumCarteiras_Itau.SemRegistroSemEmissao15DigitosIOF7: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroSemEmissao15DigitosIOF7; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro e sem emisso - 15 dgitos IOF 7%"; break; case EnumCarteiras_Itau.SemRegistroEmissaoParcialComProtestoBordero: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoParcialComProtestoBordero; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso parcial com protesto border"; break; case EnumCarteiras_Itau.SemRegistroEmissaoParcialComProtestoEletronico: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoParcialComProtestoEletronico; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso parcial com protesto eletrnico"; break; case EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF2: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF2; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso parcial, seguros com IOF 2%"; break; case EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF4: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF4; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso parcial, seguros com IOF 4%"; break; case EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF7: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF7; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso parcial, seguros com IOF 7%"; break; case EnumCarteiras_Itau.SemRegistroEmissaoIntegral: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoIntegral; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso integral"; break; case EnumCarteiras_Itau.SemRegistroEmissaoIntegralCarne: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoIntegralCarne; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso integral - Carn"; break; case EnumCarteiras_Itau.SemRegistroEmissaoIntegral15PosicoesCarne: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoIntegral15PosicoesCarne; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, emisso integral - 15 poies - Carn"; break; case EnumCarteiras_Itau.SemRegistroEmissaoEntrega: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoEntrega; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, com emisso e entrega"; break; case EnumCarteiras_Itau.SemRegistroEmissaoEntregaCarne: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoEntregaCarne; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, com emisso e entrega - Carn"; break; case EnumCarteiras_Itau.SemRegistroEmissaoEntrega15Posicoes: this.NumeroCarteira = (int)EnumCarteiras_Itau.SemRegistroEmissaoEntrega15Posicoes; this.Codigo = "I"; this.Tipo = "S"; this.Descricao = "Sem registro, com emisso e entrega - 15 posies"; break; default: this.NumeroCarteira = 0; this.Codigo = " "; this.Tipo = " "; this.Descricao = "( Selecione )"; break; } } catch (Exception ex) { throw new Exception("Erro ao carregar objeto", ex); } } public static Carteiras CarregaTodas() { try { Carteiras alCarteiras = new Carteiras(); Carteira_Itau obj; obj = new Carteira_Itau((int)EnumCarteiras_Itau.EscritualEletronicaSimples); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.EscritualEletronicaSimplesNossoNumeroLivre); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.EscritualEletronicaCarne); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.EscritualEletronicaDolar); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.EscritualEletronicaCobrancaInteligente); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.DiretaEletronicaEmissaoIntegralCarne); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.DiretaEletronicaSemEmissaoSimples); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.DiretaEletronicaSemEmissaoDolar); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.DiretaEletronicaEmissaoParcialSimples); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.DiretaEletronicaEmissaoInegralSimples); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroSemEmissaoComProtestoEletronico); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroSemEmissao15Digitos); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroSemEmissao15DigitosIOF4); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroSemEmissao15DigitosIOF7); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoParcialComProtestoBordero); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoParcialComProtestoEletronico); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF2); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF4); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoParcialSegurosIOF7); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoIntegral); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoIntegralCarne); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoIntegral15PosicoesCarne); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoEntrega); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoEntregaCarne); alCarteiras.Add(obj); obj = new Carteira_Itau((int)EnumCarteiras_Itau.SemRegistroEmissaoEntrega15Posicoes); alCarteiras.Add(obj); return alCarteiras; } catch (Exception ex) { throw new Exception("Erro ao listar objetos", ex); } } #endregion } }
Shell
UTF-8
1,296
3.21875
3
[ "BSD-3-Clause" ]
permissive
#!/bin/bash # Copyright 2019 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # To check for violations: # $ ./tools/clippy # # To fix violations where possible: # $ ./tools/clippy --fix set -e cd "$(dirname $0)/.." # TODO(b/192373803): Clean up clippy error is the following crates EXCLUDE=( aarch64 # 16 errors crosvm-fuzz # 7 errors devices # 92 errors disk # 36 errors kvm # 641 errors kvm_sys # 613 errors libvda # 79 errors net_sys # 3 errors virtio_sys # 9 errors x86_64 # 56 errors ) EXCLUDE_COMMON=( common/cros_async # 8 errors ) # Note: Clippy checks are configured in .cargo/config.toml echo "Clippy crosvm workspace" cargo clippy \ --workspace \ --features all-linux \ --all-targets \ ${EXCLUDE[@]/#/--exclude } \ "$@" -- -Dwarnings for crate in common/*; do if [ -d "${crate}" ] && [[ ! " ${EXCLUDE_COMMON[*]} " =~ " ${crate} " ]]; then echo "" echo "Clippy ${crate}" (cd "${crate}" && \ cargo clippy --all-targets --all-features "$@" -- -Dwarnings) fi done
Python
UTF-8
150
2.859375
3
[]
no_license
n = int(input()) a = list(map(int, input().split(" "))) kisuu = 1 kake = 1 for i in a: kake *= 3 if i % 2 == 0: kisuu *= 2 print(kake - kisuu)
C++
UTF-8
1,525
2.9375
3
[ "MIT" ]
permissive
// Water Drop FX for Neopixel Strips // This is the water drop effect written in C and included in an Arduino script. // Notes: This won't run on a ATTiny85 for over 50 pixels (it runs out of memory as each pixel takes 3 bytes). // Include the Adafruit NeoPixel Library #include <Adafruit_NeoPixel.h> // Include the waterdrop torture C++ lib #include "water_torture.h" // Define the Arduino pin that will send data to the strip. #define PIN 6 // Specify the number of LEDs/Pixels we will be controlling. #define NUM_LEDS 100 // Create an Adafruit Neopixel strip object as a global variable. Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800); // Initialise a Water torture object variable WaterTorture water_torture = WaterTorture(&strip); // Global Vars for Drip/cycle fucntions long lastTime = 0; void setup() { // Required function for Neopixel Library. strip.begin(); // Initialize all pixels to 'off' strip.show(); } void loop() { //Call Drip function Drip(); } void Drip() { // Specify a boolean indicating if you want to reverse the drip animation (ie. run from end of strip to begining) bool reverseAnimation = true; MODE_WATER_TORTURE: if (cycle()) { strip.setBrightness(255); water_torture.animate(reverseAnimation); strip.show(); } } bool cycle() { int cycleMillis = 20; if (millis() - lastTime >= cycleMillis) { lastTime = millis(); return true; } return false; }
C++
UTF-8
2,546
3.34375
3
[]
no_license
#pragma once #include "vector.hpp" namespace math { template <typename T, std::size_t COLS, std::size_t ROWS> class base_matrix { public: constexpr static std::size_t columns() { return COLS; } constexpr static std::size_t rows() { return ROWS; } constexpr static base_matrix<T, COLS, ROWS> uniform_scale(const T & scale) { return generate_matrix(scale, std::make_index_sequence<ROWS>()); } constexpr static base_matrix<T, COLS, ROWS> identity() { return uniform_scale(1); } constexpr static base_matrix<T, COLS, ROWS> zero() { return uniform_scale(0); } // Constructs identity matrix //base_matrix() //{ // for (std::size_t j = 0; j < ROWS; j++) // { // iterate<0, COLS - 1>([&](std::size_t i) // { // m_rows[j][i] = i == j ? T(1) : T(0); // }); // } //} template <typename TFirst, typename... TRows/*, class = std::enable_if_t<sizeof...(TRows) == ROWS>*/> constexpr base_matrix(TFirst && first, TRows &&... rows) : m_rows{ std::forward<TFirst>(first), std::forward<TRows>(rows)... } { } template<typename TOther> constexpr base_matrix(const base_matrix<TOther, COLS, ROWS> & other) : base_matrix(internal_tag(), other, std::make_index_sequence<ROWS>()) { } vector<T, COLS> & operator[](std::size_t index) { return m_rows[index]; } constexpr const vector<T, COLS> & operator[](std::size_t index) const { return m_rows[index]; } constexpr vector<T, ROWS> get_column(std::size_t index) const { return get_column(index, std::make_index_sequence<ROWS>()); } private: vector<T, COLS> m_rows[ROWS]; struct internal_tag {}; template<typename TOther, std::size_t... Indices> constexpr base_matrix(internal_tag, const base_matrix<TOther, COLS, ROWS> & other, std::index_sequence<Indices...>) : m_rows{ other[Indices]... } { } template<std::size_t... Indices> constexpr static base_matrix<T, COLS, ROWS> generate_matrix(const T & value, std::index_sequence<Indices...>) { return base_matrix<T, COLS, ROWS>(generate_row(Indices, value, std::make_index_sequence<COLS>())...); } template<std::size_t... Indices> constexpr static vector<T, COLS> generate_row(std::size_t position, const T & value, std::index_sequence<Indices...>) { return vector<T, COLS>((Indices == position ? value : T(0))...); } template<std::size_t... RowIndices> constexpr vector<T, ROWS> get_column(std::size_t index, std::index_sequence<RowIndices...>) const { return vector<T, ROWS>{ m_rows[RowIndices][index]... }; } }; }
C#
UTF-8
1,390
3.140625
3
[]
no_license
using System.IO; namespace RawParserUWP.Model.Format.Reader { class MemoryBufferedStream : BinaryReader { byte[] _buffer; long _bufferSize; long _bufferPosition; public MemoryBufferedStream(Stream s, long b) : base(s) { _bufferSize = b; _buffer = new byte[b]; _bufferPosition = s.Position; ReadBlock(); } public override byte ReadByte() { //Si dans buffer, return from buffer if (BaseStream.Position < (_bufferPosition + _buffer.Length) && BaseStream.Position > _bufferPosition) { return _buffer[BaseStream.Position++ - _bufferPosition]; } else { return _buffer[BaseStream.Position++ - _bufferPosition]; } } private void ReadBlock() { //else read new block _bufferPosition = BaseStream.Position; if (_buffer.Length > BaseStream.Length) { _buffer = new byte[BaseStream.Length - BaseStream.Position]; BaseStream.Read(_buffer, (int)BaseStream.Position, _buffer.Length); } else { BaseStream.Read(_buffer, (int)BaseStream.Position, _buffer.Length); } } } }
JavaScript
UTF-8
3,916
3.40625
3
[]
no_license
var input = document.getElementById('input'); var question_list = Array(); var idx_list = Array(); const previous_btn = document.querySelector('.previous-btn'); const next_btn = document.querySelector('.next-btn'); const question = document.querySelector('.questions'); const second = document.querySelector('.second'); // when excel file is uploaded input.addEventListener('change', function(){ readXlsxFile(input.files[0]).then(function(data){ data.forEach(function(elements){ question_list.push(elements[0]); }) }).then(function(){ var i; for(i = 0; i < question_list.length; i++) { idx_list.push(Math.floor(Math.random() * question_list.length)); } question.innerHTML = "Go!"; }); }); // clicked functions function left_clicked(){ if(question_list.length != 0) { question.innerHTML = question_list[idx_list[idx]]; idx = idx - 1; if(idx < 0) idx = question_list.length - 1; } clearInterval(countdown); currentSecond = 0; countdown = setInterval(countdownSecond, 1000); } function right_clicked(){ if(question_list.length != 0){ question.innerHTML = question_list[idx_list[idx]]; idx = (idx + 1) % question_list.length; } clearInterval(countdown); currentSecond = 0; countdown = setInterval(countdownSecond, 1000); } // buttons clicked var idx = 0; previous_btn.addEventListener('click', function(){ left_clicked(); }); next_btn.addEventListener('click', function(){ right_clicked(); }); let countdown = setInterval(countdownSecond, 1000); // second countdown var currentSecond = 0; function countdownSecond(){ second.innerHTML = String(currentSecond) + " sec"; currentSecond += 1; } // puase and stop button const pauseButton = document.querySelector('.pause-button'); const stopButton = document.querySelector('.stop-button'); const showButton = document.querySelector('.show-button'); function pause_clicked(){ if(pauseButton.classList.contains('play-button')) { clearInterval(countdown); pauseButton.classList.remove('play-button'); pauseButton.innerHTML = '<i class="fa fas fa-pause"></i>'; countdown = setInterval(countdownSecond, 1000); } else { clearInterval(countdown); pauseButton.innerHTML = '<i class="fa fas fa-play"></i>'; pauseButton.classList.add('play-button'); } } function stop_clicked(){ clearInterval(countdown); pauseButton.innerHTML = '<i class="fa fas fa-play"></i>'; currentSecond = 0; second.innerHTML = String(currentSecond) + " sec"; pauseButton.classList.add('.play-button'); } pauseButton.addEventListener('click', function(){ pause_clicked(); }); stopButton.addEventListener('click', function(){ stop_clicked(); }); // show button // visibility -> visible / hidden // display -> hidden / block function show_clicked(){ if(showButton.classList.contains('showing')) { console.log("showing clicked"); showButton.classList.remove('showing'); second.style.visibility = "hidden"; } else { console.log("not showing clicked"); showButton.classList.add('showing'); second.style.visibility = "visible"; } } showButton.addEventListener('click', function(){ show_clicked(); }); // keyboard interrupt window.addEventListener('keydown', function(event){ if (event.defaultPrevented){ return; // Do nothing if the event was already processed! } switch(event.key){ case "ArrowLeft": left_clicked(); break; case "ArrowRight": right_clicked(); break; case " ": pause_clicked(); break; case "t": show_clicked(); break; default: return; } })
Java
UTF-8
3,256
2.34375
2
[]
no_license
package com.skilldistillery.caravan.controllers; import java.security.Principal; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.skilldistillery.caravan.entities.Address; import com.skilldistillery.caravan.entities.AdventureCalendar; import com.skilldistillery.caravan.services.AdventureCalendarService; @RestController @RequestMapping("api") @CrossOrigin({ "*", "http://localhost:4260" }) public class AdventureCalendarController { @Autowired private AdventureCalendarService svc; @GetMapping("adventure-calendars") public List<AdventureCalendar> index(Principal principal) { return svc.index(principal.getName()); } @GetMapping("adventure-calendars/{cid}") public AdventureCalendar showAdventureCalendar(@PathVariable int cid, HttpServletRequest request, HttpServletResponse response) { AdventureCalendar adventureCalendar = svc.findAdventureCalendarById(cid); if (adventureCalendar == null) { response.setStatus(404); } return adventureCalendar; } @PostMapping("adventures/{id}/adventure-calendars") public AdventureCalendar createAddress(@PathVariable int id, @RequestBody AdventureCalendar adventureCalendar, HttpServletRequest request, HttpServletResponse response) { if ((adventureCalendar = svc.createAdventureCalendar(id, adventureCalendar)) != null) { response.setStatus(201); StringBuffer url = request.getRequestURL(); url.append("/").append(adventureCalendar.getId()); response.addHeader("Location", url.toString()); return adventureCalendar; } else { response.setStatus(400); return null; } } @PutMapping("adventure-calendars/{cid}") public AdventureCalendar updateAdventureCalendar(@PathVariable int cid, @RequestBody AdventureCalendar adventureCalendar, HttpServletRequest request, HttpServletResponse response) { try { adventureCalendar = svc.updateAdventureCalendar(cid, adventureCalendar); if (adventureCalendar == null) { response.setStatus(404); } } catch (Exception e) { e.printStackTrace(); response.setStatus(400); adventureCalendar = null; } return adventureCalendar; } @DeleteMapping("adventure-calendars/{cid}") public boolean deleteAdventureCalendar(@PathVariable int cid, HttpServletRequest request, HttpServletResponse response) { try { boolean deleted = svc.deleteAdventureCalendarById(cid); if (deleted) { response.setStatus(204); return true; } else { response.setStatus(404); return false; } } catch (Exception e) { e.printStackTrace(); response.setStatus(400); return false; } } }
Python
UTF-8
1,405
3.140625
3
[]
no_license
# """ # Author: Michael Gardner # Date: 12/15/16 # Advent of Code # adventofcode.com # problem 1 # """ import hashlib def md5(string): m= hashlib.md5(string).hexdigest() #print m return m class comparer(object): ''' remembers self.n __call__() allows the class instance to be called as a function ''' def __init__(self, n=3): self.n = n def __call__(self, l): if len(l) < self.n: return -1 for i in range(len(l)-self.n+1): comp = set() for j in range(self.n): comp.add(l[i+j]) if len(comp) == 1: return comp.pop() return False if __name__ == "__main__": i3 = 0 i5 = 0 l3 = "" l5 = "" keycount = 0 salt = "ihaygndm" test3 = comparer(3) test5 = comparer(5) alreadytested = dict() while keycount < 64: maybe = md5(salt+str(i3)) l3 = test3(maybe) if l3 != False and l3 != -1: #print maybe, i3, i5 = i3+1 while i5 - i3 < 1000: maybe2 = md5(salt+str(i5)) l5 = test5(maybe2) if l5 != False and l5 != -1 and l5 == l3: keycount += 1 print keycount print maybe, i3, maybe2, i5 break i5 += 1 #print i3 += 1
Markdown
UTF-8
16,672
2.5625
3
[]
no_license
# Zookeeper学习 参考: [几句话了解Zookeeper工作原理](https://mp.weixin.qq.com/s?__biz=MzI0MDQ4MTM5NQ==&mid=2247486974&idx=1&sn=4fac86401700b11970a194cbd5ccaabb&chksm=e91b68e2de6ce1f4e5c29bdcd1a026563c5dcd6b1f36cee4ec1b0c3e045ece81925e53a465a1&scene=0#rd) [ZooKeeper概念](https://mp.weixin.qq.com/s?__biz=MjM5ODI5Njc2MA==&mid=2655818907&idx=1&sn=990fb18f67f57672d5a5824455bc677b&chksm=bd74d94c8a03505af967fb8b2d59de9055b7b86ec7f5f114d2333f24a2642c014d0e4830cf43&mpshare=1&scene=24&srcid=0911N6oe8Dnn817zDaVUXfmj#rd) ## 概述 ZooKeeper是一种分布式协调服务,用于管理大型主机 分布式应用的优点: - **可靠性** - 单个或几个系统的故障不会使整个系统出现故障。 - **可扩展性** - 可以在需要时增加性能,通过添加更多机器,在应用程序配置中进行微小的更改,而不会有停机时间。 - **透明性** - 隐藏系统的复杂性,并将其显示为单个实体/应用程序。 > Apache ZooKeeper是由集群(节点组)使用的一种服务,用于在自身之间协调,并通过稳健的同步技术维护共享数据。ZooKeeper本身是一个分布式应用程序,为写入分布式应用程序提供服务。 Zookeeper提供的常见服务: - **命名服务** - 按名称标识集群中的节点。它类似于DNS,但仅对于节点。 - **配置管理** - 加入节点的最近的和最新的系统配置信息。 - **集群管理** - 实时地在集群和节点状态中加入/离开节点。 - **选举算法** - 选举一个节点作为协调目的的leader。 - **锁定和同步服务** - 在修改数据的同时锁定数据。此机制可帮助你在连接其他分布式应用程序(如Apache HBase)时进行自动故障恢复。 - **高度可靠的数据注册表** - 即使在一个或几个节点关闭时也可以获得数据。 > Zookeeper的好处: > > - **简单的分布式协调过程** > - **同步** - 服务器进程之间的相互排斥和协作。此过程有助于Apache HBase进行配置管理。 > - **有序的消息** > - **序列化** - 根据特定规则对数据进行编码。确保应用程序运行一致。这种方法可以在MapReduce中用来协调队列以执行运行的线程。 > - **可靠性** > - **原子性** - 数据转移完全成功或完全失败,但没有事务是部分的。 ## 基础知识 ### ZooKeeper的架构Architecture ![架构图](https://7n.w3cschool.cn/attachments/day_161229/201612291344222238.jpg) | 组件 | 说明 | | :---------: | :--------------------------------------: | | Client(客户端) | 客户端,我们的分布式应用集群的一个节点,从服务器访问信息。对于特定的时间间隔,每个客户端向服务器发送消息以使服务器知道客户端是活跃的。 类似的,当客户端连接时,服务器发送确认码。如果连接的服务器没有响应,客户端会自动将消息重定向到另一个服务器 | | Server(服务器) | 服务器,我们的Zookeeper总体中的一个节点,为客户端提供所有的服务。向客户端发送确认码以告知服务器是活跃的 | | Ensemble | Zookeeper服务器组。形成ensemble所需的最小节点数为3 | | Leader | 服务器节点。如果任何连接的节点失败,则执行自动恢复。Leader在服务启动时被选举 | | Follower | 跟随leader指令的服务器节点 | ### 层次命名空间Hierarchical namespace 用于内存表示的ZooKeeper文件系统的树结构。ZooKeeper节点称为** znode **。每个znode由一个名称标识,并用路径(/)序列分隔。 ![](https://7n.w3cschool.cn/attachments/day_161229/201612291345162031.jpg) - 在图中,首先有一个由“/”分隔的znode。在根目录下,你有两个逻辑命名空间** config **和** workers **。 - **config **命名空间用于集中式配置管理,**workers **命名空间用于命名。 - 在config 命名空间下,每个znode最多可存储1MB的数据。这与UNIX文件系统相类似,除了父znode也可以存储数据。这种结构的主要目的是存储同步数据并描述znode的元数据。此结构称为 ZooKeeper数据模型。 ZooKeeper数据模型中的每个znode都维护着一个stat **结构。一个stat仅提供一个znode的**元数据。它由版本号,操作控制列表(ACL),时间戳和数据长度组成。 - **版本号** - 每个znode都有版本号,这意味着每当与znode相关联的数据发生变化时,其对应的版本号也会增加。当多个zookeeper客户端尝试在同一znode上执行操作时,版本号的使用就很重要。 - **操作控制列表(ACL)** - ACL基本上是访问znode的认证机制。它管理所有znode读取和写入操作。 - **时间戳** - 时间戳表示创建和修改znode所经过的时间。它通常以毫秒为单位。ZooKeeper从“事务ID"(zxid)标识znode的每个更改。**Zxid **是唯一的,并且为每个事务保留时间,以便你可以轻松地确定从一个请求到另一个请求所经过的时间。 - **数据长度** - 存储在znode中的数据总量是数据长度。你最多可以存储1MB的数据。 #### Znode的类型 Znode被分为持久(persistent)节点,顺序(sequential)节点和临时(ephemeral)节点。 - **持久节点 ** - 即使在创建该特定znode的客户端断开连接后,持久节点仍然存在。默认情况下,除非另有说明,否则所有znode都是持久的。 - **临时节点 **- 客户端活跃时,临时节点就是有效的。当客户端与ZooKeeper集合断开连接时,临时节点会自动删除。因此,只有临时节点不允许有子节点。如果临时节点被删除,则下一个合适的节点将填充其位置。临时节点在leader选举中起着重要作用。 - **顺序节点 **- 顺序节点可以是持久的或临时的。当一个新的znode被创建为一个顺序节点时,ZooKeeper通过将10位的序列号附加到原始名称来设置znode的路径。例如,如果将具有路径 /myapp 的znode创建为顺序节点,则ZooKeeper会将路径更改为 /myapp0000000001 ,并将下一个序列号设置为0000000002。如果两个顺序节点是同时创建的,那么ZooKeeper不会对每个znode使用相同的数字。顺序节点在锁定和同步中起重要作用。 ### Sessions(会话) 会话对于ZooKeeper的操作非常重要。会话中的请求按FIFO顺序执行。一旦客户端连接到服务器,将建立会话并向客户端分配**会话ID **。 客户端以特定的时间间隔发送**心跳**以保持会话有效。如果ZooKeeper集合在超过服务器开启时指定的期间(会话超时)都没有从客户端接收到心跳,则它会判定客户端死机。 会话超时通常以毫秒为单位。当会话由于任何原因结束时,在该会话期间创建的临时节点也会被删除。 ### Watches(监视) 监视是一种简单的机制,使客户端收到关于ZooKeeper集合中的更改的通知。客户端可以在读取特定znode时设置Watches。Watches会向注册的客户端发送任何znode(客户端注册表)更改的通知。 Znode更改是与znode相关的数据的修改或znode的子项中的更改。只触发一次watches。如果客户端想要再次通知,则必须通过另一个读取操作来完成。当连接会话过期时,客户端将与服务器断开连接,相关的watches也将被删除。 ## Zookeeper工作流 一旦ZooKeeper集合启动,它将等待客户端连接。客户端将连接到ZooKeeper集合中的一个节点。它可以是leader或follower节点。一旦客户端被连接,节点将向特定客户端分配会话ID并向该客户端发送确认。如果客户端没有收到确认,它将尝试连接ZooKeeper集合中的另一个节点。 一旦连接到节点,客户端将以有规律的间隔向节点发送心跳,以确保连接不会丢失。 - **如果客户端想要读取特定的znode,**它将会向具有znode路径的节点发送**读取请求**,并且节点通过从其自己的数据库获取来返回所请求的znode。为此,在ZooKeeper集合中读取速度很快。 - **如果客户端想要将数据存储在ZooKeeper集合中**,则会将znode路径和数据发送到服务器。连接的服务器将该请求转发给leader,然后leader将向所有的follower重新发出写入请求。如果只有大部分节点成功响应,而写入请求成功,则成功返回代码将被发送到客户端。 否则,写入请求失败。绝大多数节点被称为Quorum。 > 在ZooKeeper集合中拥有不同数量的节点的效果。 > > - 如果我们有**单个节点**,则当该节点故障时,ZooKeeper集合将故障。它有助于“单点故障",不建议在生产环境中使用。 > - 如果我们有**两个节点**而一个节点故障,我们没有占多数,因为两个中的一个不是多数。 > - 如果我们有**三个节点**而一个节点故障,那么我们有大多数,因此,这是最低要求。ZooKeeper集合在实际生产环境中必须至少有三个节点。 > - 如果我们有**四个节点**而两个节点故障,它将再次故障。类似于有三个节点,额外节点不用于任何目的,因此,最好添加奇数的节点,例如3,5,7。 > > 我们知道写入过程比ZooKeeper集合中的读取过程要贵,因为所有节点都需要在数据库中写入相同的数据。因此,对于平衡的环境拥有较少数量(例如3,5,7)的节点比拥有大量的节点要好。 ![](https://7n.w3cschool.cn/attachments/image/20161229/1482990578752713.png) | 组件 | 描述 | | :------------------------- | :--------------------------------------- | | 写入(write) | 写入过程由leader节点处理。leader将写入请求转发到所有的znode,并等待咋弄的的回复,如果一半的咋弄的回复,则写入过程完成。 | | 读取(read) | 读取由特定连接的咋弄的在内部执行,因此不需要与集群进行交互 | | 复制数据库(replocated database) | 它用于在zookeeper中存储数据。每个znode都有自己的数据库,每个znode在一致性的帮助下每次都有相同的数据。 | | Leader | Leader是负责处理写入请求的Znode | | Follower | follower从客户端接受写入请求,并将它们转发到leader znode | | 请求处理器(request processor) | 只存在于leader节点,它管理来自follower节点的写入请求 | | 原子广播(atomic broadcasts) | 负责广播从leader节点到follower节点的变化 | ## Zookeeper leader选举 考虑一个集群中有N个节点。leader选举的过程如下: - 所有节点创建具有相同路径 /app/leader_election/guid_ 的顺序、临时节点。 - ZooKeeper集合将附加10位序列号到路径,创建的znode将是 /app/leader_election/guid_0000000001,/app/leader_election/guid_0000000002等。 - 对于给定的实例,在znode中创建最小数字的节点成为leader,而所有其他节点是follower。 - 每个follower节点监视下一个具有最小数字的znode。例如,创建znode/app/leader_election/guid_0000000008的节点将监视znode/app/leader_election/guid_0000000007,创建znode/app/leader_election/guid_0000000007的节点将监视znode/app/leader_election/guid_0000000006。 - 如果leader关闭,则其相应的znode/app/leader_electionN会被删除。 - 下一个在线follower节点将通过监视器获得关于leader移除的通知。 - 下一个在线follower节点将检查是否存在其他具有最小数字的znode。如果没有,那么它将承担leader的角色。否则,它找到的创建具有最小数字的znode的节点将作为leader。 - 类似地,所有其他follower节点选举创建具有最小数字的znode的节点作为leader。 --- ​:question: 简述leader的选举过程 首先服务器将自身状态转换为looking,并向集群中所有的服务器发起投票(myid,zxid) 接收其他服务器发送的投票,并进行处理,按照zxid最大的作为leader,如果相同按照myid最大的作为leader,更新投票信息,再次向集群发送投票。 统计投票结果,超过半数以上的投票即为leader 如果leader是自己,就把自己的状态变更为leading,否则变为follower ​:question: zk 的选举机制 (1)旧Leader宕机后,选举新Leader中,旧的Leader重启后不可能再次成为这次选举的新Leader。 (2)旧Leader宕机后,在剩下的Follower服务器选取新Leader的标准,一定是事务ID最大的那个Follower成为新Leader。(即数据同步最新的那台Follower服务器) (3)事务ID(ZXID)是64位的数字。其中低32位可以靠做是一个简单的单调递增的计数器,高32位则代表一个Leader从生到死的epoch编号。 (4)新Leader选举出来,从事务proposal中分析出旧Leader的epoch编号,并递增1,作为新的事务ID的高32位,然后新事务ID的低32位从0位重新开始计数。 (5)新Leader通过事务ID和所有的Follower机器上的事务ID进行对比,确保数据同步。保证数据在所有的Follower上与之达成同步。旧Leader上新被提出的事务被抛弃。当数据达到同步,才将Follower服务器加入可用的Follower服务器列表。然后开始消息广播。 :question:选举状态 - LOOKING,竞选状态。 - FOLLOWING,随从状态,同步leader状态,参与投票。 - OBSERVING,观察状态,同步leader状态,不参与投票。 - LEADING,领导者状态。 :question:选举消息内容 在投票完成后,需要将投票信息发送给集群中的所有服务器,它包含以下内容: - 服务器ID - 数据ID - 逻辑时钟 - 选举状态 ​:question: 选举流程图 ![](https://static.oschina.net/uploads/space/2017/0404/144149_n7KA_1866807.png) #### ZooKeeper为何要求分布式集群至少有3个节点 在zookeeper的选举过程中,为了保证选举过程最后能选出leader,就一定不能出现两台机器得票相同的僵局,所以一般的,要求zk集群的server数量一定要是奇数,也就是2n+1台,并且,如果集群出现问题,其中存活的机器必须大于n+1台,否则leader无法获得多数server的支持,系统就自动挂掉。所以一般是3个或者3个以上节点。 ## Zookeeper的算法 zk的核心算法为ZAB(原子消息广播协议),与Paxos不同,这是一种特别为zk设计的崩溃可恢复的原子消息广播算法 > **ZAB核心** :所有事务请求必须由一个全局唯一的服务器来协调处理,这样的服务器称为Leader服务器,而余下的其他服务器则成为Follower服务器。Leader服务器负责将一个客户端事务请求转换成一个事务Proposal(提议),并将该Proposal分发给集群中所有的Follower服务器。之后Leader服务器需要等待所有Follower服务器的反馈,一旦超过半数的Follower服务器进行了正确反馈后,那么Leader就会再次向所有的Follower服务器分发Commit消息,要求其将前一个Proposal进行提交 zab协议包括两个基本模式:消息广播以及崩溃恢复 ### 消息广播 ZAB协议的消息广播过程使用的是一个原子广播协议,类似于一个二阶段提交的过程。针对客户端的事务请求,Leader服务器会为其生成对应的事务Proposal,并将其发送给集群中其余所有的机器,然后再分别手机各自的选票,最后进行事务提交。 ### 奔溃恢复 一旦Leader服务器出现崩溃,或者由于网络原因导致Leader服务器失去了过半Follower的联系,那么就会进入崩溃恢复模式,并且恢复后需要一个新的leader,因此zab协议需要一个高效的选举方案 ## zookeeper安装 ### windows下安装 [安装教程](https://blog.csdn.net/yzy199391/article/details/80605195) ### linux下安装zookeeper集群 [安装教程](https://blog.csdn.net/qiushisoftware/article/details/79043379) ### 客户端连接zk集群 客户单连接zk集群时,url必须包含所有有效zk实例的ip+port. [java连接zookeeper集群](https://blog.csdn.net/wuhenzhangxing/article/details/52936271)
Java
UTF-8
1,578
1.929688
2
[]
no_license
package org.mediawiki.pages; import org.mediawiki.utilities.Driver; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class MediaWikiMainPageDiscussionPage { private WebDriver driver; public MediaWikiMainPageDiscussionPage() { this.driver=Driver.getDriver(); PageFactory.initElements(driver, this); } @FindBy(linkText="Edit") public WebElement Edit; @FindBy(id="TechNinja.27s_How_to_become_a_SDET") public WebElement DTopic; public WebElement isLinkDisplayed(String name) { return driver.findElement(By.linkText(name)); } public boolean isClickable(String el){ try{ WebDriverWait wait = new WebDriverWait(driver, 3); wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.linkText(el)))); return true; } catch (Exception e){ return false ; } } public boolean isAtDiscussionPage() { return driver.getTitle().equals("Talk:Main Page - Cybertek's Wiki!"); } //mainpage edit page down here: @FindBy(id="mw-editbutton-headline") public WebElement Dheadline; @FindBy(id="mw-editbutton-link") public WebElement internalLink; public boolean isAtDiscussionEditPage() { return driver.getTitle().equals("Editing Talk:Main Page - Cybertek's Wiki!"); } }
Python
UTF-8
2,651
2.671875
3
[]
no_license
# coding = utf-8 """ 云教学教师端布置作业功能 作者:郭伟伟 日期:20191112 """ from selenium import webdriver import time browser = webdriver.Firefox() browser.get("http://hd.ruizhiedu.com:8888/pallasa_cloudteach/teacher/index/index") browser.maximize_window() # 将浏览器最大化显示 browser.find_element_by_id("username").send_keys("01019992gww") # 云教学教师web端输入用户名 browser.find_element_by_id("password").send_keys("123456") # 云教学教师web端输入密码 browser.find_element_by_xpath("/html/body/div/div[1]/div[2]/div[2]/form/div[4]/button").click() # 点击登录按钮 time.sleep(3) browser.find_element_by_xpath("/html/body/div[1]/div[3]/div[2]/div[2]/div[4]/div[3]").click() # 点击布置作业按钮 time.sleep(1) # 添加学生按钮 browser.find_element_by_xpath("/html/body/div[4]/div/div[1]/div[4]/div[2]/div[2]/div[2]/div/div/div").click() # 选择班级 browser.find_element_by_xpath("/html/body/div[8]/div/div/div[2]/div[1]/div/div[1]/div[1]/div[1]/div[2]/ul" "/li[4]/div[1]").click() time.sleep(1) # 点击确认按钮 browser.find_element_by_xpath("/html/body/div[8]/div/div/div[2]/div[2]/button[1]").click() time.sleep(1) # 点击添加题目按钮 browser.find_element_by_xpath("/html/body/div[4]/div/div[1]/div[4]/div[2]/div[2]/div[1]/div[3]/div/div").click() # 点击我的题库 browser.find_element_by_xpath("/html/body/div[4]/div/div[1]/div[4]/div[2]/div[2]/div[5]/div[1]/button[1]").click() time.sleep(2) # 点击添加题库 browser.find_element_by_xpath("/html/body/div[8]/div/div/div[2]/div/div/div[2]/div[2]/div/div/" "table/tbody/tr[1]/td[6]/a[2]").click() time.sleep(2) # 点击关闭弹框 browser.find_element_by_xpath("/html/body/div[8]/div/div/div[1]/button/span").click() time.sleep(1) # 输入作业名称 browser.find_element_by_xpath('//*[@id="homeworkName"]').send_keys("20191112新建作业") # 发送时间选择 browser.find_element_by_xpath('//*[@id="sendTime"]').send_keys("2019/11/12 14:00") # 截止时间选择 browser.find_element_by_xpath('//*[@id="endTime"]').send_keys("2019/11/30 14:00") # 限时时间长 browser.find_element_by_xpath('//*[@id="hw_limitminutes"]').send_keys("60") # 备注信息输入 browser.find_element_by_xpath('//*[@id="remark"]').send_keys("把握时间及时完成,批改后返还答案") time.sleep(3) # 查看老师批改情况 browser.find_element_by_xpath('//*[@id="returnremark"]').click() # 点击发送作业 browser.find_element_by_xpath("/html/body/div[4]/div/div[1]/div[4]/div[1]/table/tbody/tr[13]/td/div/a[1]").click()