language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
1,646
2.703125
3
[]
no_license
import * as ActionConstants from '../actiontypes/quotes' const initialState = { isLoading : true, quotes: [] } const reducer = (state = initialState , action) => { switch (action.type) { case ActionConstants.START_LOADING: return {...state, isLoading: true} case ActionConstants.END_LOADING: return {...state, isLoading: false} case ActionConstants.FETCH_QUOTES: return {...state , quotes : action.payload.data, currentPage: action.payload.currentPage, numberOfPages: action.payload.numberOfPages} case ActionConstants.FETCH_QUOTE: return {...state , quote : action.payload} case ActionConstants.FETCH_QUOTES_BY_SEARCH: return {...state, quotes: action.payload} case ActionConstants.CREATE_QUOTES: return {...state, quotes: [...state.quotes , action.payload]} case ActionConstants.DELETE_QUOTES: return {...state , quotes : state.quotes.filter( (state) => state._id !== action.payload )} case ActionConstants.UPDATE_QUOTES: return {...state, quotes : state.quotes.map( state => state._id === action.payload._id ? action.payload : state)} case ActionConstants.COMMENT_QUOTE: return { ...state, quotes : state.quotes.map( quote => { if(quote._id === action.payload._id){ return action.payload } return quote }) } default: return state } } export default reducer
Python
UTF-8
1,319
3.9375
4
[]
no_license
import random n = int(input("Вкажіть довжину списку \n ")) lst = random.sample(range(1, 100), n) print("Input list: {}".format(lst)) def split(l, start, end): """ Splits list into two parts. Splits list into two parts each element of first part are not bigger then every element of last part. """ i = start - 1 splitter = l[end] for j in range(start, end): if l[j] <= splitter: i += 1 l[i], l[j] = l[j], l[i] l[i+1], l[end] = l[end], l[i+1] return i+1 def quick_sort(l, start, end): """ Sorts list of items using quick sort algorithm. This is iterative implementation of quick sort algorithm. """ stack = [] stack.append(start) stack.append(end) while stack: end = stack.pop() start = stack.pop() s = split(l, start, end) if s-1 > start: stack.append(start) stack.append(s - 1) if s+1 < end: stack.append(s + 1) stack.append(end) quick_sort(lst, 0, len(lst) - 1) print("Output list: {}".format(lst)) number = int(input("Введіть число для якого треба знайти найближчу пару \n ")) max = 0 for i in range(0, n - 1): j = i + 1 while j < n: sum = lst[i] + lst[j] if sum <= number and sum > max: max = sum max_i = i max_j = j j += 1 i += 1 print(max, lst[max_i], lst[max_j])
C++
UTF-8
3,725
3.171875
3
[]
no_license
#ifndef __JJC__INFO__HPP__ #define __JJC__INFO__HPP__ #include <string> #include <iostream> #include "MathToolbox.hpp" #define COUT std::cout #define F_PTR(s) ((unsigned long)s) const std::string std_ops[] = {"__Mean", "__Max", "__Min", "__Median", "__Range", "__Magnitude", "__Sum", "__Product", "__Clamp", "__Shuffle", "__Sort"}; static void Info_StdOps(const std::string& str); void PrintInfo(const std::string& str) { for(auto& ops: std_ops) { if(str == ops) { Info_StdOps(str); return; } } std::cout << str << " does not have an info entry... sorry" << std::endl; } void PrintInfo(unsigned long f_ptr) { if(f_ptr == F_PTR(__Mean)) PrintInfo("__Mean"); else if(f_ptr == F_PTR(__Max)) PrintInfo("__Max"); else if(f_ptr == F_PTR(__Min)) PrintInfo("__Min"); else if(f_ptr == F_PTR(__Median)) PrintInfo("__Median"); else if(f_ptr == F_PTR(__Range)) PrintInfo("__Range"); else if(f_ptr == F_PTR(__Magnitude)) PrintInfo("__Magnitude"); else if(f_ptr == F_PTR(__Sum)) PrintInfo("__Sum"); else if(f_ptr == F_PTR(__Product)) PrintInfo("__Product"); else if(f_ptr == F_PTR(__Clamp)) PrintInfo("__Clamp"); else if(f_ptr == F_PTR(__Shuffle)) PrintInfo("__Shuffle"); else if(f_ptr == F_PTR(__Sort)) PrintInfo("__Sort"); } void Info_StdOps(const std::string& str){ std::cout << str << std::endl; if(str == "__Mean") { std::cout << " Prints the average\n"; std::cout << " arguments:\n"; std::cout << " 1) data vector to find the average of\n\n"; return; } else if(str == "__Max") { std::cout << " Find the largest element\n"; COUT << " arguments:\n"; COUT << " 1) data vector to search through for largest element\n\n"; return; } else if(str == "__Min") { COUT << " Find the smallest element\n"; COUT << " arguments:\n"; COUT << " 1) data vector to search through for smallest element\n\n"; return; } else if(str == "__Median") { COUT << " Find the median element\n"; COUT << " arguments:\n"; COUT << " 1) data vector to search through for median value\n\n"; return; } else if(str == "__Range") { COUT << " Find the range of values\n"; COUT << " arguments:\n"; COUT << " 1) data vector to find the range of\n\n"; return; } else if(str == "__Magnitude") { COUT << " Make every negative value positive, just like absolute value for real numbers\n"; COUT << " arguments:\n"; COUT << " 1) data vector to operate on\n\n"; return; } else if(str == "__Sum") { COUT << " Find the sum of all elements\n"; COUT << " arguments:\n"; COUT << " 1) data vector to operate on\n\n"; return; } else if(str == "__Product") { COUT << " Find the product of all elements\n"; COUT << " arguments:\n"; COUT << " 1) data vector to operate on\n\n"; return; } else if(str == "__Clamp") { COUT << " Clamp every element between two extremes\n"; COUT << " arguments:\n"; COUT << " 1) data vector to operate on\n"; COUT << " 2) maximum value for data vector\n"; COUT << " 3) minimum value for data vector\n\n"; return; } else if(str == "__Shuffle") { COUT << " Randomize elements\n"; COUT << " arguments:\n"; COUT << " 1) data vector to operate on\n\n"; return; } else if(str == "__Sort") { COUT << " Sort elements in one of two ways\n"; COUT << " arguments:\n"; COUT << " 1) data vector to operate on\n"; COUT << " 2) sort method to use when sorting\n"; COUT << " a) SortMethod_Increasing: smallest element at the beginning\n"; COUT << " b) SortMethod_Decreasing: largest element at the beginning\n\n"; return; } std::cout << " THIS FUNCTION DOES NOT HAVE A DEFINITION\n"; } #endif // __JJC__INFO__HPP__
C++
UTF-8
4,655
2.546875
3
[]
no_license
#include <Console.h> #include <Process.h> #include <SPI.h> #include <RH_RF95.h> RH_RF95 rf95; char DeviceID[20]="\0"; //Storage DeviceID or Device identifier char lon[20]="\0"; //Storage longtitude char lat[20]="\0"; //Storage latitude char alt[20]="\0"; //Storage altitude char tem[20]="\0"; //Storage tempreture char hum[20]="\0"; //Storage humidity char ppm[20]="\0"; //Storage CO2 air quality char pir[20]="\0"; //Storage pir char dst[20]="\0"; //Storage distance void getTimeStamp(); //LG01 will call the Linux "date" command and get the time stamp void receivepacket(); //Processing receive message and store it in the appropriate array void run_send_gps_data();//LG01 will call the Linux "send_gps_data.sh" command and write the GPS data in GPSWOX.com void setup() { Bridge.begin(115200); Console.begin(); while (!Console); if (!rf95.init()) {// Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on Console.println("Starting LoRa failed!"); while (1); } /* Set frequency is 868MHz,SF is 7,SB is 125KHz,CR is 4/5 and Tx power is 20dBm */ rf95.setFrequency(868); rf95.setSpreadingFactor(7); rf95.setSignalBandwidth(125E3); rf95.setCodingRate4(5); rf95.setTxPower(20,false); Console.println("Ready to receive!"); } void loop(){ receivepacket(); } void getTimeStamp() { Process time; // date is a command line utility to get the date and the time // in different formats depending on the additional parameter time.begin("date"); time.addParameter("+%D-%T"); // parameters: D for the complete date mm/dd/yy // T for the time hh:mm:ss time.run(); // run the command // read the output of the command while(time.available()>0) { char c = time.read(); Console.print(c); } } void run_send_gps_data() {//send_gps_data.sh -d DeviceID -l latitude -n longtitude -a altitude Process p; // Create a process and call it "p" p.begin("send_gps_data.sh"); p.addParameter("-d"); p.addParameter(DeviceID); p.addParameter("-l"); p.addParameter(lat); p.addParameter("-n"); p.addParameter(lon); p.addParameter("-a"); p.addParameter(alt); p.run(); // Run the process and wait for its termination } //Receiver LoRa packets and forward it void receivepacket() { if (rf95.available()) { // received a packet Console.print("Get new data: "); int i = 0,j=0,code[7]; int m1=0,m2=0,m3=0,m4=0,m5=0,m6=0,m7=0,m8=0; uint8_t buf[100]; char message[100]="\0"; uint8_t len = sizeof(buf); if (rf95.recv(buf, &len)){ Console.print((char*)buf); strcpy(message,(char *)buf); while(i<50) { if(message[i]==',') { code[j]=i; j++; } i++; } } for(int k=0;k<code[0];k++) { lon[m1]=message[k];//get longtitude m1++; } for(int k=code[0]+1;k<code[1];k++) { lat[m2]=message[k];//get latitude m2++; } for(int k=code[1]+1;k<code[2];k++) { alt[m3]=message[k];//get altitude m3++; } for(int k=code[2]+1;k<code[3];k++) { tem[m4]=message[k];//get tempreture m4++; } for(int k=code[3]+1;k<code[4];k++) { hum[m5]=message[k];//get humidity m5++; } for(int k=code[4]+1;k<code[5];k++) { ppm[m6]=message[k];//get CO2 m6++; } for(int k=code[5]+1;k<code[6];k++) { pir[m7]=message[k];//get PIR count m7++; } for(int k=code[6]+1;k<code[7];k++) { dst[m8]=message[k];//get garbage lvl m8++; } // run_send_gps_data(); Console.print(" with RSSI: "); Console.print(rf95.lastRssi(), DEC); Console.print(" ");getTimeStamp(); Console.print("the longtitude is " );Console.print(lon); Console.println(" deg"); Console.print("the latitude is ");Console.print(lat);Console.println(" deg"); Console.print("the altitude is ");Console.print(alt);Console.println(" deg"); Console.print("the tempreture is ");Console.print(tem);Console.println(" C"); Console.print("the humidity is ");Console.print(hum);Console.println("%"); Console.print("the CO2 presence is ");Console.print(ppm);Console.println(" ppm"); Console.print("the PIR count is ");Console.println(pir); Console.print("the garbage level is ");Console.print(dst);Console.println(" cm"); uint8_t data[] = "Gateway receive GPS data"; rf95.send(data, sizeof(data)); rf95.waitPacketSent(); } }
JavaScript
UTF-8
768
3.140625
3
[ "Apache-2.0" ]
permissive
"use strict" // api.openweathermap.org / data / 2.5 / weather ? q = { city name } & appid={ your api key } let city = prompt("Enter City ") const url = "http://api.openweathermap.org/data/2.5/weather?appid=20642b561dd890fd5884bff2116b23ec&q=" + city; $.ajax({ url: url, success: function (result) { console.log(result); console.log(result.name); $("#location").text(result.name); $("#sky").text(result.weather[0].description); let f = result.main.temp * (9 / 5) - 459.67; f = Math.round(f); let fahreneit = f.toString(); $("#temp").text(fahreneit); let mph = Math.round(result.wind.speed / .44704).toString(); $("#wind").text(mph); } })
PHP
UTF-8
2,750
2.75
3
[]
no_license
<?php require_once(__DIR__."/../core/ValidationException.php"); require_once(__DIR__."/../model/ActivitiesstatisticsMapper.php"); class Activitiesstatistics{ private $activityname; private $activityid; private $porcentajeMatriculados; private $matriculados; private $deportistas; private $asistentes; private $porcentajeAsistentes; private $dia; private $horainicio; private $arrayAsistentesAño; public function __construct($activityname=NULL, $activityid=NULL, $dia=null, $horainicio=null, $porcentajeMatriculados=NULL, $matriculados=NULL, $deportistas=NULL, $asistentes=NULL, $porcentajeAsistentes=NULL, $arrayAsistentesAño=NULL){ $this->activityname = $activityname; $this->activityid = $activityid; $this->dia = $dia; $this->horainicio = $horainicio; $this->porcentajeMatriculados = $porcentajeMatriculados; $this->matriculados = $matriculados; $this->deportistas = $deportistas; $this->asistentes = $asistentes; $this->porcentajeAsistentes = $porcentajeAsistentes; $this->arrayAsistentesAño = $arrayAsistentesAño; } public function setActivityname($activityname){ $this->activityname = $activityname; } public function getActivityname(){ return $this->activityname; } public function setActivityid($activityid){ $this->activityid = $activityid; } public function getActivityid(){ return $this->activityid; } public function setPorcentajeMatriculados($porcentajeMatriculados){ $this->porcentajeMatriculados = $porcentajeMatriculados; } public function getPorcentajeMatriculados(){ return $this->porcentajeMatriculados; } public function setMatriculados($matriculados){ $this->matriculados = $matriculados; } public function getMatriculados(){ return $this->matriculados; } public function setDeportistas($deportistas){ $this->deportistas = $deportistas; } public function getDeportistas(){ return $this->deportistas; } public function setAsistentes($asistentes){ $this->asistentes = $asistentes; } public function getAsistentes(){ return $this->asistentes; } public function setPorcentajeAsistentes($porcentajeAsistentes){ $this->porcentajeAsistentes = $porcentajeAsistentes; } public function getPorcentajeAsistentes(){ return $this->porcentajeAsistentes; } public function setDia($dia){ $this->dia = $dia; } public function getDia(){ return $this->dia; } public function setHorainicio($horainicio){ $this->horainicio = $horainicio; } public function getHorainicio(){ return $this->horainicio; } public function setArrayAsistentesAño($arrayAsistentesAño){ $this->arrayAsistentesAño = $arrayAsistentesAño; } public function getArrayAsistentesAño(){ return $this->arrayAsistentesAño; } } ?>
Java
UTF-8
764
2.65625
3
[]
no_license
package set; import java.util.TreeSet; import javax.swing.text.html.HTMLDocument.Iterator; //import java.util.Iterator; ////import java.util.LinkedHashSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet ha=new TreeSet(new ComparetorByName()); ha.add(new Person("lili",27)); ha.add(new Person("yaya",28)); ha.add(new Person("sasa",23)); ha.add(new Person("hihi",25)); ha.add(new Person("hihi",23)); // String st=null; // Object java.util.Iterator it=ha.iterator(); while(it.hasNext()) { Person p=(Person) it.next(); System.out.println(p.getName()+"...."+p.getAge()); } } // private void add(Person person) { // } }
C++
UTF-8
1,365
2.84375
3
[]
no_license
// --------------------------------------------------------------------------- MOTORES DC // motor pins int motorA0 = 6; int motorA1 = 11; int motorB0 = 3; int motorB1 = 5; int min_speed = 100; // motorLeftSpeed, motorRightSpeed; void MotorSetup() { //the motor control wires are outputs pinMode(motorA0, OUTPUT); pinMode(motorA1, OUTPUT); pinMode(motorB0, OUTPUT); pinMode(motorB1, OUTPUT); } void MotorSetMaxVelocity(int speedLeft, int speedRight) { maxSpeedLeft = speedLeft; maxSpeedRight = speedRight; } void MotorDiffTurn(int _speedLeft, int _speedRight) { int speedLeft = map(_speedLeft, -255, 255, -maxSpeedLeft, maxSpeedLeft); int speedRight = map(_speedRight, -255, 255, -maxSpeedRight, maxSpeedRight); if (speedLeft > 0) { analogWrite(motorB0, speedLeft); digitalWrite(motorB1, LOW); } if (speedLeft < 0) { digitalWrite(motorB0, LOW); analogWrite(motorB1, map(speedLeft, 0, -255, 0, 255)); } if (speedLeft == 0) { digitalWrite(motorB0, LOW); digitalWrite(motorB1, LOW); } if (speedRight > 0 ) { analogWrite(motorA0, speedRight); digitalWrite(motorA1, LOW); } if (speedRight < 0 ) { digitalWrite(motorA0, LOW); analogWrite(motorA1, map(speedRight, 0, -255, 0, 255)); } if (speedRight == 0) { digitalWrite(motorA0, LOW); digitalWrite(motorA1, LOW); } }
TypeScript
UTF-8
1,419
2.8125
3
[]
no_license
import IPackage from "../interfaces/IPackage"; import Package from "../Package"; import {Guid} from "guid-typescript"; import Person from "../Person"; export default class RecordProcessor { public static processRecords(records: any[]): IPackage[] { let pkgs: IPackage[] = []; for (const record of records) { pkgs.push(RecordProcessor.getPackage(record)); } return pkgs as IPackage[]; } public static generateInsertDocument(pkg: IPackage): any { const primaryKey: string = pkg.getId().toString(); return { _id: primaryKey, firstName: pkg.getFirstName(), lastName: pkg.getLastName(), arrivalDate: pkg.getArrivalDate(), pickupDate: pkg.getPickupDate(), } } public static generateUpdateDocument(pkg: IPackage): any { return { $set: { pickupDate: pkg.getPickupDate() } } } private static getPackage(record: any): IPackage { const firstName: string = record.firstName; const lastName: string = record.lastName; const arrivalDate: Date = record.arrivalDate; const pickupDate: Date = (record.pickupDate) ? record.pickupDate : null; const id: Guid = Guid.parse(record._id); return new Package(new Person(firstName, lastName), id, arrivalDate, pickupDate); } }
Markdown
UTF-8
884
2.90625
3
[]
no_license
# 11.虚拟环境和包 ## 概述 - 不同的应用可以使用不同版本的python,我们可以创建虚拟环境,来隔开不同的应用,支持他们使用不同的版本 ## 创建虚拟环境 - 运行`python3 -m venv tutorial-env`,这将创建 tutorial-env 目录,并在其中创建包含Python解释器,标准库和各种支持文件的副本的目录 - 创建虚拟环境之后,需要运行相对应的`activate`文件来激活该环境 ```python $ source ~/envs/tutorial-env/bin/activate (tutorial-env) $ python Python 3.5.1 (default, May 6 2016, 10:59:36) ... >>> import sys >>> sys.path ['', '/usr/local/lib/python35.zip', ..., '~/envs/tutorial-env/lib/python3.5/site-packages'] >>> ``` ## 使用pip管理包 - 可以使用一个叫做`pip`的程序来安装、升级和移除软件包
Markdown
UTF-8
2,633
2.546875
3
[ "Apache-2.0" ]
permissive
# Fake News Detector This project aims to be non-partisan and fair in it's access to data and methodology. It aims to judge an article on quality by looking at factors such as: - Who wrote the article? - Who published the article? - What are the political leanings of the author/publisher? - Are the sources for the article internal or external? - What external sources are saying about the issue the article on? Eventually, it will score articles on their sources to and provide some context on why it made the decision. ## Supported Sites - [CNN](https://www.cnn.com/) - [CNN Money](money.cnn.com) - [NBC News](https://www.nbcnews.com/) - [NBC Sports](https://www.nbcsports.com/) - [CNBC](https://www.cnbc.com/) - [MSNBC](http://www.msnbc.com/) ## Unsupported Sites (PRs wanted) - [Fox News](http://www.foxnews.com/) - [Breitbart](http://www.breitbart.com/) - [New York Times](https://www.nytimes.com/) - [Washington Post](https://www.washingtonpost.com/) - [Huffington Post](https://www.huffingtonpost.com/) - [Buzzfeed](https://www.buzzfeed.com/) - [The Guardian](https://www.theguardian.com/us) - [Daily Beast](https://www.thedailybeast.com/) - [The Hill](http://thehill.com/) - [Blaze](https://www.theblaze.com/) - [Slate](https://slate.com/) - [Bloomberg](https://www.bloomberg.com/) - etc. ## How do I add a site? 1. Sites are kept in [server/sites](https://github.com/cbelsole/fakenewsdetector/tree/master/server/sites) as a flat file for configuration for now. ```js { "corp": [], // hostnames of corporate affiliated sites "advertizer": [], // hostnames of advertizers to filter out of results "ignore": [], // ignored hostnames "articleSelector": "css selector", // css selector to find the article text "authorSelector": "css selector", // css selector to find the author of the article "titleSelector": "css selector" // css selector to find the title of the article } ``` 2. Add the site to the list of supported sites in [server/conf/sites.yaml](https://github.com/cbelsole/fakenewsdetector/tree/master/server/conf/sites.yaml) 3. Add corporate information for the site to [server/conf/corporations.yaml](https://github.com/cbelsole/fakenewsdetector/tree/master/server/conf/corporations.yaml) ## Start the dev server ``` # this will take a while because it needs to download headless chrome yarn install && cd client && yarn install && cd .. yarn run dev ``` ## How do I contribute? 1. Clone the repo. 2. Start the dev server and make sure everything is working. 3. Once your changes are done please submit a PR with a title and description describing the feature/enhancement you want to add.
Java
UTF-8
1,042
2.53125
3
[]
no_license
package diexp.di20; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; import diexp.vo7.Mart; import diexp.vo7.Product; import diexp.vo7.exp.Bus; //import diexp.vo7.exp.Driver; import diexp.vo7.exp.Driver; public class DI27 { public static void main(String[] args) { AbstractApplicationContext ctx1= new GenericXmlApplicationContext("diexp\\di20\\a27.xml"); // 한번에 객체로 로딩되는데, id값을 클래스명의 소문자가 id명을 default 설정이 된다.. Product obj1 = ctx1.getBean("product", Product.class); Mart obj2 = ctx1.getBean("mart", Mart.class); obj1.setName("사과"); obj1.setPrice(3000); obj1.setCnt(2); obj2.setMname("행복마트"); obj2.show(); Bus bus = ctx1.getBean("bus01", Bus.class); Driver driver = ctx1.getBean("driver01", Driver.class); driver.setName("마길동"); driver.setRole("1급 기사"); bus.setNumber("5050"); bus.showBusInfo(); ctx1.close(); } }
JavaScript
UTF-8
2,918
3.703125
4
[]
no_license
// Copy to clipboard function function copyToClipboard() { var copyText = document.getElementById('textBox'); copyText.select(); document.execCommand("copy"); // copy to clipboard if (window.getSelection) { // deselect text window.getSelection().removeAllRanges(); } else if (document.selection) { document.selection.empty(); } } // Live update character and word count function updateCounts() { text = document.getElementById('textBox').value; var charCount = text.length + 1; var wordCount = text.split(' ').length; document.getElementById('charCount').innerHTML = charCount; document.getElementById('wordCount').innerHTML = wordCount; } function resetCounts() { document.getElementById('charCount').innerHTML = 0; document.getElementById('wordCount').innerHTML = 0; } // Lowercase Button document.getElementById("lowercase").onclick = function () { var text = document.getElementById('textBox').value; var result = text.toLowerCase(); document.getElementById('textBox').value = result; copyToClipboard(); }; // Uppercase Button document.getElementById("uppercase").onclick = function () { var text = document.getElementById('textBox').value; var result = text.toUpperCase(); document.getElementById('textBox').value = result; copyToClipboard(); }; // Sentence Case Button document.getElementById("sentence").onclick = function () { var text = document.getElementById('textBox').value.toLowerCase().replace(/-/g, " "); var n = text.split("."); var vfinal = "" for(i=0; i < n.length; i++) { var spaceput = ""; var spaceCount = n[i].replace(/^(\s*).*$/,"$1").length; n[i] = n[i].replace(/^\s+/,""); var newstring = n[i].charAt(n[i]).toUpperCase() + n[i].slice(1); for(j=0;j<spaceCount;j++) spaceput = spaceput + " "; vfinal = vfinal + spaceput + newstring + "."; } vfinal = vfinal.substring(0, vfinal.length - 1); document.getElementById('textBox').value = vfinal; copyToClipboard(); }; // Capitalize Button document.getElementById("capitalize").onclick = function () { var text = document.getElementById('textBox').value; var result = text.replace( /\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); } ); document.getElementById('textBox').value = result.replace(/-/g, " "); copyToClipboard(); }; // Lower Dashed Button document.getElementById("dashed").onclick = function () { var text = document.getElementById('textBox').value; var result = text.toLowerCase().replace(/ /g, "-"); document.getElementById('textBox').value = result; copyToClipboard(); }; // Clear Button document.getElementById("clear").onclick = function () { document.getElementById('textBox').value = ''; resetCounts(); }; // Copy to clipboard Button document.getElementById("copy").onclick = function () { copyToClipboard(); };
C++
WINDOWS-1251
1,644
3.3125
3
[]
no_license
// , , " -2", ++, // // sample_matrix.cpp - Copyright (c) .. 07.05.2001 // Microsoft Visual Studio 2008 .. (20.04.2015) // // #include <iostream> #include "utmatrix.h" //--------------------------------------------------------------------------- void main() { int n; TMatrix<int> a(n), b(n), c(n), d(n); setlocale(LC_ALL, "Russian"); cout << " " << endl; cout << " " << endl; cin >> n; cout << " " << endl; cin >> a; cout << endl; cout << " " << endl; cin >> b; cout << endl; cout << "1 - , 2 - , 3 - , 4 - " << endl; int temp; cin >> temp; cout << endl; if (temp == 1) { c = a + b; cout << "Matrix c = a + b" << endl << c << endl; } if (temp == 2) { d = a - b; cout << "Matrix d = a - b" << endl << d << endl; } if (temp == 3) { a = b; cout << "Matrix a = b" << endl << a << endl; } if (temp == 4) { if (a != b) { cout << "Matrix a != b" << endl << d << endl; } else { cout << "Matrix a == b" << endl << d << endl; } } } //---------------------------------------------------------------------------
Python
UTF-8
413
4.1875
4
[]
no_license
highValue = 0 lowValue = 0 for person in range(1, 6): weight = float(input('What is the weight of {}ª person: '.format(person))) highValue = highValue if highValue != 0 and highValue > weight else weight lowValue = lowValue if lowValue != 0 and lowValue < weight else weight print('The person with high weight has {:.2f}Kg and the person with lower weight has {:.2f}Kg.'.format(highValue, lowValue))
Go
UTF-8
470
2.609375
3
[]
no_license
package main import ( "bytes" "code.google.com/p/go.net/html" "fmt" "io/ioutil" "log" "os" "strings" ) func main() { fmt.Println(os.Args) b, err := ioutil.ReadFile(os.Args[1]) if err != nil { panic(err) } n, err := html.Parse(strings.NewReader(string(b))) if err != nil { log.Fatalf("Parse error: %s", err) } var buf bytes.Buffer if err := html.Render(&buf, n); err != nil { log.Fatalf("Render error: %s", err) } fmt.Println(buf.String()) }
Java
UTF-8
325
1.773438
2
[]
no_license
package com.hiking.hkimgloader.loader; import android.graphics.Bitmap; import com.hiking.hkimgloader.request.BitmapRequest; /** * Created by Administrator on 2018/3/24. */ public class NullLoader extends AbstarctLoader { @Override protected Bitmap onLoad(BitmapRequest request) { return null; } }
C#
UTF-8
4,039
3.28125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Lydia.MapGeneration { /// <summary> /// A Map's blueprints which we can build from. /// Contains rooms and their locations /// </summary> public class Map { /// <summary> /// All rooms the map contains /// </summary> private List<Room> rooms; public Map(){ this.rooms = new List<Room> (); } public Map(Room[] rooms){ this.rooms = new List<Room> (); Room addResult = null; // Add rooms one by one and check if any overlap with eachother for (var i = 0; i < rooms.Length; i ++) { addResult = this.AddRoom (rooms [i]); if (addResult != null) { Debug.LogWarning ("Unable to add room due to overlapping issues. Room[" + i + "]: " + rooms[i].ToString() + ". Overlaps with: " + addResult.ToString()); } } } /// <summary> /// All rooms the map contains /// </summary> public List<Room> Rooms { get { return rooms; } } /// <summary> /// Adds the room to the map if it doesn't overlap with other rooms /// </summary> /// <returns><c>null</c>, if room was added, <c>room instace</c> of the room it's overlapping with.</returns> /// <param name="roomToAdd">Room to add.</param> public Room AddRoom(Room roomToAdd) { /** * Make sure the room we're trying to add isn't * trying to take up the space of another room */ foreach (Room room in rooms) { if (room.overlaps(roomToAdd)) { return room; } } rooms.Add (roomToAdd); return null; } /// <summary> /// Merges the rooms together removes the two previous rooms /// and then adds the merged room to the map. /// </summary> /// <returns>The rooms.</returns> /// <param name="room1">Room1.</param> /// <param name="room2">Room2.</param> public Room MergeRooms(Room room1, Room room2) { if (room1 == null || room2 == null) { Debug.LogWarning ("Can not merge null rooms"); return null; } if (!this.Rooms.Contains(room1)) { Debug.LogError ("This map does not contain the first room passed in"); return null; } if (!this.Rooms.Contains(room2)) { Debug.LogError ("The map doesn't contain the second room passed in"); return null; } List<Vector2> combinedArea = new List<Vector2> (); foreach (Vector2 area in room1.Area) { combinedArea.Add (area); } foreach (Vector2 area in room2.Area) { combinedArea.Add (room2.Position + area - room1.Position); } Room mergedRoom = new Room (room1.Position, combinedArea.ToArray()); // Remove rooms before adding or the map won't let you add (because the room would overlap with other) this.Rooms.Remove(room1); this.Rooms.Remove(room2); // Add in our merged room this.AddRoom (mergedRoom); return mergedRoom; } /// <summary> /// Finds what rooms are surrounding the current room, if there are any. /// </summary> /// <returns>Null if the room passed in is null, and a list if not</returns> /// <param name="room">Room.</param> public Room[] RoomsSurrounding(Room room) { if (room == null) { return null; } List<Vector2> areaSurroundingRoom = new List<Vector2> (); /* * Get all area that surounds the room. */ foreach (Vector2 area in room.Area) { foreach(Vector2 direction in MapGenerator.directions){ if (!areaSurroundingRoom.Contains(area + direction + room.Position)) { areaSurroundingRoom.Add (area + direction + room.Position); } } } List<Room> roomsSurounding = new List<Room> (); /* * Find area that rooms contain * * OPTIMIZATION: Only loop through rooms that haven't been added yet */ foreach (Vector2 surroundingArea in areaSurroundingRoom) { foreach (Room roomInMap in this.Rooms) { if (roomsSurounding.IndexOf (roomInMap) == -1 && roomInMap.ContainsArea (surroundingArea) && !roomInMap.Equals(room)) { roomsSurounding.Add (roomInMap); } } } return roomsSurounding.ToArray(); } } }
Python
UTF-8
628
2.765625
3
[]
no_license
import ast from unittest import TestCase from printer import Printer from printer import Paper from drivers import MethodDefinitionPrinterDriver class TestPrinter(TestCase): def setUp(self): self.paper = Paper() self.printer = Printer() self.printer.insert(self.paper) def test_addIndentationAtTheStartOfALineAsLongAsItIsNotRemoved(self): driver = MethodDefinitionPrinterDriver(self.printer) tree = ast.parse(open("samples/method.py", 'r').read()) driver.visit(tree) self.assertEqual(self.paper.text, 'public Object basic_method( Object one, Object two){\n}')
C#
UTF-8
779
3.125
3
[]
no_license
[WebMethod] public static List<string> GetPreviousSaltsAndHashes(string name) { List<string> prevSalts = new List<string>(); // Note: This totally sticks. It's unclear what this reader instance is but if it is a // SqlReader, as it name suggests, it should probably be wrapped in a using statement if (reader.HasRows) { while (reader.Read()) { prevSalts.Add(reader.GetString(0)); } } // Note: This totally sticks. It's unclear what this conn instance is but if it is a // SqlConnection, as it name suggests, it should probably be wrapped in a using statement conn.Close(); return prevSalts; } }
Python
UTF-8
913
3.4375
3
[]
no_license
from threading import Lock class Foo: def __init__(self): self.firstLock = Lock() #careful not to name variables same as method names self.secondLock = Lock() self.firstLock.acquire() self.secondLock.acquire() def first(self, printFirst: 'Callable[[], None]') -> None: # printFirst() outputs "first". Do not change or remove this line. printFirst() self.firstLock.release() def second(self, printSecond: 'Callable[[], None]') -> None: # printSecond() outputs "second". Do not change or remove this line. with self.firstLock: printSecond() self.secondLock.release() def third(self, printThird: 'Callable[[], None]') -> None: # printThird() outputs "third". Do not change or remove this line. with self.secondLock: printThird()
C++
UTF-8
5,705
2.984375
3
[]
no_license
/* 시간제한 1초 문제 폭파 작전에 투입된 태경은 폭탄 설치를 모두 마쳤다. 이제 폭탄을 한꺼번에 터뜨리기 위해 폭탄을 모두 연결시키는 작업만 남았다. 폭탄을 서로 연결하는 방법은 폭탄이 서로 전선으로 연결되면 된다. 폭탄이 설치된 모습을 격자판에 옮겨 표현하면 다음과 같다. install_bomb1 [그림 1] 현재 들고 있는 전선은 너무 빳빳해서 구부릴 수 없는 상황이다. 전선은 직선 형태로만 사용할 수 있다. 폭탄이 전선에 의해 연결되려면 전선의 양 끝에 폭탄이 붙어있어야한다. [그림 2]에서 녹색칸에 해당하는 부분에 전선이 연결된다. 또한, [그림 2]에서 볼 수 있듯 전선은 교차될 수 있다. install_bomb2 [그림 2] 전선 특징 위 전선 특징에 따라 [그림 1]에 존재하는 폭발물을 전선으로 모두 연결하면 최소 길이 4 의 전선이 필요하다. install_bomb3 [그림 3] 현재 작전을 명령한 승훈은 태경이 작전에 들고간 전선을 최대한 적게 쓰고 복귀했으면 한다. 폭탄이 설치된 상황이 주어졌을때, 폭발물을 모두 연결하는데에 필요한 전선의 최소 길이를 알아내보자. 입력 첫 번째 줄에 테스트 케이스의 개수 T가 주어진다. 다음 줄부터 T개의 테스트 케이스에 대한 정보가 주어진다. 각각의 테스트 케이스의 첫 번째 줄에 폭탄이 설치된 상황을 격자판으로 나타내었을때의 크기 R, C 가 공백을 통해 구분하여 주어진다. 두 번째 줄부터 R 개의 줄에 걸쳐 격자판 형태로 현재 폭탄이 설치된 상황이 주어진다. 각 줄은 C 개의 숫자를 가지고 있고, 각 숫자는 0 혹은 1이다. 1은 폭탄이 존재한다는 의미다. 하나의 폭탄은 서로 상하좌우로 연결되어있다. (5 ≤ R, C ≤ 10, 2 ≤ 폭탄의 개수 ≤ 6) 출력 각 테스트 케이스에 대해 폭탄을 설치하고 남은 전선의 길이를 출력한다. 만약 폭발물을 모두 연결할 수 없다면 -1을 출력한다. 각 테스트 케이스의 출력 양식은 "#t r"이다. t는 테스트 케이스의 번호이며, 1부터 시작한다. r은 문제에 대한 결과값을 뜻한다. 예제 입력 copy4 5 7 0 0 0 0 0 1 1 1 1 1 0 0 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 1 1 1 3 5 1 0 0 1 0 0 0 0 1 0 1 0 1 0 0 5 4 1 0 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1 1 0 0 9 7 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 1 1 0 1 0 0 0 예제 출력 #1 4 #2 4 #3 -1 #4 5 */ #include <stdio.h> #include <cstring> #include <queue> #include <algorithm> using namespace std; const int MAX = 10 + 10; int T; int R, C; int map[MAX][MAX]; int group[MAX][MAX], groupCnt = 1; int myMin; int finished[MAX] = {0, }; int comb[MAX]; bool visited[MAX] = {0, }; int dy[4] = {-1, 1, 0, 0}; int dx[4] = {0, 0, -1, 1}; bool getDistance() { int minDist = 987987987; for(int x=1; x<=groupCnt-1; x++) { if(finished[x]) continue; int minDist = 987987987, minGroup = -1; for(int i=0; i<R; i++) { for(int j=0; j<C; j++) { if(group[i][j] == x) { for(int k=0; k<4; k++) { int dist = 0; int g = 0; int nextY = i + dy[k]; int nextX = j + dx[k]; if(nextY < 0 || nextY > R-1 || nextX < 0 || nextX > C-1) continue; if(!group[nextY][nextX]) { while(nextY >= 0 && nextY <= R-1 && nextX >= 0 && nextX <= C-1) { if(group[nextY][nextX] == 0) { dist++; } else if(group[nextY][nextX] != x){ g = group[nextY][nextX]; break; } else if(group[nextY][nextX] == x) { break; } nextY += dy[k]; nextX += dx[k]; } if(g != 0) { if(minDist > dist) { minDist = dist; minGroup = g; } } } } } } } if(minDist != 987987987) { finished[x] = true; finished[minGroup] = true; myMin += minDist; } } for(int i=1; i<=groupCnt-1; i++) { if(!finished[i]) return false; } return true; } void setGroup(int y, int x) { queue < pair<int, int> > q; group[y][x] = groupCnt; q.push(make_pair(y, x)); while(!q.empty()) { pair<int, int> front = q.front(); q.pop(); for(int i=0; i<4; i++) { int nextY = front.first + dy[i]; int nextX = front.second + dx[i]; if(nextY < 0 || nextY > R-1 || nextX < 0 || nextX > C-1) continue; if(!group[nextY][nextX] && map[nextY][nextX] == 1) { group[nextY][nextX] = groupCnt; q.push(make_pair(nextY, nextX)); } } } } int main() { scanf("%d", &T); for(int t=1; t<=T; t++) { myMin = 0; memset(group, 0, sizeof(group)); memset(finished, 0, sizeof(finished)); groupCnt = 1; scanf("%d %d", &R, &C); for(int i=0; i<R; i++) { for(int j=0; j<C; j++) { scanf("%d", &map[i][j]); } } for(int i=0; i<R; i++) { for(int j=0; j<C; j++) { if(!group[i][j] && map[i][j] == 1) { setGroup(i, j); groupCnt++; } } } if(getDistance()) printf("#%d %d\n", t, myMin); else printf("#%d -1\n", t); } return 0; }
JavaScript
UTF-8
597
3.421875
3
[]
no_license
exports.giveNames = (name) => { return { camelToken: camelCase(name), classToken: capitalise(name), pluralToken: camelCase(name) + 's' } } function camelCase(string) { const processedStr = string .split('_') .map((word) => { return word.charAt(0).toUpperCase() + word.slice(1) }) .join(''); return processedStr.charAt(0).toLowerCase() + processedStr.slice(1); } function capitalise(string) { return string .split('_') .map((word) => { console.log(word) return word.charAt(0).toUpperCase() + word.slice(1) }) .join(''); }
Java
UTF-8
400
2.34375
2
[]
no_license
/************************************************************************* > File Name: ByteDemo.java > Author: alick > Mail: alick97@outlook.com > Created Time: 2016年11月28日 星期一 11时25分55秒 ************************************************************************/ class ByteDemo { public static void main(String[] args) { System.out.println(Byte.MAX_VALUE + "\n" + Byte.MIN_VALUE); } }
Java
UTF-8
1,520
3.171875
3
[]
no_license
//Jake Steckel CSC141-13 public class EmployeeListings { public static class Employee { private String name; private int idNum; private String department; private String position; public Employee(String n, int id, String dep, String pos) { name=n; idNum=id; department=dep; position=pos; } public Employee(String n, int id) { name=n; idNum=id; department=""; position=""; } public Employee() { name=""; idNum=0; department=""; position=""; } public String getName() { return name; } public int getIdNum() { return idNum; } public String getDep() { return department; } public String getPos() { return position; } public void setName(String n) { name=n; } public void setIdNum(int id) { idNum=id; } public void setDep(String dep) { department=dep; } public void setPos(String pos) { position=pos; } public void display() { System.out.println(name+", "+idNum+", "+department+", "+position); } public String toString() { return ""+name+", "+idNum+", "+department+", "+position; } } }
C#
UTF-8
1,933
2.546875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class select : MonoBehaviour { public static GameObject selected; public LineRenderer line; void Start() { } void Update() { } void OnMouseDown() { if(!selected) { selected=this.transform.gameObject; } else if(selected==this.transform.gameObject) { selected = null; } else if (selected!=this.transform.gameObject) { float radio = 2.5F; //ajustar a tamano del radio line = selected.gameObject.AddComponent<LineRenderer>(); line.SetWidth(0.1F, 0.1F); line.SetVertexCount(2); Vector2 temp1 = selected.transform.position; Vector2 temp2 = this.transform.position; float dist = Vector2.Distance(temp1,temp2); float disty = Mathf.Abs(temp1.y-temp2.y); float distx = Mathf.Abs(temp1.x-temp2.x); print(dist); print(disty); print(distx); if (temp1.x>=temp2.x) { temp1.x=temp1.x-(distx/dist)*radio; temp2.x=temp2.x+(distx/dist)*radio; } else { temp1.x=temp1.x+(distx/dist)*radio; temp2.x=temp2.x-(distx/dist)*radio; } if (temp1.y>=temp2.y) { temp1.y=temp1.y-(disty/dist)*radio; temp2.y=temp2.y+(disty/dist)*radio; } else { temp1.y=temp1.y+(disty/dist)*radio; temp2.y=temp2.y-(disty/dist)*radio; } line.SetPosition(0, temp1); line.SetPosition(1, temp2); print(selected); print(this.transform.gameObject); selected=null; } } }
Markdown
UTF-8
2,101
2.875
3
[ "Apache-2.0" ]
permissive
# Pdfy # Pdfy is a Python library for converting HTML (and anything Chrome can render) into PDF. It uses Chrome printing functionality, so the PDFs will be rendered exactly as printed in the browser. ## Installation ## To install the library, you need to run. pip install pdfy Additionally, [you will need to install Chrome Driver](http://chromedriver.chromium.org/getting-started). ## Usage ## Using the library is as easy as: from pdfy import Pdfy p = Pdfy() p.html_to_pdf("html_file.htm", pdf_path="pdf_file.pdf") ### More control over the PDF layout ### If you need to have more control over the layout, you can pass additional parameters to html_to_pdf options = {"paperWidth": 8.3, "paperHeight":11.7} p.html_to_pdf("html_file.htm", pdf_path="pdf_file.pdf" options=options) The full list of parameters is available on [Chrome's Developer site](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF). ### Not saving the PDF ### In the absence of the pdf_path argument, the html_to_pdf function will return the PDF as a base64 encoded string. pdf = p.html_to_pdf("html_file.htm") ### Multiple instances ### The library will run Chrome in the background in the remote debug mode. This means that if your project requires multiple initialized Pdfy objects, you might need to change the port used for debugging. This can be done by passing the port number to Pdfy() as follows: p = Pdfy(debug_port=9222) #9222 is the default port ## Credits ## This library is released under [the Apache 2.0 License](https://opensource.org/licenses/Apache-2.0). (C) Copyright 2018 [Mika Hämäläinen](https://mikakalevi.com) ## Cite @software{mika_hamalainen_2020_3977555, author = {Mika Hämäläinen and Mike and Mirza Delic}, title = {mikahama/pdfy 1.0.40}, month = aug, year = 2020, publisher = {Zenodo}, version = {1.0.40}, doi = {10.5281/zenodo.3977555}, url = {https://doi.org/10.5281/zenodo.3977555} }
C++
UTF-8
441
2.640625
3
[]
no_license
#include <iostream> #include <string> #include <sstream> using namespace std; int main ( void ) { string s; int n1 = 0, n2 = 0, h = 0, m = 0; int hour = 0, minuts = 0; cin >> s; cin >> h >> m; n1 = ( s[0] - 48 ) * 10 + ( s[1] - 48 ); n2 = ( s[3] - 48 ) * 10 + ( s[4] - 48 ); minuts = n2 + m; if ( minuts > 59 ) { minuts = minuts % 60; hour++; } hour += ( n1 + h ) % 24; printf ( "%02i:%02i", hour, minuts ); return 0; }
C++
UTF-8
1,255
3
3
[]
no_license
// // main.cpp // integer_triangle_43105 // // Created by 김윤상 on 29/04/2020. // Copyright © 2020 김윤상. All rights reserved. // #include <iostream> #include <string> #include <vector> using namespace std; int cash[500][500]; int a = 0, b = 0; int solution(vector<vector<int>> triangle) { int answer = 0; for (int i =0; i < triangle[triangle.size() - 1].size(); i++) cash[triangle.size() - 1][i] = triangle[triangle.size() - 1][i]; for(int i = triangle.size() - 2; i >= 0; i--){ for (int j =0; j < i + 1; j++) { cash[i][j] = max(cash[i + 1][j], cash[i+1][j+1]) + triangle[i][j]; } } answer = cash[0][0]; return answer; } int main(int argc, const char * argv[]) { // insert code here... vector<vector<int>> triangle (5, vector<int>(5, 0)); triangle[0][0] = 7; triangle[1][0] = 3; triangle[1][1] = 8; triangle[2][0] = 8; triangle[2][1] = 1; triangle[2][2] = 0; triangle[3][0] = 2; triangle[3][1] = 7; triangle[3][2] = 4; triangle[3][3] = 4; triangle[4][0] = 4; triangle[4][1] = 5; triangle[4][2] = 2; triangle[4][3] = 6; triangle[4][4] = 5; int i = solution(triangle); cout<<i << endl; }
Markdown
UTF-8
2,299
2.609375
3
[ "MIT" ]
permissive
### Saving and loading * FSM diagrams can be saved to (resp. read from) files with the ![](./imgs/save.png) (resp. ![](./imgs/open.png)) button of the toolbar (or the by invoking the `Save`, `Save As` or `Open` actions in the `File` menu) * The ![](./imgs/new.png) button (`New` action in the `File` menu) clears the current diagram ### Editing * To **add a state**, select the ![](./imgs/state.png) button in the toolbar and click on the canvas * To **add a transition**, select the ![](./imgs/transition.png) button, click on the start state and, keeping the mouse button pressed, go the end state and release mouse button. * To **add a self transition** (from a state to itself) , select the ![](./imgs/loop.png) button and click on start state (the location of the click will decide on that of the transition). * To **add an initial transition**, select the ![](./imgs/initstate.png) button and click on initial state * To **delete a state or a transition**, select the ![](./imgs/delete.png) button and click on the state or transition (deleting a state will also delete all incoming and outcoming transitions) * To **move a state**, select the ![](./imgs/select.png) button and drag the state. * To **edit a state or a transition**, select the ![](./imgs/select.png) button, click on the corresponding item and update the property panel on the right. ### Compiling * To **generate a DOT representation of the diagram**, click the ![](./imgs/compileDOT.png) button (or invoke the corresponding action in the `Build` menu) * To **generate `CTask` code **, click the ![](./imgs/compileCTask.png) button * To **generate `SystemC` code **, click the ![](./imgs/compileSystemc.png) button * To **generate `VHDL` code **, click the ![](./imgs/compileVHDL.png) button The generated graphs and code will appear as separate tabs in the right part of the window. ### Simulating To **simulate the diagram** (provided that stimuli have been attached to inputs using the `IOs and variables` in the left part of the window), click the ![](./imgs/runSimulation.png) button (or invoke the corresponding action in the `Build` menu) If a valid VCD viewer (such as `gtkwave`) has been specified, simulation results will be displayed in a separate window.
Java
UTF-8
5,180
1.84375
2
[]
no_license
package com.yulu.zhaoxinpeng.myeasyshop_2017_4_13.User.Registe; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.MenuItem; import android.widget.Button; import android.widget.EditText; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import com.hannesdorfmann.mosby.mvp.MvpActivity; import com.yulu.zhaoxinpeng.myeasyshop_2017_4_13.R; import com.yulu.zhaoxinpeng.myeasyshop_2017_4_13.commons.ActivityUtils; import com.yulu.zhaoxinpeng.myeasyshop_2017_4_13.commons.RegexUtils; import com.yulu.zhaoxinpeng.myeasyshop_2017_4_13.components.AlertDialogFragment; import com.yulu.zhaoxinpeng.myeasyshop_2017_4_13.components.ProgressDialogFragment; import com.yulu.zhaoxinpeng.myeasyshop_2017_4_13.main.MainActivity; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; public class RegisteActivity extends MvpActivity<RegisteView,RegistePresenter> implements RegisteView{ @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.et_username) EditText mEtUsername; @BindView(R.id.et_pwd) EditText mEtPwd; @BindView(R.id.et_pwdAgain) EditText mEtPwdAgain; @BindView(R.id.btn_register) Button mBtnRegister; private Unbinder unbinder; private ActivityUtils mActivityUtils; private String Username; private String Password; private String Pwdagain; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; private ProgressDialogFragment mProgressDialogFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registe); unbinder = ButterKnife.bind(this); mActivityUtils = new ActivityUtils(this); initView(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @NonNull @Override public RegistePresenter createPresenter() { return new RegistePresenter(); } private void initView() { setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mEtUsername.addTextChangedListener(mTextWatcher); mEtPwd.addTextChangedListener(mTextWatcher); mEtPwdAgain.addTextChangedListener(mTextWatcher); } private TextWatcher mTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { Username = mEtUsername.getText().toString(); Password = mEtPwd.getText().toString(); Pwdagain = mEtPwdAgain.getText().toString(); boolean canLogin = !(TextUtils.isEmpty(Username) || TextUtils.isEmpty(Password) || TextUtils.isEmpty(Pwdagain)); mBtnRegister.setEnabled(canLogin); } }; @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) finish(); return super.onOptionsItemSelected(item); } @OnClick(R.id.btn_register) public void onClick() { if (RegexUtils.verifyUsername(Username) != RegexUtils.VERIFY_SUCCESS) { mActivityUtils.showToast(R.string.username_rules); return; } else if (RegexUtils.verifyPassword(Password) != RegexUtils.VERIFY_SUCCESS) { mActivityUtils.showToast(R.string.password_rules); return; } else if (!TextUtils.equals(Password, Pwdagain)) { mActivityUtils.showToast(R.string.username_equal_pwd); return; } getPresenter().Registe(Username,Password); } @Override public void showPrb() { mActivityUtils.hideSoftKeyboard(); if (mProgressDialogFragment==null) { mProgressDialogFragment=new ProgressDialogFragment(); } if (mProgressDialogFragment.isVisible()) return; mProgressDialogFragment.show(getSupportFragmentManager(),"dialogFragment"); } @Override public void hidePrb() { mProgressDialogFragment.dismiss(); } @Override public void registerSuccess() { mActivityUtils.startActivity(MainActivity.class); finish(); } @Override public void registerFailed() { mEtUsername.setText(""); mEtPwd.setText(""); mEtPwdAgain.setText(""); } @Override public void showMsg(String msg) { mActivityUtils.showToast(msg); } }
JavaScript
UTF-8
5,980
2.84375
3
[]
no_license
function showItems() { hide("edit-form-wrapper"); hide("select-movie-dialog"); show("page"); let xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { document.getElementById("movie-table").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "getMovies.php", true); xmlhttp.send(); } function deleteItem() { show("select-movie-dialog"); hide("edit-form-wrapper"); hide("page"); document.getElementById("select-movie-message").innerHTML = "Please select the movie to delete:"; document.getElementById("selected-function").value = "delete"; let xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { document.getElementById("edMovie").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "getMoviesList.php", true); xmlhttp.send(); } function editItem() { show("select-movie-dialog"); hide("edit-form-wrapper"); hide("page"); document.getElementById("select-movie-message").innerHTML = "Please select the movie to edit:"; document.getElementById("selected-function").value = "edit"; let xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { document.getElementById("edMovie").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "getMoviesList.php", true); xmlhttp.send(); } function getMovieDetails() { let o = document.getElementById("edMovie"); let movieID = o.options[o.selectedIndex].value; let movieName = o.options[o.selectedIndex].text; if (movieID === '-1') return; let xmlhttp; if (document.getElementById("selected-function").value === "delete") { if (!confirm("Do you want to delete the movie '" + movieName + "'?")) return; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { alert(xmlhttp.responseText); showItems(); } }; xmlhttp.open("GET", "deleteMovie.php?id=" + movieID, true); xmlhttp.send(); return; } hide("select-movie-dialog"); show("edit-form-wrapper"); document.getElementById("movieID").value = movieID; document.getElementById("formTitle").innerHTML = "Edit existing Movie"; document.getElementById("movieTitle").value = ""; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { let xmlDoc, genreID; if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { xmlDoc = xmlhttp.responseXML; movieName = xmlDoc.getElementsByTagName("movieName")[0].childNodes[0].nodeValue; genreID = xmlDoc.getElementsByTagName("genreId")[0].childNodes[0].nodeValue; document.getElementById("movieTitle").value = movieName; fillGenresDropDownList(genreID); } }; xmlhttp.open("GET", "getMovie.php?id=" + movieID, true); xmlhttp.send(); } function fillGenresDropDownList(selectedGenre) { let xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { document.getElementById("genre").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "getGenres.php?id=" + selectedGenre, true); xmlhttp.send(); } function addItem() { hide("page"); hide("select-movie-dialog"); show("edit-form-wrapper"); document.getElementById("movieID").value = "-1"; document.getElementById("formTitle").innerHTML = "Add New Movie"; document.getElementById("movieTitle").value = ""; fillGenresDropDownList("-1"); } function saveMovie() { let itemID = document.getElementById("movieID").value; let itemName = document.getElementById("movieTitle").value; let o = document.getElementById("genre"); let itemGenre = o.options[o.selectedIndex].value; let xmlhttp; if (confirm('Do you want to save this movie?')) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { alert(xmlhttp.responseText); showItems(); } }; let url = (itemID === "-1" ? "addMovie.php" : "updateMovie.php") + "?itemID=" + itemID + "&itemName=" + itemName + "&itemGenre=" + itemGenre; xmlhttp.open("GET", url, true); xmlhttp.send(); } } function show(objectName) { document.getElementById(objectName).style.display = 'block'; } function hide(objectName) { document.getElementById(objectName).style.display = 'none'; }
Rust
UTF-8
1,232
2.75
3
[ "Apache-2.0" ]
permissive
mod helper; use szimg::png::save_png; use helper::diff_file; #[test] fn test_save_png_rgb() { let mut png_array = [[[0_u8; 3]; 255]; 255]; for outer_index in 0..255 { for inner_index in 0..255 { png_array[outer_index][inner_index][0] = outer_index as u8; png_array[outer_index][inner_index][1] = inner_index as u8; png_array[outer_index][inner_index][2] = 128; } } save_png("./tests/output/rgb.png", png_array).unwrap(); assert!(diff_file("./tests/output/rgb.png", "./tests/templates/rgb.png")); } #[test] fn test_save_png_rgba() { // Prepare data let mut png_array = [[[0_u8; 4]; 255]; 255]; for outer_index in 0..255 { for inner_index in 0..255 { png_array[outer_index][inner_index][0] = outer_index as u8; png_array[outer_index][inner_index][1] = inner_index as u8; png_array[outer_index][inner_index][2] = 128; png_array[outer_index][inner_index][3] = ((outer_index as u16 + inner_index as u16) / 2) as u8; } } save_png("./tests/output/rgba.png", png_array).unwrap(); assert!(diff_file("./tests/output/rgba.png", "./tests/templates/rgba.png")); }
Java
UTF-8
2,199
2.015625
2
[ "Apache-2.0" ]
permissive
package net.sparkeek.piggybank.tests.mock; import android.content.Context; import android.support.annotation.NonNull; import com.github.aurae.retrofit2.LoganSquareConverterFactory; import com.squareup.picasso.Picasso; import dagger.Module; import net.sparkeek.piggybank.di.modules.ModuleRest; import net.sparkeek.piggybank.rest.GitHubService; import net.sparkeek.piggybank.rest.errorHandling.ErrorHandlingExecutorCallAdapterFactory; import io.palaima.debugdrawer.picasso.PicassoModule; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.MockWebServer; import retrofit2.Retrofit; import static org.mockito.Mockito.mock; @Module public class MockModuleRest extends ModuleRest { //region Fields private MockWebServer mMockWebServer; private final Picasso mPicasso = mock(Picasso.class); private final PicassoModule mPicassoModule = mock(PicassoModule.class); //endregion //region Constructor public MockModuleRest() { mMockWebServer = new MockWebServer(); } //endregion //region Modules @Override public GitHubService provideGithubService(@NonNull final OkHttpClient poOkHttpClient) { final Retrofit loRetrofit = new Retrofit.Builder() .baseUrl(mMockWebServer.url("/").toString()) .client(poOkHttpClient) .addConverterFactory(LoganSquareConverterFactory.create()) .addCallAdapterFactory(new ErrorHandlingExecutorCallAdapterFactory(new ErrorHandlingExecutorCallAdapterFactory.MainThreadExecutor())) .build(); return loRetrofit.create(GitHubService.class); } @Override public Picasso providePicasso(@NonNull final Context poContext) { return mPicasso; } @Override public PicassoModule providePicassoModule(@NonNull final Picasso poPicasso) { return mPicassoModule; } //endregion //region Getters public MockWebServer getMockWebServer() { return mMockWebServer; } public Picasso getPicasso() { return mPicasso; } //endregion //region Visible API public void setUp() { mMockWebServer = new MockWebServer(); } //endregion }
JavaScript
UTF-8
11,145
3
3
[]
no_license
$(document).ready(function () { let selectedLang = {} selectedLang = sessionStorage.getItem("lang"); //Get selected language from session variable if (selectedLang === "all") selectedLang = {} //If album category selected in library page if (sessionStorage.getItem("section") === "category") { var selectedCategory; $("#song-heading").hide(); selectedCategory = sessionStorage.getItem("value") //Get selected category name $.ajax({ //Get albums as per selected category and language type: "GET", url: "http://localhost:3000/albums", dataType: "json", data: { "category": selectedCategory, "language": selectedLang }, async: true, success: function (albums) { if (albums.length === 0) $(".album-container").append(`<h5>No albums present in the selected language in this category</h5>`); else { let albumlist = "" $.each(albums, function (i, a) { //Display each album as card var albumId = a.id; albumlist += ` <div id=${albumId} class="card"> <img class="card-img-top" src=${a.cover} alt="Card image cap"> <h5 class="card-title">${a.name}</h5> <p class="card-text" style="font-size: 12px;">${a.artist}</p> </div> ` }) $(".album-container").append(albumlist); } }, error: function () { console.log("not able to process request"); }, }); } //If artist selected in library page if (sessionStorage.getItem("section") === "artists") { selectedArtist = sessionStorage.getItem("value") //Get artist name from session variable $.ajax({ //Get albums as per selected language type: "GET", url: "http://localhost:3000/albums", data: { "language": selectedLang }, dataType: "json", async: true, success: function (albums) { if (albums.length === 0) { console.log("Not found") } else { let albumlist = ""; $.each(albums, function (i, a) { //Get all the songs $.ajax({ type: "GET", url: "http://localhost:3000/songs", dataType: "json", async: true, success: function (songs) { if (songs.length === 0) console.log("Not found") else { let songlist = "" $.each(songs, function (i, s) { //Check if the selected artist is associated with the song and the song is assoiciated with album fetched if (s.artist.includes(selectedArtist) && a.id === s.album_id) { songlist += ` <div class="song"> <div id=${s.id} class="card"> <img class="card-img-top" src=${a.cover} alt="Card image cap"> <div class="card-body" style="text-align: left;"> <h5 class="card-title" style="margin:2px;">${s.name}</h5> <p class="card-text" style="font-size: 12px;margin:2px;">Album : ${a.name}</p> <p class="card-text" style="font-size: 12px;margin:2px;">Artist(s) : ${s.artist}</p> <p class="card-text" style="font-size: 12px;margin:2px;">Duration : ${s.duration}</p> </div> <img class="play-img" src="../assets/images/play.png" > </div> </div> `; } }) $(".song-container").append(songlist); } }, error: function () { console.log("not able to process request"); }, }); if (a.artist.includes(selectedArtist)) { //Check if the selected artist is associated with the album. If yes,print var albumId = a.id; albumlist += ` <div id=${albumId} class="card"> <img class="card-img-top" src=${a.cover} alt="Card image cap"> <h5 class="card-title">${a.name}</h5> <p class="card-text" style="font-size: 12px;">${a.artist}</p> </div> ` } }) $(".album-container").append(albumlist); if (albumlist === ``) $(".album-container").append(`<h5>No albums present for the artist in the selected language</h5>`); } }, error: function () { console.log("not able to process request"); }, }); } //On selecting the album,store id of album in session storage and navigate to songlist page $(".album-container").on("click", ".card", function (e) { let selectedAlbum = e.currentTarget.id; sessionStorage.setItem("selectedAlbum", selectedAlbum); window.location.href = "songlist.html" }) //On selecting the song,append id of song in url and navigate to audio player page $(".song-container").on("click", ".card", function (e) { let selectedSong = e.currentTarget.id; //Add song id to recently played $.ajax({ type: "GET", url: "http://localhost:3000/users/" + sessionStorage.getItem("id"), dataType: "json", async: true, success: function (user) { let userAddSong; user = JSON.parse(JSON.stringify(user).replace("recentlyPlayed[]", "recentlyPlayed")); if (user.recentlyPlayed.includes(selectedSong)) { user.recentlyPlayed.splice(user.recentlyPlayed.indexOf(selectedSong), 1) user.recentlyPlayed.unshift(selectedSong) } else if (user.recentlyPlayed.length <= 5) { user.recentlyPlayed.unshift(selectedSong) if (user.recentlyPlayed.includes("none")) user.recentlyPlayed.pop() } else { user.recentlyPlayed.unshift(selectedSong) user.recentlyPlayed.pop() } console.log(user) $.ajax({ type: "PUT", url: "http://localhost:3000/users/" + sessionStorage.getItem("id"), dataType: "json", data: user, async: true, success: function () { window.location.href = "audio.html?id=" + selectedSong //navigate to audio player page } }) } }) }) //If a song is searched if (sessionStorage.getItem("section") === "search") { $("#album-heading").hide() $.ajax({ type: "GET", url: "http://localhost:3000/songs", dataType: "json", async: true, success: function (data) { const URLparams = new URLSearchParams(window.location.search); searchedSong = URLparams.get('searchSong') //Get song id from url params $.each(data, function (i, song) { if (song.name.toLowerCase() === searchedSong) $.ajax({ type: "GET", url: "http://localhost:3000/albums", dataType: "json", data: { "id": song.album_id }, async: true, success: function (data) { let songlist = ""; $.each(data, function (i, album) { //Display song info songlist += ` <div class="song"> <div id=${song.id} class="card"> <img class="card-img-top" src=${album.cover} alt="Card image cap"> <div class="card-body" style="text-align: left;"> <h5 class="card-title" style="margin:2px;">${song.name}</h5> <p class="card-text" style="font-size: 12px;margin:2px;">Album : ${album.name}</p> <p class="card-text" style="font-size: 12px;margin:2px;">Artist(s) : ${song.artist}</p> <p class="card-text" style="font-size: 12px;margin:2px;">Duration : ${song.duration}</p> </div> <img class="play-img" src="../assets/images/play.png" > </div> </div> `; }) $(".song-container").append(songlist); }, error: function () { console.log("not able to process request"); }, }) }) }, error: function () { console.log("not able to process request"); }, }); } })
JavaScript
UTF-8
704
2.65625
3
[]
no_license
let submitSubscription = document.getElementById('formSubscribe') submitSubscription.addEventListener('submit', function (event) { event.preventDefault(); if (submitSubscription.checkValidity()) { let email = submitSubscription[0].value let promise = changeSubscription('subscribe', email) promise.then(response => { if (response == 'success') { let success = document.querySelector('.valid-feedback') success.style.display = "block" if (submitSubscription[0].readOnly) { setTimeout(() => submitSubscription.style.display = 'none', 2000); } } }); } })
Python
UTF-8
507
2.859375
3
[]
no_license
import math T=int(input()) len=0 br=0 sr=0 for i in range(0,T): x1,y1,r1,x2,y2,r2=map(int,input().split()) len=math.sqrt((x2-x1)**2+(y2-y1)**2) if r1>=r2: br=r1 sr=r2 else: br=r2 sr=r1 if len<r1+r2 and br-sr<len: print(2) if r1+r2==len or (br-sr==len and (x1!=x2 or y1!=y2)): print(1) if r1+r2<len or len<br-sr or(x1==x2 and y1==y2 and r1!=r2): print(0) if x1==x2 and y1==y2: if r1==r2: print(-1)
Markdown
UTF-8
8,026
2.859375
3
[ "MIT" ]
permissive
# chef-dokku [![Build Status](http://img.shields.io/travis/fgrehm/chef-dokku.svg)](http://travis-ci.org/fgrehm/chef-dokku) [![Cookbook Version](https://img.shields.io/cookbook/v/dokku.svg)](https://community.opscode.com/cookbooks/dokku) Manages a [dokku](https://github.com/progrium/dokku) installation, allowing configuration of application's [environment variables](https://github.com/progrium/dokku#environment-setup), installation of [plugins](https://github.com/progrium/dokku/wiki/Plugins) and management of ssh keys. ## :warning: This project is no longer being actively maintained :warning: This project is no longer being maintained and you might want to check out https://github.com/nickcharlton/dokku-cookbook ## Usage Include the `bootstrap` recipe in your run list to have dokku installed/updated during chef runs. ### Docker This cookbook does not handle aspects of the docker installation such as lxc support or storage drivers. Please refer to the [docker cookbook](https://github.com/bflad/chef-docker) for more information on the specifics of a docker install. ## Attributes These attributes are under the `node['dokku']` namespace. Attribute | Description | Type | Default ----------|-------------|------|-------- root | dokku's home directory | String | `/home/dokku` domain | Domain name to write to `['dokku']['root]'/VHOST` | String | nil (`node['fqdn']` will be used) ssh_keys | SSH keys that can push to dokku | Hash | `{}` see [SSH Keys](https://github.com/fgrehm/chef-dokku#ssh-keys) plugins | Plugins to install | Hash with plugin name as key and GitHub repository URL as value | `{}` see [Plugins](https://github.com/fgrehm/chef-dokku#plugins) plugin_path | Directory where plugins are installed | String | `/var/lib/dokku/plugins` apps | App environment settings to populate | Hash | `{}` see [Apps](https://github.com/fgrehm/chef-dokku#apps) git_repository | The git repository for the base dokku code | String | https://github.com/progrium/dokku.git git_revision | The git revision to check out from `git_repository` | String | v0.2.0 ## Configuration While this cookbook will be able to provide you with a working dokku installation, there is some configuration you will likely want to do first: ### SSH Keys This is a required step to getting dokku working. You will want to set `node['dokku']['ssh_keys']` to a hash of the following structure: default['dokku']['ssh_keys'] = { 'awesome_user' => 'awesome_users_pubkey', 'superb_user' => 'superb_users_pubkey' } The [`ssh_keys`](https://github.com/fgrehm/chef-dokku#recipes) recipe will handle setting up the keys for dokku ### Apps Pre-configured applications. These attributes are used to configure environment variables or remove an app: default['dokku']['apps'] = { 'cool_app' => { 'env' => { 'ENV_VAR' => 'ENV_VAR_VALUE', 'ENV_VAR2' => 'ENV_VAR2_VALUE' }, 'tls' => { 'cert_file' => '/etc/ssl/certs/my.pem', 'key_file' => '/etc/ssl/private/my.key' } } } Both `env` and `tls` are optional. To enable TLS connection to your application, use `tls` attribute. `cert_file` and `key_file` are the paths to .crt/.pem and .key files. The [`apps`](https://github.com/fgrehm/chef-dokku#recipes) repice will create symlinks inside `$APP_HOME/tls` folder pointing to paths you've defined. If you want to enable TLS connections for all applications at once, you can use [certificate](https://supermarket.getchef.com/cookbooks/certificate) cookbook. For more information, check out [dokku documentation](http://progrium.viewdocs.io/dokku/tls-spdy-support). ### Plugins You will likely want to install plugins to expand the functionality of your dokku installation. See the dokku [wiki page](https://github.com/progrium/dokku/wiki/Plugins) for a list of available plugins. Plugins are defined on the `node['dokku']['plugins']` attribute: default['dokku']['plugins'] = { 'plugin_name' => 'plugin_repository_url', # For example: 'postgresql' => 'https://github.com/Kloadut/dokku-pg-plugin' } ### Applications Attributes These attributes are under the `node['dokku']['apps']['YOUR_APP_NAME']` namespace. Attribute | Description | Type | Default ----------|-------------|------|-------- env | Application's [environment variables](https://github.com/progrium/dokku#environment-setup) | Hash | nil remove | Whether the application should be removed | Boolean | nil ### Sync attributes These attributes are under the `node['dokku']['sync']` namespace. They control whether remote code bases will be updated on chef runs Attribute | Description | Type | Default ----------|-------------|------|-------- base | Whether the dokku codebase will be synced with the remote repository | Boolean | true plugins | Whether the dokku plugins will be synced with their remote repositories | Boolean | true dependencies | Whether the sshcommand and pluginhook dependencies will be updated from their remotes | Boolean | true ### Build Stack attributes These attributes are under the `node['dokku']['buildstack']` namespace. They correspond to the [buildstep](https://github.com/progrium/buildstep) that is used by dokku. Attribute | Description | Type | Default ----------|-------------|------|-------- image_name | The name of the image to use when importing into Docker | String | progrium/buildstep use_prebuilt | Whether to use the prebuilt image or build off the git repository | Boolean | true stack_url | The url to the buildstep git repository | String | github.com/progrium/buildstep prebuilt_url | The url to the prebuild docker image for the buildstep | String | https://s3.amazonaws.com/progrium-dokku/progrium_buildstep_79cf6805cf.tgz ### PluginHook Attributes These attributes are under the `node['dokku']['pluginhook']` namespace. Attribute | Description | Type | Default ----------|-------------|------|-------- src_url | The source url for the pluginhook .deb file | String | https://s3.amazonaws.com/progrium-pluginhook/pluginhook_0.1.0_amd64.deb filename | The pluginhook .deb file name | String | pluginhook_0.1.0_amd64.deb checksum | The SHA-256 checksum for the pluginhook .deb file | String | 26a790070ee0c34fd4c53b24aabeb92778faed4004110c480c13b48608545fe5 ## Recipes * `recipe[dokku]` - Noop. Will be used to include LWRPs in the future * `recipe[dokku::bootstrap]` - A chef version of [`bootstrap.sh`](https://github.com/progrium/dokku/blob/master/bootstrap.sh). Include this recipe to have dokku installed/updated by chef * `recipe[dokku::install]` - Clones/checks out the dokku git repository and copies the required files via `make copyfiles` * `recipe[dokku::buildstack]` - Builds/imports the dokku [buildstep](https://github.com/progrium/buildstep) docker image. See `node['dokku']['buildstack']['use_prebuilt']` to set which buildstep is imported ## Testing and Development ### Vagrant Here's how you can quickly get testing or developing against the cookbook thanks to [Vagrant](http://vagrantup.com/). vagrant plugin install vagrant-omnibus git clone git://github.com/fgrehm/chef-dokku.git cd chef-dokku bundle install bundle exec berks install -p vendor/cookbooks vagrant up You can then SSH into the running VM using the `vagrant ssh` command. The VM can easily be stopped and deleted with the `vagrant destroy` command. Please see the official [Vagrant documentation](http://docs.vagrantup.com/v2/cli/index.html) for a more in depth explanation of available commands. ## Roadmap * Convert things like ssh keys, app env, etc to LWPRs w/ Chefspec v3 matchers * Reduce rewritten/overridden areas of the bootstrap process to better keep up with dokku's rapid development * Plugin removal * Use dokku app removal process * Support dokku [addons](https://github.com/progrium/dokku/pull/292) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/fgrehm/chef-dokku/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
Rust
UTF-8
3,359
3.515625
4
[]
no_license
use std::fmt::Debug; use std::cmp::max; pub struct CircularBuffer<T> { buffer: Vec<T>, tail: usize, } impl<T> CircularBuffer<T> { pub fn with_capacity(capacity: usize) -> CircularBuffer<T> { if capacity == 0 { panic!("Zero-capacity buffer not supported") } CircularBuffer { buffer: Vec::with_capacity(capacity), tail: 0, } } pub fn fill_with(items: Vec<T>) -> CircularBuffer<T> { CircularBuffer { buffer: items, tail: 0 } } #[inline] fn index_into(&self, raw_index: usize) -> usize { raw_index % self.buffer.capacity() } #[inline] fn head_unchecked(&self) -> usize { self.index_into(self.tail + self.buffer.capacity()) } pub fn push(&mut self, item: T) { if !self.is_full() { self.buffer.push(item); } else { self.buffer[self.tail] = item; self.tail = self.index_into(self.tail + 1); } } pub fn is_full(&self) -> bool { debug_assert!(self.buffer.len() <= self.buffer.capacity()); self.buffer.len() == self.buffer.capacity() } pub fn len(&self) -> usize { if !self.is_full() { self.buffer.len() } else { self.buffer.capacity() } } pub fn iter(&self) -> impl Iterator<Item = &T> { let (u, v) = self.slices(); u.iter().chain(v.iter()) } pub fn slices(&self) -> (&[T], &[T]) { if !self.is_full() { (self.buffer.as_slice(), &[]) } else { ( &self.buffer[self.tail..], &self.buffer[..self.head_unchecked()], ) } } } impl<T: Debug> Debug for CircularBuffer<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{:?} @ {}", self.buffer, max(self.head_unchecked(), self.len()) ) } } impl<T: PartialEq> PartialEq for CircularBuffer<T> { fn eq(&self, other: &Self) -> bool { // JB 2021-01-02: can do advanced magic with slices, but unnecessary // for any existing requirements self.iter().eq(other.iter()) } } #[cfg(test)] mod tests { use super::*; #[test] fn can_enumerate_empty_buffer() { let b = CircularBuffer::<i32>::with_capacity(2); let mut i = b.iter(); assert_eq!(None, i.next()) } #[test] fn can_enumerate_partial_buffer() { let mut b = CircularBuffer::with_capacity(2); b.push(0i32); let mut i = b.iter(); assert_eq!(Some(&0), i.next()); assert_eq!(None, i.next()); } #[test] fn can_enumerate_full_buffer() { let mut b = CircularBuffer::with_capacity(2); b.push(0i32); b.push(1); let mut i = b.iter(); assert_eq!(Some(&0), i.next()); assert_eq!(Some(&1), i.next()); assert_eq!(None, i.next()); } #[test] fn can_enumerate_overfull_buffer() { let mut b = CircularBuffer::with_capacity(2); b.push(0i32); b.push(1); b.push(2); let mut i = b.iter(); assert_eq!(Some(&1), i.next()); assert_eq!(Some(&2), i.next()); assert_eq!(None, i.next()); } }
JavaScript
UTF-8
1,477
2.625
3
[]
no_license
export default class PwProjectLayout extends HTMLElement { static get observedAttributes() { return ['svg']; } createdCallback() { // Setting the initial attributes this._svg = this.getAttribute('svg') || ''; // Setting the Inner Dom and the styles this.attachShadow({ mode: 'open' }); this.render(); if (super.createdCallback) { super.createdCallback(); } } attributeChangedCallback(name, oldVal, newVal) { if (this[name] !== newVal) { this[name] = newVal; } } render() { this.shadowRoot.innerHTML = this.style + this.html; } get svg() { return this._svg; } set svg(value) { this._svg = value; this.setAttribute('svg', value); this.render(); } get html() { /* eslint quotes:0 class-methods-use-this:0 */ return `<div class="container"> <img src="${this.svg}"/> </div>`; } get style() { return `<style> .container { border: 10px solid #b6bdc3; background: #fff; margin: 0 auto; } /* Required to make image fluid in IE */ img:not(.png) { width: 100%; height: 35em; } </style>`; } } // Check that the element hasn't already been registered if (!window.customElements.get('pw-project-layout')) { document.registerElement('pw-project-layout', PwProjectLayout); }
C#
UTF-8
3,287
2.78125
3
[]
no_license
using BambiDataAccess; using BambiIBusinessLogic; using BambiModels; using BambiSQLServerDataAccess; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BambiBusinessLogic { /// <summary> /// Business logic class whose purpose is to handle /// data access for EngineType table. It implements /// IEngineTypeBusinessLogic interface. /// </summary> public class EngineTypeLogic : IEngineTypeBusinessLogic { private readonly IEngineTypeRepository _engineTypeRepository; /// <summary> /// Constructor whose purpose is to create /// a new EngineTypeSQLServerDataAccess object. /// </summary> public EngineTypeLogic() : this(new EngineTypeSQLServerDataAccess()) { } /// <summary> /// Constructor whose purpose is to set /// _engineTypeRepository variable. /// </summary> /// <param name="engineTypeRepository"> /// Existing IEngineTypeRepository object. /// </param> public EngineTypeLogic(IEngineTypeRepository engineTypeRepository) { _engineTypeRepository = engineTypeRepository; } /// <summary> /// Method whose purpose is to delete /// and existing EngineType object. /// </summary> /// <param name="engineType"> /// Existing EngineTypeModel object. /// </param> /// <returns> /// Returns true if the query is successfully executed /// otherwise returns false. /// </returns> public bool Delete(EngineTypeModel engineType) { return _engineTypeRepository.Delete(engineType) > 0 ? true : false; } /// <summary> /// Method whose purpose is to return all /// engine type records from the database. /// </summary> /// <returns> /// Returns all engine type objects as a IList /// of EngineTypeModel objects. /// </returns> public IList<EngineTypeModel> GetAll() { return _engineTypeRepository.GetAll(); } /// <summary> /// Method whose purpose is to insert /// a new EngineType record. /// </summary> /// <param name="engineType"> /// Newly created EngineTypeModel object. /// </param> /// <returns> /// Returns true if the query is successfully executed /// otherwise returns false. /// </returns> public bool Insert(EngineTypeModel engineType) { return _engineTypeRepository.Insert(engineType) > 0 ? true : false; } /// <summary> /// Method whose purpose is to update /// an existing EngineType record. /// </summary> /// <param name="engineType"> /// Existing EngineTypeModel object. /// </param> /// <returns> /// Returns true if the query is successfully executed /// otherwise returns false. /// </returns> public bool Update(EngineTypeModel engineType) { return _engineTypeRepository.Update(engineType) > 0 ? true : false; } } }
C
UTF-8
1,815
2.640625
3
[]
no_license
/* Black Rose Tavern in Qual'tor along the East Road. If Homer is not present (someone kills him) then players are not able to order drinks. See black bar for more details. (/players/daranath/qualtor/obj/black_bar.c) -Daranath */ #define tp this_player()->query_name() #include <ansi.h> inherit "room/room"; int t; reset(int arg){ if(!present("sign")) { move_object(clone_object("/players/daranath/qualtor/obj/black_bar.c"),this_object()); } if(!present("player")) { move_object(clone_object("/obj/go_player.c"),this_object()); } if(!present("homer")) { move_object(clone_object("/players/daranath/qualtor/mon/homer.c"),this_object()); } if(!arg){ set_light(1); short_desc= (BLK+BOLD+"City of Qual'tor "+NORM+"(Black Rose Tavern)"); long_desc= "A large hearth set in the western wall warms the Black Rose Tavern\n"+ "no matter what time of year it is. The walls of the establishment\n"+ "are a dark red color, giving the tavern its name. The same dark\n"+ "wood forms a long bar along the far wall, a sign post behind it\n"+ "listing the various beverages for sale.\n"; items=({ "hearth","A large stone hearth warms the tavern", "wall","The dark red walls give the tavern a rosy atmosphere", "walls","The walls in the tavern are made of a dark red wood", "bar","The bar runs along the northern side of the tavern, several\n"+ "barstools lined up in front of it. A large sign on the wall\n"+ "lists stuff you can order here", }); dest_dir=({ "/players/daranath/qualtor/east_road2.c","south", }); } } init() { ::init(); add_action("search","search"); } search() { write("You find nothing of interest about the Black Rose Tavern.\n"); say(tp +" searches the area\n"); return 1; }
Markdown
UTF-8
6,773
2.796875
3
[ "MIT" ]
permissive
--- layout: post title: "백준 3190 뱀" subtitle: "" categories: ps tags: ps comments: true date: 2021-03-31 19:35:00 -0400 --- [백준 3190 뱀](boj.kr/3190) 문제를 풀면서 든 생각, 느낀점을 모두 기록해보려고 한다. ### 문제파악단계 - 보드의 상하좌우 끝에 벽이 있다. 0행, n-1행, 0열, n-1열은 모두 벽처리를 하려고 했는데, 테케 1번과 부딪혔다. 질문검색에서 찾음 (https://www.acmicpc.net/board/view/48201) ### 코드 작성 단계 bam 의 자료구조를 Node를 담은 deque로 설정했다. 이 부분에서 겪은 시행착오는, deque.contains(new Node(nx,ny)) 함수를 써서 같은 좌표를 가진 노드가 있는지 체크하는 포문을 작성했는데 저렇게 되면 기존에 뱀의 몸통 중 한 좌표가 (1,2)인 노드가 힙 1000번 주소에 저장되어있고, 새로 만든 Node 객체는 (1,2)라고 하더라도 전혀 다른 힙 공간에 배치될 것이다. 그래서 contains를 iterator로 일일이 검색하도록 고쳤다. ### 갈무리 단계 사과를 먹었으면 0으로 갱신해줘야하는데 그 부분을 놓쳤다. 이건 질문검색에서 테케모음으로 찾았다. (https://www.acmicpc.net/board/view/56469) 오늘도 스터디원들에게 감사함을 남기며~~ 좋은 하루 되세요. 자아성찰 : 테케로 문제를 깎아나가고, 디버깅으로 해결하는 문제가 너무 많다. 이런 식이면 테케가 공개되지 않는 프로그래머스 문제는 너무 힘든데.. 앞으로 더 갈고 닦아야겠다. ㅎㅇㅌ ```java package boj; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; // 종료조건 벽 또는 자기자신의 몸과 부딪히면 게임이 끝난다. // 보드의 상하좌우 끝에 벽이 있다. ( 범위 밖에 벽이 있다는 뜻) //(1,1)부터 시작 //'먼저 뱀은 몸길이를 늘려' 사과가 있으면 그대로, 없으면 꼬리비움 public class std0331b3190뱀 { static int N, K, L, sec, nextDir, dir = 1; static int[][] map; static ArrayList<Info> list = new ArrayList<>(); // static int[] dx = {0, 0, 1, 0, -1}; static int[] dy = {0, 1, 0, -1, 0}; //우하좌상 처음에 우, D들어오면 +1 시켜서 하, L들어오면 -1 상. cnt 모듈러 static Info info = new Info(); //dir 1,2,3,4 우,하,좌,상 static ArrayDeque<Node> bam = new ArrayDeque<>(); static boolean flag = true; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); //보드크기 N*N [2,100] map = new int[N + 1][N + 1]; K = Integer.parseInt(br.readLine()); //사과개수 K [0,100] StringTokenizer st = null; int a, b; for (int i = 0; i < K; i++) { //사과위치 st = new StringTokenizer(br.readLine()); a = Integer.parseInt(st.nextToken()); b = Integer.parseInt(st.nextToken()); map[a][b] = 1; //사과 1, 벽 -1 } L = Integer.parseInt(br.readLine()); //방향전환 L 범위는 [1,100] for (int i = 0; i < L; i++) { st = new StringTokenizer(br.readLine()); a = Integer.parseInt(st.nextToken()); char ch = st.nextToken().charAt(0); list.add(new Info(a, ch)); } bam.add(new Node(1, 1)); //(1,1) 부터 우방향 시작 pollInfo(); System.out.println(sec); } static void func() { //dir고정 while (true) { //시작 : 0초부터 info시간까지. //널체크? if (bam.isEmpty()) { flag = false; return; } Node node = bam.peekFirst(); //머리좌표 int nx = node.x + dx[dir]; int ny = node.y + dy[dir]; if (nx < 1 || ny < 1 || nx > N || ny > N) { //보드는 1부터 N까지 좌표 //범위밖. 종료조건. 현재 시간 출력하고 return. sec++; flag = false; return; } Node newnode = new Node(nx, ny); Iterator<Node> iterator = bam.iterator(); while (true) { if (iterator.hasNext()) { Node tmpnode = iterator.next(); if(tmpnode.x == nx && tmpnode.y == ny) { flag = false; break; } } else break; } if (!flag){ sec++; return; } bam.addFirst(newnode); //머리에 새노드(nx,ny)를 추가하면 자연스레 이전노드(node.x,node.y)는 뱀의 두번째노드가 되고 // peekLast는 꼬리가 됨. = 사과먹은 것과 동일 if (map[nx][ny] == 0) { //사과없으면 새노드 nx,ny를 머리에 넣고 //이전의 꼬리는 지워야함 bam.removeLast(); }else if(map[nx][ny] ==1 ){ map[nx][ny]=0; } sec++; //시간증가 if (sec == info.x) return; //다음 이동정보로 가야하므로 , 상위 함수스택에 있는 pollinfo로 감 } } static void pollInfo() { for (int i = 0; i < list.size(); i++) { info = list.get(i);// info.x; 시간 info.c; 방향 func(); if (!flag) return; if (info.c == 'D') { if (dir == 4) dir = 1; else dir++; } else { //L이면 if (dir == 1) dir = 4; else dir--; } } func(); } static class Node { int x; int y; Node(){} Node(int x, int y) { this.x = x; this.y = y; } } static class Info { int x; char c; Info() { } Info(int x, char c) { this.x = x; this.c = c; } } } /* 자료구조 1. 이동 정보가 담긴 큐 자료구조 2. 뱀객체. 계속 길어짐. 뱀이 가져야할 정보 : 자기자신의 좌표. -> 사이즈가 곧 길이 -머리가 닿은 곳에 사과가 있으면, 이전에 지나온 좌표를 자기꼬리에 추가함(여기서 contains 확인-부딪히면 종료조건) -머리가 닿은 곳이 범위밖이면 종료 방향 전환 1,2,3,4 = 우,하,좌,상 배열에 담겨있고 D라서 +1해야하는데 -> if(cnt==4) cnt=1; else cnt++; L이면 -1해야하는데 -> if(cnt==1) cnt=4; else cnt--; dir=cnt; */ ```
C++
UTF-8
877
2.921875
3
[]
no_license
#include <algorithm> #include <iostream> #include <list> #include <numeric> #include <random> #include <vector> using namespace std; int main() { vector<int> data(20); iota(begin(data), end(data), 1); copy(cbegin(data), cend(data), ostream_iterator<int>(cout, " ")); cout << '\n'; random_device seeder; const auto seed = seeder.entropy() ? seeder() : time(nullptr); default_random_engine generator( static_cast<default_random_engine::result_type>(seed)); const size_t numberOfSamples = 5; vector<int> sampledData(numberOfSamples); for (size_t i = 0; i < 10; ++i) { sample(cbegin(data), cend(data), begin(sampledData), numberOfSamples, generator); copy(cbegin(sampledData), cend(sampledData), ostream_iterator<int>(cout, " ")); cout << '\n'; } return 0; }
Shell
UTF-8
522
2.703125
3
[]
no_license
pkgname=stlphallus-font pkgver=1.0 pkgrel=1 pkgdesc="Merged the fonts stlarch, uushi and lemon (https://github.com/phallus/fonts). " pkgurl="https://github.com/phallus/fonts, http://sourceforge.net/projects/stlarchfont/" arch=('any') depends=('fontconfig' 'xorg-font-utils') source=('git+https://github.com/Ploppz/fonts') md5sums=('SKIP') install="$pkgname.install" package() { install -d "$pkgdir/usr/share/fonts/misc" cp -dpr --no-preserve=ownership "$srcdir/fonts/stlphallus.pcf" "$pkgdir/usr/share/fonts/misc/" }
Java
UTF-8
833
3.515625
4
[]
no_license
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int testCases = sc.nextInt(); while(testCases --> 0){ int n = sc.nextInt(); int[][] arr = new int[n][n]; for(int row = 0;row < n;row++){ for(int col = 0;col < row + 1;col++){ arr[row][col] = sc.nextInt(); } } for(int row = n-2;row >= 0;row--){ for(int col = 0;col<row+1;col++){ arr[row][col] += Math.max(arr[row+1][col],arr[row+1][col+1]); } } System.out.println(arr[0][0]); } } }
Ruby
UTF-8
1,258
3.21875
3
[]
no_license
# encoding : utf-8 # Will mark every specified directory for synchronization with specified target # This will add the codename of the target in a .syncinfo file in the directory # Usage : # $ mark-for-sync ./dir1 [./dir2] sansa require_relative "syncinfo" class MarkForSync class Error < StandardError; end class ArgumentError < Error; end def initialize(*args) parse_args(*args) end # Make sure every arg is correct def parse_args(*args) # At least directory and target if args.size == 0 raise MarkForSync::ArgumentError, "You need at least a target", "" end # Current dir is default dir if args.size == 1 args.unshift('.') end # Last argument must be a target (ie. a custom name, not a filepath) if File.exists?(args[-1]) raise MarkForSync::ArgumentError, "Last argument must be a target (ie. jukebox, sansa, etc)", "" end @target = args[-1] # Keep only existing directories @directories = [] args[0..-2].each do |dir| dir = File.expand_path(dir) next unless File.exists?(dir) next unless File.directory?(dir) @directories << dir end end # Will mark all specified directories for synchronization def run @directories.each do |dir| Syncinfo.new(dir).add_target(@target) end end end
Shell
UTF-8
354
2.6875
3
[]
no_license
#!/bin/bash echo "may need to wait a few minutes for container to create ... " export -n QUAY_URL=`oc get route |grep ".com" | awk '{print $2}'` echo $QUAY_URL echo "consult: deploy_red_hat_quay_on_openshift_with_quay_operator manual" echo "in section 5.11 for default username and password" echo "also in section 5.11 - changing the default values"
C#
UTF-8
2,341
3.125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ParallelApi { class ExeParallel { private static string batCmd = @"dir"; private static string[] paths = new string[] { @"C:\temp", @"C:\tmp" }; private void DoWorkSequentially(string[] pathStrs) { Console.WriteLine("Start DoWorkSequentially"); Stopwatch stopWatch = Stopwatch.StartNew(); for (int i = 0; i < pathStrs.Length; i++) { Console.WriteLine(ExeConsole.Run(batCmd, pathStrs[i], 30000)); Console.WriteLine("Execute iteration i = " + i.ToString() + " using " + pathStrs[i]); } stopWatch.Stop(); Console.WriteLine("Execution time(ms) is " + stopWatch.ElapsedMilliseconds.ToString()); Console.WriteLine(); } private void DoWorkParallelFor(string[] pathStrs) { Console.WriteLine("Start DoWorkParallelFor"); Stopwatch stopWatch = Stopwatch.StartNew(); Parallel.For(0, pathStrs.Length, (i) => { Console.WriteLine(ExeConsole.Run(batCmd, pathStrs[i], 30000)); Console.WriteLine("Execute iteration i = " + i.ToString() + " using " + pathStrs[i]); }); stopWatch.Stop(); Console.WriteLine("Execution time(ms) is " + stopWatch.ElapsedMilliseconds.ToString()); Console.WriteLine(); } private void DoWorkParallelForEach(string[] pathStrs) { Console.WriteLine("Start DoWorkParallelForEach"); Stopwatch stopWatch = Stopwatch.StartNew(); Parallel.ForEach(pathStrs, path => { Console.WriteLine(ExeConsole.Run(batCmd, path, 30000)); Console.WriteLine("Execute using " + path); }); stopWatch.Stop(); Console.WriteLine("Execution time(ms) is " + stopWatch.ElapsedMilliseconds.ToString()); Console.WriteLine(); } public void DoAll() { DoWorkSequentially(paths); DoWorkParallelFor(paths); DoWorkParallelForEach(paths); } } // end class ExeParallel }
JavaScript
UTF-8
1,773
4.03125
4
[]
no_license
/** * Created by liguohua on 2016/10/14. */ /** *对象的每个属性都有一个描述对象(Descriptor),用来控制该属性的行为。 * Object.getOwnPropertyDescriptor方法可以获取该属性的描述对象。 */ { let obj = {foo: 123}; let r = Object.getOwnPropertyDescriptor(obj, 'foo'); console.info(r); // { // value: 123, // writable: true, // enumerable: true, // configurable: true // } /** * ES5有三个操作会忽略enumerable为false的属性 for...in循环:只遍历对象自身的和继承的可枚举的属性 Object.keys():返回对象自身的所有可枚举的属性的键名 JSON.stringify():只串行化对象自身的可枚举的属性 ES6新增了一个操作Object.assign(),会忽略enumerable为false的属性,只拷贝对象自身的可枚举的属性。 */ } /** * 实际上,引入enumerable的最初目的,就是让某些属性可以规避掉for...in操作。 比如,对象原型的toString方法,以及数组的length属性,就通过这种手段,不会被for...in遍历到。 ES6规定,所有Class的原型的方法都是不可枚举的。 */ { let r = Object.getOwnPropertyDescriptor(Object.prototype, 'toString').enumerable; console.info(r);// false r = Object.getOwnPropertyDescriptor([], 'length').enumerable; console.info(r);// false r = Object.getOwnPropertyDescriptor(class { foo() { } }.prototype, 'foo').enumerable; console.info(r);// false } /** *总的来说,操作中引入继承的属性会让问题复杂化,大多数时候,我们只关心对象自身的属性。 * 所以,尽量不要用for...in循环,而用Object.keys()代替。 */
Java
UTF-8
855
2.5
2
[]
no_license
package com.epam.test_generator.dto; import java.util.List; /** * This DTO is a list of {@link ValidationErrorDTO}. It's used for retrieving and sending validation errors' information * respectively from and to API. */ public class ValidationErrorsDTO { private Boolean isError = true; private String type; private List<ValidationErrorDTO> errors; public ValidationErrorsDTO() { } public Boolean getError() { return isError; } public void setError(Boolean error) { isError = error; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<ValidationErrorDTO> getErrors() { return errors; } public void setErrors(List<ValidationErrorDTO> errors) { this.errors = errors; } }
JavaScript
UTF-8
2,619
3.078125
3
[]
no_license
$(document).ready(function() { $("form#info").submit(function(event) { event.preventDefault(); //collect variables var age = parseInt($("#age").val()); var gender = $("#gender").val(); var color = $("input:radio[name=color]:checked").val(); var cuisine = $("input:radio[name=cuisine]:checked").val(); if (age < 18) { alert("You are too young for this site"); } else { if (gender === 'male') { // at this point, we know we have a male, over 18 if (color === 'light') { // any code in here knows that we have a male, over 18 whose favorite color is a light color if (cuisine === 'american') { // go eat american food! $("#jennifer").show(); } else if (cuisine === 'chinese') { // go eat chinese food, only if american was not chosen. ("#angelina").show(); } else if (cuisine === 'mediterranean') { // go eat mediterranean, ONLY if american AND chinese were not chosen. $("#angelina").show(); } else { // go eat latin, only if none of the other options were chosen. // here, we know over 18, male, light, latin food $("#jennifer").show(); } } else { // male, over 18, likes dark colors. if (cuisine === 'american' || cuisine === 'chinese') { //male, over 18, likes dark colors, eats american or chinese $("#lopez").show(); } else if (cuisine === 'mediterranean') { //male male, over 18, likes dark colors, eats mediterranean ONLY if American and chinese are not chosen $("#lopez").show(); } else { // over 18, male, dark, latin food. ("#angelina").show(); } } } else { // female, over 18. if (color === 'light'){ //female, over 18, light colors if (cuisine === 'mediterranean' || cuisine === 'latin') { //female, over 18, light, likes mediterranean OR latin NOT the others $("#brad").show(); } else if (cuisine === 'american') { //female, over 18, light, likes american $("#will").show(); } else { //female, over 18, light, likes chinese $("#chow").show(); } } else { //female, over 18, dark colors if (cuisine === 'american' || cuisine === 'chinese') { //female, over 18, dark, likes american and chinese $("#chow").show(); } else if (cuisine === 'latin') { //female, over 18, dark, likes latin $("#will").show(); } else { //femal, over 18, dark, likes mediterranean $("#brad").show(); } } } } }); });
Python
UTF-8
642
2.984375
3
[]
no_license
class Person: def __init__(self,id,immune_status,status): self.id=id self.immune_status=immune_status self.status=status self.cont=3 def get_id(self): return self.id def get_immune_status(self): return str(self.immune_status) def get_status(self): return str(self.status) def get_cont(self): return self.cont def set_cont(self,value): self.cont=value def set_status(self,value): self.cont=3 self.status=value def set_immune_status(self,value): self.immune_status=value
C++
WINDOWS-1251
3,872
3.625
4
[]
no_license
#include<iostream> #include <ctime> #include <stdlib.h> #include <string> #include <vector> #include <fstream> using namespace std; struct person { string surname; string name; string patronymic; string position; int age; double wages; }; vector <person> mas; int razmer = 0; void Read() { system("pause"); system("cls"); int n; cout << " ? "; cin >> n; razmer = n; person temp; for (int i = 0; i<n; i++) { cout << " : , , , , , . " << endl; cout << " , . " << endl; cout << " " << (i + 1) << endl; cout << " : "; cin >> temp.surname; cout << " : "; cin >> temp.name; cout << " : "; cin >> temp.patronymic; cout << " : "; cin >> temp.position; cout << " : "; cin >> temp.age; cout << " : "; cin >> temp.wages; mas.push_back(temp); system("cls"); } } void ToFail(vector<person> &mas, string &name) { std::ofstream fs(name, std::ios::binary); if (!fs.is_open()) { std::cout << " " << name << " "; return; } int size = mas.size(); cout << "- : " << size << endl; if (size == 0) { cout << " ." << endl; return; } else for (int i = 0; i<size; i++) { fs << mas[i].surname << " " << mas[i].name << " " << mas[i].patronymic << " " << mas[i].position << " " << mas[i].age << " " << mas[i].wages << endl; } fs.close(); } void Display(string &name, int&razmer) { person tmp; ifstream fs(name, ios::binary); if (!fs.is_open()) { std::cout << " " << name << " "; return; } for (int i = 0; i < razmer; i++) { fs >> tmp.surname; fs >> tmp.name; fs >> tmp.patronymic; fs >> tmp.position; fs >> tmp.age; fs >> tmp.wages; cout << "===========================" << endl; cout << " " << (i + 1) << endl << ": " << tmp.surname << endl << " : " << tmp.name << endl << " : " << tmp.patronymic << endl << " : " << tmp.position << endl << " : " << tmp.age << endl << " : " << tmp.wages << "\n"; if (fs.eof())break; } fs.close(); } void Delet(string &name, string name2, int&razmer) { string fam; cout << " : "; cin >> fam; cout << endl; person tmp; ifstream fs(name, ios::binary); if (!fs.is_open()) { std::cout << " " << name << " "; return; } for (int i = 0; i < razmer; i++) { fs >> tmp.surname; fs >> tmp.name; fs >> tmp.patronymic; fs >> tmp.position; fs >> tmp.age; fs >> tmp.wages; if (fs.eof())break; } fs.close(); } int main() { srand((unsigned)time(NULL)); setlocale(LC_ALL, "Russian"); string name, name2, fam; Read(); cout << " : "; cin >> name; cout << endl; ToFail(mas, name); Display(name, razmer); cout << " : "; cin >> name; cout << endl; Delet(name,name2,razmer); system("pause"); return 0; }
Java
UTF-8
2,682
2.296875
2
[]
no_license
package applusiana.apkvolume; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity /*implements View.OnClickListener*/ { EditText etPanjang, etLebar, etTinggi, etVolume; Button btnHitung, btnHapus, btnKeluar; /*private static final int TIME_DELAY = 2000; private static long back_pressed;*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etPanjang = findViewById(R.id.etPanjang); etLebar = findViewById(R.id.etLebar); etTinggi = findViewById(R.id.etTinggi); etVolume = findViewById(R.id.etVolume); btnHitung = findViewById(R.id.btnHitung); btnHitung.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double panjang = Double.valueOf(etPanjang.getText().toString()); double lebar = Double.valueOf(etLebar.getText().toString()); double tinggi = Double.valueOf(etTinggi.getText().toString()); double volume = panjang * lebar * tinggi; /*double volume = Double.valueOf(etVolume.getText().toString());*/ etVolume.setText(String.valueOf(volume)); } }); btnHapus = findViewById(R.id.btnHapus); btnHapus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etPanjang.setText(""); etTinggi.setText(""); etLebar.setText(""); etVolume.setText(""); } }); btnKeluar = findViewById(R.id.btnKeluar); btnKeluar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } /* @Override public void onBackPressed(){ if (back_pressed + TIME_DELAY > System.currentTimeMillis()){ super.onBackPressed(); }else { Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show(); } back_pressed = System.currentTimeMillis(); }*/ }); } /*@Override public void onClick(View v) { }*/ }
JavaScript
UTF-8
2,795
2.640625
3
[]
no_license
import React, { Component } from 'react'; import api from '../../services/todoService'; import "./UpdateTodo.css"; class UpdateTodo extends Component { constructor(props) { super(props); this.state = { name: "", description: "", }; } async componentDidUpdate(oldProps) { const newProps = this.props if(oldProps.todoid !== newProps.todoid ) { const p1 = document.getElementById("update-p1"); const p2 = document.getElementById("update-p2"); await this.setState({name: this.props.todoname, description: this.props.tododescription}); p1.textContent = this.state.name; p2.textContent = this.state.description; } } clearParagraph(id) { const p1 = document.getElementById(id); p1.textContent = ""; } setParagraphState() { const p1 = document.getElementById("update-p1"); const p2 = document.getElementById("update-p2"); this.setState({name: p1.textContent, description: p2.textContent }); } async submit() { await this.setParagraphState(); if (this.state.name.length > 50 || this.state.name.length === 0 || this.state.description.length === 0) { alert("Must be between 0 and 50 characters") } else { this.updateTodo(); this.closeModal(); } } closeModal() { const elem = document.getElementById("modal-update"); var instance = window.M.Modal.getInstance(elem); instance.close(); } async updateTodo() { const user = this.props.user; const todoid = this.props.todoid; const defaultJson = {userId: user.sub, todoName: this.state.name, description: this.state.description, color: this.props.color}; await api.update(todoid, defaultJson); } render() { return ( <div id="modal-update" className="modal modal-update"> <h1 className="modal-title" style={{paddingTop: "5vh"}}>Name:</h1> <p onClick={() => this.clearParagraph("update-p1")} id="update-p1" contenteditable="true">Edit me to give a name for your to-do note!</p> <h1 className="modal-title">Description:</h1> <p onClick={() => this.clearParagraph("update-p2")} id="update-p2" contenteditable="true">Edit me to write a description for your to-do note!</p> <button onClick={() => this.submit()} className="submit-btn"><i className="far fa-check-circle fa-1x confirm-icon"></i></button> </div> ); } } export default UpdateTodo;
Ruby
UTF-8
745
2.59375
3
[ "MIT" ]
permissive
module Sword class Log < ActiveSupport::Logger attr_reader :start_time, :datetime_format, :output_level def initialize(*args) @start_time = Time.now @datetime_format = '%Y-%m-%d %H:%M:%S' @output_level = args[0] # reset the first argument to the log file for the super call args[0] = 'log/sword.log' super self.formatter = proc do |severity, datetime, progname, msg| "#{datetime.strftime(@datetime_format)} #{severity} #{msg}\n" end self.info "Packager started" end def close end_time = Time.now duration = (end_time - @start_time) / 1.minute self.info "Duration: #{duration}" self.info "Packager ended" super end end end
Python
UTF-8
244
3.921875
4
[]
no_license
color = input("Enter the color : ") pronun_color = input("Enter the pronun_color : ") celebrity = input("Enter the celebrity : ") print("Roses are " + color) print(pronun_color + " are grey") print("My favourite celebrity is " + celebrity)
C++
UTF-8
305
2.65625
3
[]
no_license
#ifndef RECTANGULO_H #define RECTANGULO_H #include "Figura.h" class Rectangulo : public Figura { public: Rectangulo(int x, int y, int base, int altura); ~Rectangulo(); double obtenerSuperficie() const; private: int x, y, base, altura; }; #endif // RECTANGULO_H
C#
UTF-8
4,062
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; namespace Day25 { internal class Program { public static void Main(string[] args) { int[] tape = new int[100000]; int currentPosition = 50000; char state = 'A'; for(long i = 0; i < 12586542; i++) { if (state == 'A') { int currentValue = tape[currentPosition]; if (currentValue == 0) { tape[currentPosition] = 1; currentPosition++; state = 'B'; } if (currentValue == 1) { tape[currentPosition] = 0; currentPosition--; state = 'B'; } continue; } if (state == 'B') { int currentValue = tape[currentPosition]; if (currentValue == 0) { tape[currentPosition] = 0; currentPosition++; state = 'C'; } if (currentValue == 1) { tape[currentPosition] = 1; currentPosition--; state = 'B'; } continue; } if (state == 'C') { int currentValue = tape[currentPosition]; if (currentValue == 0) { tape[currentPosition] = 1; currentPosition++; state = 'D'; } if (currentValue == 1) { tape[currentPosition] = 0; currentPosition--; state = 'A'; } continue; } if (state == 'D') { int currentValue = tape[currentPosition]; if (currentValue == 0) { tape[currentPosition] = 1; currentPosition--; state = 'E'; } if (currentValue == 1) { tape[currentPosition] = 1; currentPosition--; state = 'F'; } continue; } if (state == 'E') { int currentValue = tape[currentPosition]; if (currentValue == 0) { tape[currentPosition] = 1; currentPosition--; state = 'A'; } if (currentValue == 1) { tape[currentPosition] = 0; currentPosition--; state = 'D'; } continue; } if (state == 'F') { int currentValue = tape[currentPosition]; if (currentValue == 0) { tape[currentPosition] = 1; currentPosition++; state = 'A'; } if (currentValue == 1) { tape[currentPosition] = 1; currentPosition--; state = 'E'; } continue; } } long count = tape.Count(w => w == 1); Console.WriteLine(count); } } }
Python
UTF-8
1,781
3.078125
3
[ "MIT" ]
permissive
import itertools import re import sys def solve(data): data = data.splitlines() assert len(data) == 4 prop = [] for line in data: p = line[line.find(':') + 2:] prop.append(list(map(lambda s: int(s.split()[1]), p.split(', ')))) total_score1 = 0 total_score2 = 0 for i in range(101): for j in range(101 - i): for k in range(101 - i - j): h = 100 - i - j - k idx = [i, j, k, h] cap = max(0, sum(prop[p][0] * n for p, n in enumerate(idx))) dur = max(0, sum(prop[p][1] * n for p, n in enumerate(idx))) fla = max(0, sum(prop[p][2] * n for p, n in enumerate(idx))) tex = max(0, sum(prop[p][3] * n for p, n in enumerate(idx))) cal = max(0, sum(prop[p][4] * n for p, n in enumerate(idx))) score = cap * dur * fla * tex total_score1 = max(score, total_score1) if cal == 500: total_score2 = max(score, total_score2) print(total_score1) print(total_score2) ######################################################################## # SETUP STUFF # ######################################################################## actual_input = r""" Sprinkles: capacity 5, durability -1, flavor 0, texture 0, calories 5 PeanutButter: capacity -1, durability 3, flavor 0, texture 0, calories 1 Frosting: capacity 0, durability -1, flavor 4, texture 0, calories 6 Sugar: capacity -1, durability 0, flavor 0, texture 2, calories 8 """.strip() if len(sys.argv) > 1: with open(sys.argv[1], 'r') as f: file_input = f.read().strip() solve(file_input) else: solve(actual_input)
Java
UTF-8
11,354
3.390625
3
[]
no_license
package pets_amok; import java.util.ArrayList; import java.util.Random; public class VirtualPetShelter { static Random rand = new Random(); public static ArrayList<VirtualPet> petArrayList = new ArrayList<VirtualPet>(); public static void generatePets() { VirtualPet pet1 = new Cat(rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), "Kyle the Cat", "Sweet, Sly, Smooth", rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10)); VirtualPet pet2 = new Dog(rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), "Dusty the Dog", "Fluffy, Furry, Flamboyant", rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), rand.nextInt(10)); VirtualPet pet3 = new RoboticDog(rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), "Ricky the Robotic Dog", "Cool, Calm, Cunning", rand.nextInt(10)); VirtualPet pet4 = new RoboticCat(rand.nextInt(10), rand.nextInt(10), rand.nextInt(10), "Ronnie the Robotic Cat", "Talkative, Territorial, Tame", rand.nextInt(10)); petArrayList.add(pet1); petArrayList.add(pet2); petArrayList.add(pet3); petArrayList.add(pet4); } public static void showPets() { for (VirtualPet petList : petArrayList) { if (petList instanceof Natural) { System.out.println("We have: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); System.out.println("Their boredom level is: " + petList.getBoredomLevel()); System.out.println("Their tiredness level is: " + petList.getTirednessLevel()); System.out.println("Their overall health level is: " + petList.getOverallHealth()); System.out.println("Their hunger level is: " + ((Natural) petList).getHungerLevel()); System.out.println("Their thirst level is: " + ((Natural) petList).getThirstLevel()); System.out.println("Their waste level is: " + ((Natural) petList).getWasteLevel()); } if (petList instanceof Cat) { System.out.println("Their litter box cleanliness level is: " + ((Cat) petList).getLitterBoxCleanliness()); } if (petList instanceof Dog) { System.out.println("Their cage cleanliness level is: " + ((Dog) petList).getCageCleanlinessLevel()); } if (petList instanceof Robotic) { System.out.println("We have: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); System.out.println("Their boredom level is: " + petList.getBoredomLevel()); System.out.println("Their tiredness level is: " + petList.getTirednessLevel()); System.out.println("Their oil level is: " + ((Robotic) petList).getOilLevel()); System.out.println("Their overall health level is: " + petList.getOverallHealth()); } } } public static void petNames() { for (VirtualPet petList : petArrayList) { System.out.println("We have: " + petList.getName()); } } public static void naturalPetNames() { for (VirtualPet petList : petArrayList) { if (petList instanceof Natural) { System.out.println("We have: " + petList.getName()); } } } public static void roboticPetNames() { for (VirtualPet petList : petArrayList) { if (petList instanceof Robotic) { System.out.println("We have: " + petList.getName()); } } } public static void gamePlay() { while (true) { for (int i = 0; i < petArrayList.size(); i++) { if ((petArrayList.get(i).getOverallHealth() < 15)) { Application.whatActivity(); } } gameOver(); } } public static void gameOver() { for (int i = 0; i < petArrayList.size(); i++) { if (petArrayList.get(i).getOverallHealth() >= 15) { System.out.println(petArrayList.get(i).getName() + " had too low of health and ran away. You lose. Game Over!"); System.exit(0); } } } public static void adoptPet(String name) { for (int i = 0; i < petArrayList.size(); i++) { if (petArrayList.get(i).getName().equals(name)) { System.out.println("You chose to adopt: " + petArrayList.get(i).getName()); System.out.println("Their description is: " + petArrayList.get(i).getNameDescription()); petArrayList.remove(i); } } } public static void adoptPet() { for (int i = 0; i < petArrayList.size(); i++) { petArrayList.remove(i); } } public static void intakePet(VirtualPet pet) { petArrayList.add(pet); } public static void feedPet(String name) { for (VirtualPet petList : petArrayList) { if (petList.getName().equals(name)) { if (petList instanceof Natural) { System.out.println("You chose to feed: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((Natural) petList).feed(); } if (petList instanceof Robotic) { System.out.println("You cannot feed a robotic animal. Please choose another option."); } } } } public static void feedPet() { for (VirtualPet petList : petArrayList) { if (petList instanceof Natural) { ((Natural) petList).feed(); } } } public static void waterPet(String name) { for (VirtualPet petList : petArrayList) { if (petList.getName().equals(name)) { if (petList instanceof Natural) { System.out.println("You chose to give water to: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((Natural) petList).water(); } if (petList instanceof Robotic) { System.out.println("You cannot give water to a robotic animal. Please choose another option."); } } } } public static void waterPet() { for (VirtualPet petList : petArrayList) { if (petList instanceof Natural) { ((Natural) petList).water(); } } } public static void oilPet(String name) { for (VirtualPet petList : petArrayList) { if (petList.getName().equals(name)) { if (petList instanceof Natural) { System.out.println("You cannot give oil to a natural animal. Please choose another option."); } if (petList instanceof Robotic) { System.out.println("You chose to give oil to: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((Robotic) petList).oiling(); } } } } public static void oilPet() { for (VirtualPet petList : petArrayList) { if (petList instanceof Robotic) { ((Robotic) petList).oiling(); } } } public static void walkPet(String name) { for (VirtualPet petList : petArrayList) { if (petList.getName().equals(name)) { if (petList instanceof Cat) { System.out.println("You chose to let out: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((Cat) petList).letOut(); } if (petList instanceof Dog) { System.out.println("You chose to walk: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((Dog) petList).walk(); } if (petList instanceof RoboticCat) { System.out.println("You chose to let out: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((RoboticCat) petList).letOut(); } if (petList instanceof RoboticDog) { System.out.println("You chose to walk: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((RoboticDog) petList).walk(); } } } } public static void walkPet() { for (VirtualPet petList : petArrayList) { if (petList instanceof Cat) { ((Cat) petList).letOut(); } if (petList instanceof Dog) { ((Dog) petList).walk(); } if (petList instanceof RoboticCat) { ((RoboticCat) petList).letOut(); } if (petList instanceof RoboticDog) { ((RoboticDog) petList).walk(); } } } public static void cleanPet(String name) { for (VirtualPet petList : petArrayList) { if (petList.getName().equals(name)) { if (petList instanceof Natural) { System.out.println("You chose to clean the cage of: " + petList.getName()); System.out.println("Their description is: " + petList.getNameDescription()); ((Natural) petList).cleanCage(); } if (petList instanceof Robotic) { System.out.println("Robotic animals do not have cages to clean. Please choose another option."); } } } } public static void cleanPet() { for (VirtualPet petList : petArrayList) { if (petList instanceof Natural) { ((Natural) petList).cleanCage(); } } } public static void playPet(String name) { for (int i = 0; i < petArrayList.size(); i++) { if (petArrayList.get(i).getName().equals(name)) { System.out.println("You chose to play with: " + petArrayList.get(i).getName()); System.out.println("Their description is: " + petArrayList.get(i).getNameDescription()); petArrayList.get(i).play(); } } } public static void playPet() { for (int i = 0; i < petArrayList.size(); i++) { petArrayList.get(i).play(); } } public static void letAnimalSleep() { for (int i = 0; i < petArrayList.size(); i++) { petArrayList.get(i).sleep(); } } public static void tick() { for (int i = 0; i < petArrayList.size(); i++) { petArrayList.get(i).tick(); } } }
C++
UTF-8
1,688
2.546875
3
[]
no_license
#include <Arduino.h> #include <ThingTime.h> #include <WiFiManager.h> void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("Entered config mode"); Serial.println(WiFi.softAPIP()); //if you used auto generated SSID, print it Serial.println(myWiFiManager->getConfigPortalSSID()); //entered config mode, make led toggle faster //ticker.attach(0.2, tick); } void handleNtpRequest(String choose) { String response = ""; if(choose.equals("init")) { ThingTime.setNtpTimeSubscriber(); } else if (choose.equals("get")) { Serial.print("Time: "); Serial.print(ThingTime.getDateTime()); Serial.print(", String: "); char textTime [50]; ThingTime.getTextDateTime(textTime); Serial.println(textTime); } else { response = "time-command no parameter found"; } Serial.println("Time-Command, "+response); //WifiHttpServer.send( 200, "text/html", response); //Returns the HTTP response } void setup() { Serial.begin(115200); //Initialisierung der seriellen Schnittstelle Serial.println(); Serial.println(); Serial.println("ThingTimeTest"); Serial.println("============"); Serial.println(); WiFiManager wm; wm.setAPCallback(configModeCallback); if (!wm.autoConnect()) { Serial.println("failed to connect and hit timeout"); //reset and try again, or maybe put it to deep sleep ESP.restart(); delay(1000); } //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); // ticker.detach(); //keep LED on // digitalWrite(LED, LOW); handleNtpRequest("init"); handleNtpRequest("get"); } void loop() { handleNtpRequest("get"); delay(10000); }
Markdown
UTF-8
855
3.640625
4
[]
no_license
# Memory-Allocation- I. Inputs : ====================== 1- User inputs holes sizes and starting addresses. 2- User inputs number of processes. 3- User inputs processes’ size (Ex: p0 size =100, p1 size = 50… etc). 4- User inputs the method of allocation (first fit or best fit). II. Scenario to be done: ============================ 1- Allocate all processes using allocation methodology. 2- De-Allocate a process ( The user choose a process to de-allocate, you should consider its space as a hole to be used later and add to it any neighboring holes) III. Output: ======================== Your output is the list of holes and allocated memory blocks (starting addresses and sizes) at each allocation step (Ex: initial state , after P0 allocation, after P1 allocation, after P2 swapped out P1 and is allocated instead of P1, … etc.)
Python
UTF-8
3,151
2.625
3
[]
no_license
import requests import json import base64 import os from dotenv import load_dotenv load_dotenv() clientid = os.getenv('Client_ID') clientsecret = os.getenv('Client_Secret') mePlaylistUrl = 'https://api.spotify.com/v1/me/playlists' playlistTraksUrl = 'https://api.spotify.com/v1/playlists/{playlist_id}/tracks' def refreshToken(): url = "https://accounts.spotify.com/api/token" params = { 'grant_type': 'refresh_token', 'refresh_token': getRefreshToken(), } authorization = base64.b64encode(bytes(clientid + ':' + clientsecret, 'utf-8')) response = requests.post(url, data=params, headers={'Authorization': 'Basic ' + authorization.decode('utf-8')}) print(f"REFRESH TOKEN: {response.json()}") credentials_json = getCredentials() for k,v in response.json().items(): credentials_json[k] = v with open('json/credentials.json', 'w') as outfile: json.dump(credentials_json, outfile) if response.status_code == 200: return True else: return False def getCredentials(): with open('json/credentials.json') as json_file: return json.load(json_file) def getAccessToken(): return getCredentials()['access_token'] def getTokenType(): return getCredentials()['token_type'] def getRefreshToken(): return getCredentials()['refresh_token'] def get(url, params={}, should_refresh_token=True): headers = {'Authorization': getTokenType() + ' ' + getAccessToken()} response = requests.get(url, data=params, headers=headers) if response.status_code == 200: print(f"GET: {response.json()}") return response.json() elif response.status_code == 401 and should_refresh_token: if refreshToken(): return get(url, params, headers) else: return {'Error': 'Something went wrong'} else: return {'Error': 'Something went wrong'} def getUserPlaylistsPaginated(items, url): if not url: return response_json = get(url) items += response_json['items'] getUserPlaylistsPaginated(items, response_json['next']) def getUserPlaylists(): items = [] getUserPlaylistsPaginated(items, mePlaylistUrl) return items def getUserPlaylistsTraks(playlists): for playlist in playlists: playlist['tracks_list'] = [] getUserPlaylistsTracksPaginated(playlist, playlistTraksUrl.format(playlist_id = playlist['id'])) print(playlist['id'] + ': ' + str(len(playlist['tracks_list'])) + ' ' + str(playlist['tracks']['total'])) def getUserPlaylistsTracksPaginated(playlist, url): if not url: return response_json = get(url) print(response_json) tracks_list = playlist['tracks_list'] tracks_list += response_json['items'] playlist['tracks_list'] = tracks_list getUserPlaylistsTracksPaginated(playlist, response_json['next']) def main_spoti_export(): playlists = getUserPlaylists() getUserPlaylistsTraks(playlists) with open('json/playlists.json', 'w') as outfile: json.dump(playlists, outfile) if __name__ == "__main__": main_spoti_export()
Shell
UTF-8
2,315
3.203125
3
[ "MIT" ]
permissive
#!/bin/bash echo "Starting ... " &> ./setup.log echo -e "\e[32m#### Load environment file aka config...\e[0m" 2>&1 | tee ./setup.log source /usr/local/share/team-development-server/.env >> ./setup.log sudo systemctl start docker>> ./setup.log echo -e "\e[32m#### Create backup and repo directories if not exit...\e[0m" 2>&1 | tee ./setup.log sudo mkdir --p $TDS_BACKUP_DIR >> ./setup.log sudo mkdir --p $TDS_REPO_DIR >> ./setup.log sudo chown -R $TDS_GITEA_USER_UID:$TDS_GITEA_USER_GID $TDS_REPO_DIR >> ./setup.log echo -e "\e[32m#### Generate wildcard certificate...\e[0m" 2>&1 | tee ./setup.log sudo mkdir --p /var/team-development-server/services/traefik/certs sudo openssl genrsa -out "/var/team-development-server/services/traefik/certs/wildcard.key" 2048 >> ./setup.log sudo openssl req -new -subj "/C=${TDS_CERT_COUNTRY}/ST=${TDS_CERT_STATE}/O=${TDS_CERT_COMPANY_NAME}/localityName=${TDS_CERT_CITY}/commonName=${TDS_CERT_DOMAIN}/organizationalUnitName=${TDS_CERT_DOMAIN}/emailAddress=${TDS_CERT_EMAIL}" -key "/var/team-development-server/services/traefik/certs/wildcard.key" -out "/var/team-development-server/services/traefik/certs/wildcard.csr" >> ./setup.log sudo openssl x509 -req -days 365 -in "/var/team-development-server/services/traefik/certs/wildcard.csr" -signkey "/var/team-development-server/services/traefik/certs/wildcard.key" -out "/var/team-development-server/services/traefik/certs/wildcard.crt" >> ./setup.log # Converting sudo openssl pkcs12 -export -name "/var/team-development-server/services/traefik/certs/wildcard" -out /var/team-development-server/services/traefik/certs/wildcard.pfx -inkey /var/team-development-server/services/traefik/certs/wildcard.key -in /var/team-development-server/services/traefik/certs/wildcard.crt -password pass:${TDS_CERT_PASSWORD} >> ./setup.log sudo openssl x509 -inform PEM -in /var/team-development-server/services/traefik/certs/wildcard.crt -outform DER -out /var/team-development-server/services/traefik/certs/wildcard.der >> ./setup.log echo -e "\e[32m#### Create empty log files...\e[0m" 2>&1 | tee ./setup.log echo -e "\e[32m#### Spin up Containers...\e[0m" 2>&1 | tee ./setup.log sudo docker-compose -f /usr/local/share/team-development-server/docker-compose.yml up -d echo -e "\e[32m#### FINISH ! ##\e[0m" 2>&1 | tee ./setup.log
Java
UTF-8
3,112
2.265625
2
[]
no_license
package dto; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; import enumerations.ContractType; public class JobOffer { public JobOffer() { super(); } public JobOffer(String jobTitle, String reference, String mission, String demanderProfile, String location) { JobTitle = jobTitle; Reference = reference; Mission = mission; DemanderProfile = demanderProfile; Location = location; } /* @JsonProperty("RmId") private int RmId; */ @JsonProperty("JobId") private int JobId ; /* @JsonProperty("Employee") private Employee Employee ; */ /* @JsonProperty("EmployeeId") private int EmployeeId ; */ @JsonProperty("JobTitle") private String JobTitle ; @JsonProperty("Reference") private String Reference ; @JsonProperty("Mission") private String Mission; @JsonProperty("DemanderProfile") private String DemanderProfile ; @JsonProperty("Location") private String Location ; @JsonProperty("ExpirationDate") private Date ExpirationDate ; /* @JsonProperty("ContratType") private ContractType ContratType; */ /* @JsonProperty("RecruitementManager") private RecruitementManager RecruitementManager; */ public int getJobId() { return JobId; } public void setJobId(int jobId) { JobId = jobId; } public String getJobTitle() { return JobTitle; } public void setJobTitle(String jobTitle) { JobTitle = jobTitle; } public String getReference() { return Reference; } public void setReference(String reference) { Reference = reference; } public String getMission() { return Mission; } public void setMission(String mission) { Mission = mission; } public String getDemanderProfile() { return DemanderProfile; } public void setDemanderProfile(String demanderProfile) { DemanderProfile = demanderProfile; } public String getLocation() { return Location; } public void setLocation(String location) { Location = location; } public Date getExpirationDate() { return ExpirationDate; } public void setExpirationDate(Date expirationDate) { ExpirationDate = expirationDate; } /* public ContractType getContratType() { return ContratType; } public void setContratType(ContractType contratType) { ContratType = contratType; } public RecruitementManager getRecruitementManager() { return RecruitementManager; } public void setRecruitementManager(RecruitementManager recruitementManager) { RecruitementManager = recruitementManager; } */ @Override public String toString() { return "id is "+JobId+"job title :"+JobTitle+"mission is "+Mission+"reference is "+Reference+"location is "+Location; } }
Ruby
UTF-8
1,748
2.875
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/ruby # encoding: utf-8 module Text class Table class Column include Utils def initialize( table, index ) @table = table @index = index @filling = Segments.default_filling( @table.style ) @left_side = Segments.default_joints( @table.style ) @wrap = false @flow = true @alignment = :left @width = nil @fixed_width = nil end def left_side first? ? @table.left_edge : @left_side end def right_side last? ? @table.right_edge : next_column.left_side end attr_reader :table, :index, :filling attr_accessor :alignment for m in %w(wrap flow) attr_accessor( m ) alias_method( "#{m}?", m ) undef_method( m ) end def cells @table.grep( Row ) { | row | row[ @index ].to_s } end def previous_column @index.zero? ? nil : @table.columns[ @index - 1 ] end def next_column @table.columns[ @index + 1 ] end def first? @index.zero? end def last? @index == (table.columns.length - 1) end def prepare( cell_text ) cell_text = cell_text.to_s if @wrap @flow and cell_text = cell_text.fold cell_text = cell_text.word_wrap( width ) cell_text.strip! end align( cell_text, @alignment, width ) end def fill_text( text ) text.is_a?( Symbol ) and text = @filling[ text ] super( text, width ) end def width=( w ) @fixed_width = w.to_i.at_least( 0 ) end def width @fixed_width or @width or calculate_width end def calculate_metrics @width = @fixed_width || calculate_width end def clear_metrics @width = nil end protected def calculate_width cells.map { | c | block_width( c ) }.max end end end end
Java
UTF-8
717
2.34375
2
[ "Apache-2.0" ]
permissive
package io.rsocket.aeron.frames; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; public final class AeronPayloadFlyweight { private static final short VERSION = 0; private AeronPayloadFlyweight() {} public static FrameType frameType(ByteBuf byteBuf) { int anInt = byteBuf.getInt(Short.BYTES); return FrameType.fromEncodedType(anInt); } public static short version(ByteBuf byteBuf) { return byteBuf.getShort(0); } public static ByteBuf encode(ByteBufAllocator allocator, FrameType type) { return allocator.buffer().writeShort(VERSION).writeInt(type.getEncodedType()); } public static int headerOffset() { return Short.BYTES + Integer.BYTES; } }
C
GB18030
2,462
2.609375
3
[]
no_license
#include "dma.h" /******************************************************************************* * : DMAx_Init * : DMAʼ * : DMAy_Channelx:DMAͨѡ,@ref DMA_channel DMA_Channel_0~DMA_Channel_7 par:ַ mar:洢ַ ndtr:ݴ * : *******************************************************************************/ void DMAx_Init(DMA_Channel_TypeDef *DMAy_Channelx, u32 par, u32 mar, u16 ndtr) { DMA_InitTypeDef DMA_InitStructure; RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);//DMA1ʱʹ DMA_DeInit(DMAy_Channelx); /* DMA Stream */ DMA_InitStructure.DMA_PeripheralBaseAddr = par;//DMAַ DMA_InitStructure.DMA_MemoryBaseAddr = mar;//DMA 洢0ַ DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;//洢ģʽ DMA_InitStructure.DMA_BufferSize = ndtr;//ݴ DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;//ģʽ DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;//洢ģʽ DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;//ݳ:8λ DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;//洢ݳ:8λ DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;// ʹͨģʽ DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;//еȼ DMA_InitStructure.DMA_M2M = DMA_M2M_Disable; //DMAͨxûΪڴ浽ڴ洫 DMA_Init(DMAy_Channelx, &DMA_InitStructure);//ʼDMA Stream } /******************************************************************************* * : DMAx_Enable * : һDMA * : DMAy_Channelx:DMAͨѡ,@ref DMA_channel DMA_Channel_0~DMA_Channel_7 ndtr:ݴ * : *******************************************************************************/ void DMAx_Enable(DMA_Channel_TypeDef *DMAy_Channelx, u16 ndtr) { DMA_Cmd(DMAy_Channelx, DISABLE); //رDMA DMA_SetCurrDataCounter(DMAy_Channelx, ndtr); //ݴ DMA_Cmd(DMAy_Channelx, ENABLE); //DMA }
C
UTF-8
549
2.921875
3
[]
no_license
#ifndef SORT_H #define SORT_H #include <stdio.h> #include <stdlib.h> #define MAXI 100 void countSort(int** nums, int row, int colNo, int* p){ int output[row]; int counter[MAXI] = {0}; for (int i = 0; i < row; i++) counter[nums[p[i]][colNo]]++; for (int i = 1; i < MAXI; i++) counter[i] += counter[i-1]; for (int i = row-1; i >= 0; i--){ output[counter[nums[p[i]][colNo]] - 1] = p[i]; counter[nums[p[i]][colNo]]--; } for (int i = 0; i < row; i++) p[i] = output[i]; } #endif
Markdown
UTF-8
2,168
3.65625
4
[]
no_license
## 员工管理系统 ### 项目介绍 模拟数据库操作,实现数据库的增删改查操作 ``` 1. 可进行模糊查询,语法至少支持下面3种: (1). select name,age from staff_table where age > 22 (2). select * from staff_table where dept = "IT" (3). select * from staff_table where enroll_date like "2013" 2. 查到的信息,打印后,最后面还要显示查到的条数 3. 可创建新员工纪录,以phone做唯一键,staff_id需自增,增加语法: insert into staff_table values Alex Li,22,13455662334,IT,2013-02-11 4. 可删除指定员工信息纪录,删除语法: delete from staff_table where id=5 5. 可修改员工信息,语法如下: UPDATE staff_table SET dept="Market" WHERE dept = "IT" ``` ### 程序说明 - 作者:tengjuyuan - 版本:v1.0 - 程序功能:以txt文件模拟数据库,实现数据库的增删改查功能。 --- #### 功能说明: where后面的判断条件可以为以下几种: > 基本功能: - 1. id筛选,可以为 运算符>=、<=、>、<、=,运算符两边可以有任意空格,如id =5或 id>= 3 - 2. name筛选,可以为 name = "Jack Wang" ,待查找的名字必须用双引号 - 3. age筛选,同id筛选,如age >=22 - 4. phone筛选,程序同id筛选,但是输入等号符合实际情况,如phone=13434545667 - 5. dept筛选,同name,如dept="IT" - 6. enroll_data筛选, 可以为 enroll_date like "2013", 也可以输入年和月,格式为:year-month-day如enroll_date like "2013-10-10" > 高级功能: - 可以使用【and, or, not】连接以上任意两个条件,如age >= 20 and dept="IT" > select显示说明: - select后面的显示可以为一个或多个的组合或全部(*),以逗号连接,中间不能有空格,如 id,name,age 或id,dept,enroll_date #### 数据说明: - 输出存储格式:['id', 'name', 'age', 'phone', 'dept', 'enroll_date'] 如:1,Alex Li,22,13651054608,IT,2013-04-01 - 中间数据采用的是二级列表进行存储, 即[['1', 'Alex Li', '22', '13651054608', 'IT', '2013-04-01']...] #### 程序运行: - 直接按照提示输入命令即可
C
GB18030
717
3.78125
4
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> typedef struct Stu { char name[20]; short age; char tele[12]; char sex[5]; }Stu; void Print1(Stu tmp) { printf("name:%s\n", tmp.name); printf("age:%d\n", tmp.age); printf("tele:%s\n", tmp.tele); printf("sex:%s\n", tmp.sex); } void Print2(Stu* ps) { printf("name:%s\n",ps->name); printf("age:%d\n",ps->age); printf("tele:%s\n",ps->tele); printf("sex:%s\n",ps->sex); } int main() { Stu s = { "",40,"12138","" }; Print1(s); Print2(&s); return 0; }//ѡPrint2Ϊεʱ򣬲Ҫѹջһṹ󣬽ṹ󣬲ѹջϵͳȽϴԻᵼ½
PHP
UTF-8
393
2.984375
3
[ "MIT" ]
permissive
<?php namespace Proweb21; /** * Interface for subscribers * * Event Subscribers recieve publications (dispatchable objects) from channels (Buses) * @see https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern */ interface Subscriber { /** * Subscribes itself to an Bus * * @param Bus $bus * @return void */ public function subscribe(Bus $bus); }
JavaScript
UTF-8
1,316
2.640625
3
[]
no_license
function DataBinder(object_id) { var pubSub = jQuery({}) var data_attr = "bind-"+object_id var message = object_id + ":change" jQuery(document).on("change", "[data-" + data_attr + "]", function(evt) { var input = jQuery(this) pubSub.trigger(message, [input.data(data_attr), input.val()]) }) pubSub.on(message, function(evt, prop_name, new_val){ jQuery(`[data-${data_attr}=${prop_name}]`).each(function(){ var $bound = jQuery(this) if ($bound.is("input,text area,select")) { $bound.val(new_val) } else { $bound.html(new_val) } }) }) return pubSub } function User(uid) { var binder = new DataBinder(uid) user = { attributes: {}, set: function(attr_name, val) { this.attributes[attr_name] = val console.log("set", attr_name, "to", val) binder.trigger(uid+":change", [attr_name, val, this]) }, get: function(attr_name) { return this.attributes["attr_name"] }, _binder: binder } binder.on(uid+":change", function(evt, attr_name, new_val, initiator) { if (initiator !== user) { user.set(attr_name, new_val) } }) return user }
Markdown
UTF-8
1,604
2.578125
3
[]
no_license
# aimldl/python/courses/udemy/AutomateTheBoringStuffWithPythonProgramming Al Sweigart made his book "Automate the Boring Stuff with Python Programming" publically available at https://automatetheboringstuff.com. I recommend to take his online course at Udemy (https://www.udemy.com/automate/learn/v4/content). # To-dos 1. Summarize the data types, //, ** from Lecture 1 & 2 2. Start from "Return Values and return Statements" at https://automatetheboringstuff.com/chapter3/ # References 1.Automate the Boring Stuff with Python Programming, https://automatetheboringstuff.com 2.Automate the Boring Stuff with Python Programming, https://www.udemy.com/automate/learn/v4/content # Chapter 1. Python Basics ## Lecture 1. Get Python Installed ## Lecture 2. Basic Terminology and Using IDLE Three topics: Expressions, Data Types, and Variables. ##Entering Expressions into the Interactive Shell # Chapter 2. Flow Control test # aimldl/python/packages/csv This is a branch for the csv package. # To-dos Try and Except Error handling Python Tutorial https://pythonprogramming.net/handling-exceptions-try-except-python-3/?completed=/reading-csv-files-python-3/ # References 1.Reading CSV files in Python, https://pythonprogramming.net/reading-csv-files-python-3/ * 14.1. csv — CSV File Reading and Writing, https://docs.python.org/3/library/csv.html # aimldl/python/packages/numpy This is my repository of Python scripts for the Numpy tutorial. # To-dos # References 1.Quickstart tutorial, https://docs.scipy.org/doc/numpy/user/quickstart.html * Numpy and Scipy Documentation, https://docs.scipy.org/doc/
JavaScript
UTF-8
2,059
2.734375
3
[]
no_license
let log = console.log; class ToobarElement{ constructor(){ } //Main section get howItWorksLink() { return browser.element('a[aria-label="How it Works"]'); } get createDocumentsLink(){ let selector = '//span[text()="create documents"]//parent::li/a'; browser.waitForVisible(selector,3000); return browser.element(selector); } get myDocumentsLink(){ return browser.element('//span[text()="my documents"]//parent::li/a'); } get myProfileLink(){ return browser.element('//i[text()="person"]/parent::a'); } get helpLink(){ return browser.element('//span[text()="live_help"]//parent::li/a'); } //Right slide section get closeRightMenuArrow(){ return browser.element('//aside[@class="menu slideInLeft"]//i[text()="keyboard_arrow_left"]/parent::a'); } get searchField(){ return browser.element('//aside[@class="menu slideInLeft"]//input[@placeholder="search"]'); } typeToSearchField(value){ this.searchField.setValue(value); } clickOnDocumentLink(docName){ let elementSelector = `//aside[@class="menu slideInLeft"]//ul[@class="menu-list"]//a[text()='${docName}']`; browser.waitForVisible(elementSelector,3000); browser.waitForEnabled(elementSelector,3000); browser.element(elementSelector).click(); log(`Click on '${docName}' link.`); } navigateToMainPage(){ this.howItWorksLink.click(); log('Click on "Main Page" button.'); } openCreateDocumentsMenu(){ this.createDocumentsLink.click(); log('Click on "Create Documents" button.'); } navigateToMyDocuments(){ this.myDocumentsLink.click(); log('Click on "My Documents" button.'); } navigateToMyProfile(){ this.myProfileLink.click(); log('Click on "My Profile" button.'); } navigateToHelp(){ this.helpLink.click(); log('Click on "Help" button.'); } } module.exports = ToobarElement;
Python
UTF-8
632
2.71875
3
[]
no_license
from django.shortcuts import render from .models import destination # Create your views here. def index(request): dest1 = destination() dest1.name = 'Udaipur' dest1.desc = 'The City Of Lakes' dest1.img = 'udaipur.jpg' dest1.price = 500 dest2 = destination() dest2.name = 'Mumbai' dest2.desc = 'The City never sleeps' dest2.img = 'mumbai.jpg' dest2.price = 600 dest3 = destination() dest3.name = 'Jaipur' dest3.desc = 'The Pink City' dest3.img = 'hawa.jpg' dest3.price = 680 dests = [dest1, dest2, dest3] return render(request, 'index.html', {'dests': dests})
TypeScript
UTF-8
712
3.03125
3
[]
no_license
export default class ScrollingSprite { private image: any; private x: number; private y: number; private width: number; private height: number; private speed: number; constructor(image: any, x: number, y: number, width: number, height: number, speed: number) { this.image = image; this.x = x; this.y = y; this.width = width; this.height = height; this.speed = speed; } scroll() { this.x -= this.speed; if (this.x <= -this.width) { this.x = this.width - 1; } } draw(ctx: CanvasRenderingContext2D) { ctx.drawImage(this.image, this.x, this.y, this.width, this.height); } }
Java
UTF-8
4,066
2.40625
2
[]
no_license
package spring5mvc.rest.services; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import spring5mvc.rest.api.v1.mapper.CustomerMapper; import spring5mvc.rest.api.v1.model.CustomerDTO; import spring5mvc.rest.domain.Customer; import spring5mvc.rest.repositories.CustomerRepository; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; class CustomerServiceTest { public static final Long ID = 1L; public static final String NAME = "Jimmy"; @Mock CustomerRepository customerRepository; CustomerService customerService; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); customerService = new CustomerServiceImpl(customerRepository, CustomerMapper.INSTANCE); } @Test void createNewCustomer() { Customer customer = Customer.builder().id(ID).firstName(NAME).build(); CustomerDTO customerDTO = new CustomerDTO(); customerDTO.setId(customer.getId()); customerDTO.setFirstName(customer.getFirstName()); when(customerRepository.save(any(Customer.class))).thenReturn(customer); CustomerDTO savedDto = customerService.createNewCustomer(customerDTO); assertNotNull(savedDto); assertEquals(ID, savedDto.getId()); assertEquals(NAME, savedDto.getFirstName()); assertEquals("/api/v1/customers/1", savedDto.getCustomerUrl()); verify(customerRepository, times(1)).save(any(Customer.class)); } @Test void saveCustomerByDTO() { Customer customer = Customer.builder().id(ID).firstName(NAME).build(); CustomerDTO customerDTO = new CustomerDTO(); customerDTO.setFirstName(customer.getFirstName()); when(customerRepository.save(any(Customer.class))).thenReturn(customer); CustomerDTO savedDto = customerService.saveCustomerByDTO(ID, customerDTO); assertNotNull(savedDto); assertEquals(ID, savedDto.getId()); assertEquals(NAME, savedDto.getFirstName()); assertEquals("/api/v1/customers/1", savedDto.getCustomerUrl()); verify(customerRepository, times(1)).save(any(Customer.class)); } @Test void getCustomers() { List<Customer> customers = List.of(new Customer(), new Customer(), new Customer()); when(customerRepository.findAll()).thenReturn(customers); List<CustomerDTO> customerDTOS = customerService.getCustomers(); assertEquals(customers.size(), customerDTOS.size()); verify(customerRepository, times(1)).findAll(); } @Test void getCustomerById() { Customer customer = Customer.builder().id(ID).firstName(NAME).build(); when(customerRepository.findById(anyLong())).thenReturn(Optional.of(customer)); CustomerDTO customerDTO = customerService.getCustomerById(ID); assertEquals(ID, customerDTO.getId()); assertEquals(NAME, customerDTO.getFirstName()); verify(customerRepository, times(1)).findById(anyLong()); } @Test void patchCustomer() { Customer customer = Customer.builder().id(ID).firstName(NAME).build(); String updateName = "Tommy"; when(customerRepository.findById(anyLong())).thenReturn(Optional.of(customer)); when(customerRepository.save(any(Customer.class))).thenReturn(customer); CustomerDTO dto = CustomerDTO.builder().id(ID).firstName(updateName).build(); CustomerDTO updatedCustomerDTO = customerService.patchCustomer(ID, dto); assertNotNull(updatedCustomerDTO); assertEquals(ID, updatedCustomerDTO.getId()); assertNotEquals(NAME, updatedCustomerDTO.getFirstName()); } @Test void deleteCustomer() { customerRepository.deleteById(ID); verify(customerRepository, times(1)).deleteById(anyLong()); } }
Markdown
UTF-8
3,781
3.328125
3
[ "CC-BY-4.0", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- id: 145 state: approved created: 2020-05-28 placement: category: fields order: 60 --- # Ranges Services often need to represent ranges of discrete or continuous values. These have wide differences in meaning, and come in many types: integers, floats, and timestamps, just to name a few, and the expected meaning of a range can vary in subtle ways depending on the type of range being discussed. ## Guidance A resource or message representing a range **should** ordinarily use two separate fields of the same type, with prefixes `start_` and `end_`: ```proto // A representation of a chapter in a book. message Chapter { string title = 1; // The page where this chapter begins. int32 start_page = 2; // The page where the next chapter or section begins. int32 end_page = 3; } ``` ### Inclusive or exclusive ranges Fields representing ranges **should** use inclusive start values and exclusive end values (half-closed intervals) in most situations; in interval notation: `[start_xxx, end_xxx)`. Exclusive end values are preferable for the following reasons: - It conforms to user expectations, particularly for continuous values such as timestamps, and avoids the need to express imprecise "limit values" (e.g. `2012-04-20T23:59:59`). - It is consistent with most common programming languages, including C++, Java, Python, and Go. - It is easier to reason about abutting ranges: `[0, x), [x, y), [y, z)`, where values are chainable from one range to the next. ### Timestamp intervals The following section describes the use of the [google.type.Interval][interval] type, found amongst the common protos that are described in [AIP-213][]. This type represents a range between two timestamps, with an inclusive start value and exclusive end value. Ranges between two timestamps which conform to the expectations of the `Interval` message **should** use this rather than having separate start and end fields. This allows client code to be written against the `Interval` message (such as checking whether a given timestamp occurs within the interval) and reused across multiple intervals in the same API, or even across multiple APIs. APIs **may** use start and end timestamp fields instead. In particular, if a message within an API is inherently describing an interval with extra information about that interval, the additional level of nesting introduced by using the `Interval` message may be undesirable. ### Exceptions In some cases, there is significant colloquial precedent for inclusive start and end values (closed intervals), to the point that using an exclusive end value would be confusing even for people accustomed to them. For example, when discussing dates (not to be confused with timestamps), most people use inclusive end: a conference with dates "April 21-23" is expected to run for three days: April 21, April 22, and April 23. This is also true for days of the week: a business that is open "Monday through Friday" is open, not closed, on Fridays. In this situation, the prefixes `first` and `last` **should** be used instead: ```proto // A representation of a chapter in a book. message Chapter { string title = 1; // The first page of the chapter. int32 first_page = 2; // The last page of the chapter. int32 last_page = 3; } ``` Fields representing ranges with significant colloquial precedent for inclusive start and end values **should** use inclusive end values with `first_` and `last_` prefixes for those ranges only. The service **should** still use exclusive end values for other ranges where this does not apply, and **must** clearly document each range as inclusive or exclusive. [aip-213]: ./0213.md [interval]: https://github.com/googleapis/googleapis/blob/master/google/type/interval.proto
Java
UTF-8
3,081
2.125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package diu.edu.bd.controller; import diu.edu.bd.Pimanpower; import diu.edu.bd.impl.PimanpowerDao; import java.util.ArrayList; import javax.faces.component.UIForm; /** * * @author sagar */ public class PimanpowerController { public Pimanpower pimanpower=new Pimanpower(); public PimanpowerDao pimanpowerDao=new PimanpowerDao(); String msg=""; private UIForm tableForm=new UIForm(); public UIForm getTableForm(){ return tableForm; } public void setTableForm(UIForm tableForm) { this.tableForm = tableForm; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Pimanpower getPimanpower() { return pimanpower; } public void setPimanpower(Pimanpower pimanpower) { this.pimanpower = pimanpower; } public PimanpowerDao getPimanpowerDao() { return pimanpowerDao; } public void setPimanpowerDao(PimanpowerDao pimanpowerDao) { this.pimanpowerDao = pimanpowerDao; } public PimanpowerController() { tableForm.setRendered(false); } public void save(){ pimanpowerDao.save(pimanpower); setMsg("data saved"); } public void update(){ pimanpowerDao.update(pimanpower); setMsg("data has been updated"); } public void delete(){ pimanpowerDao.delete(pimanpower); setMsg("data has been deleted"); } public ArrayList<Pimanpower> getPimanpowerList(){ return (ArrayList<Pimanpower>) pimanpowerDao.display(); } public void find(){ Pimanpower manpower=pimanpowerDao.find(pimanpower.getPimanPowerSerial()); if(manpower==null){ setMsg("data not found"); } else{ pimanpower.setDate(manpower.getDate()); pimanpower.setSweingOperatorPresent(manpower.getSweingOperatorPresent()); pimanpower.setSweingHelperPresent(manpower.getSweingHelperPresent()); pimanpower.setSweingOperatorHelperPresent(manpower.getSweingOperatorHelperPresent()); pimanpower.setCuttingTotalManPower(manpower.getCuttingTotalManPower()); pimanpower.setFinishingTotalManPower(manpower.getFinishingTotalManPower()); pimanpower.setFactoryTotalManPower(manpower.getFactoryTotalManPower()); pimanpower.setTotalNoOfManHourAvilableMohel(manpower.getTotalNoOfManHourAvilableMohel()); pimanpower.setTotalNoOfManHourAvailableCutting(manpower.getTotalNoOfManHourAvailableCutting()); pimanpower.setTotalNoOfManHourAvailableFinishing(manpower.getTotalNoOfManHourAvailableFinishing()); pimanpower.setTotalNoOfManHourAvailableFactory(manpower.getTotalNoOfManHourAvailableFactory()); setMsg("data has been found"); } } public void display(){ tableForm.setRendered(true); } public void hide(){ tableForm.setRendered(false); } }
Python
UTF-8
1,952
3
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env python """ Extract the full list of emoji and names from the Unicode Consortium and apply as much formatting as possible so the codes can be dropped into the emoji registry file. Written and run with Python3. Not tested on Python2 and definitely not intended for production use. http://www.unicode.org/Public/emoji/1.0/full-emoji-list.html """ import requests from bs4 import BeautifulSoup from collections import OrderedDict url = 'http://www.unicode.org/emoji/charts/emoji-list.html' response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") # with open('utils/content.html') as f: # soup = BeautifulSoup(f.read()) header = [ 'Count', 'Code', 'Sample', 'Name' ] output = {} for row in soup.find('table').find_all('tr'): cols = row.find_all('td') cols = [e.text.strip() for e in cols] d = OrderedDict(zip(header, [e.strip() for e in cols])) if d: _code = [] for c in d['Code'].split(' '): if len(c) is 6: _code.append(c.replace('+', '0000')) else: _code.append(c.replace('+', '000')) code = ''.join(_code) """ replace semi-colons, commas, open smart quote, close smart quote, and asterisk (⊛) symbol used to denote newly added emojis replace spaces after trimming for the asterisk case """ name = d['Name'].replace(':', '') \ .replace(',', '') \ .replace(u'\u201c', '') \ .replace(u'\u201d', '') \ .replace(u'\u229b', '')\ .strip()\ .replace(' ', '_') char = "u'" + code.replace('U', '\\U') + "'," output[name] = char for name in sorted(output.keys()): print(" u':%s:': %s" % (name, output[name]))
Java
UTF-8
535
2.265625
2
[]
no_license
package com.example.ashishtiwari.navdraw_iaq; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.*; /** * Created by ashish.tiwari on 25-04-2016. */ /* public class GraphViewData implements GraphViewInterface { private double x,y; public GraphViewData(double x, double y) { this.x = x; this.y = y; } @Override public double getX() { return this.x; } @Override public double getY() { return this.y; } } */
TypeScript
UTF-8
370
3.015625
3
[ "MIT" ]
permissive
export function once<T>(callback: (...args: any[]) => T): typeof callback { let fn: ((...args: any[]) => T) | undefined = callback; let value: T | undefined; return (...args: any[]): T => { if (value) { return value; } value = fn?.(args); fn = undefined; if (value === undefined) { throw new Error(); } return value; }; }
Java
UTF-8
21,174
1.84375
2
[]
no_license
package org.spbu.pldoctoolkit.dialogs; import java.util.ArrayList; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Label; import org.spbu.pldoctoolkit.actions.SelectIntoInfProductAction; import org.spbu.pldoctoolkit.wizards.NewDrlFilePage; public class SelectIntoInfProdDialog extends Dialog { private IPath containerPath; private String infProdId = ""; private String infProdName = ""; private String finalInfProdId = ""; private String infElemId = ""; private String infElemName = ""; private String infElemRefInText = ""; private String infElemRefInProduct = ""; private String productFile = ""; private String finalFile = ""; private Text prodIdText; private Text prodNameText; private Text finalProdIdText; private Text elemIdText; private Text elemNameText; private Text refInTextIdText; private Text refInProductIdText; private Text productFileText; private Text finalFileText; private Label prodIdLabel; private Label prodNameLabel; private Label finalProdIdLabel; private Label elemIdLabel; private Label elemNameLabel; private Label refInTextIdLabel; private Label refInProductIdLabel; private Label productFileLabel; private Label finalFileLabel; // private Label errorMessage; private Label errorMessageProdId; private Label errorMessageFinalProdId; private Label errorMessageElemId; private Label errorMessageTextRefId; private Label errorMessageProductRefId; private Label errorMessageProductFile; private Label errorMessageFinalFile; private boolean isValideElemId = false; private boolean isValideTextRefId = false; private boolean isValideProdRefId = false; private boolean isValideProdId = false; private boolean isValideFinalProdId = false; private ArrayList<String> infProdIds = new ArrayList<String>(); private ArrayList<String> finalInfProdIds = new ArrayList<String>(); private ArrayList<String> infElemIds = new ArrayList<String>(); private ArrayList<String> infElemRefIds = new ArrayList<String>(); public SelectIntoInfProdDialog(Shell parentShell, IPath containerPath) { super(parentShell); setBlockOnOpen(true); this.containerPath = containerPath; } protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.verticalSpacing = 20; composite.setLayout(layout); Label description = new Label(composite, SWT.LEFT); description.setText("Extract selection into new InfProduct"); GridData gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 3; description.setLayoutData(gd); // 1/////////////////////////////////////////////////////////// prodNameLabel = new Label(composite, SWT.LEFT); prodNameLabel.setText("Name of new InfProduct:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; prodNameLabel.setLayoutData(gd); prodNameText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; prodNameText.setLayoutData(gd); KeyListener prodListener = new KeyAdapter() { public void keyReleased(KeyEvent e) { setProductTexts(); } }; prodNameText.addKeyListener(prodListener); new Label(composite, SWT.NONE); // 2//////////////////////////////////////////////////////////////////////////////////// prodIdLabel = new Label(composite, SWT.LEFT); prodIdLabel.setText("Id of new InfProduct:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; prodIdLabel.setLayoutData(gd); prodIdText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; prodIdText.setLayoutData(gd); prodIdText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validate(); } }); errorMessageProdId = new Label(composite, SWT.LEFT); errorMessageProdId .setText(" "); errorMessageProdId.setForeground(new Color(Display.getCurrent(), new RGB(255, 0, 0))); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; errorMessageProdId.setLayoutData(gd); // 4//////////////////////////////////////////////////////////////////////////////////// finalProdIdLabel = new Label(composite, SWT.LEFT); finalProdIdLabel.setText("Id of new FinalInfProduct:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; finalProdIdLabel.setLayoutData(gd); finalProdIdText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; finalProdIdText.setLayoutData(gd); finalProdIdText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validate(); } }); errorMessageFinalProdId = new Label(composite, SWT.LEFT); errorMessageFinalProdId .setText(" "); errorMessageFinalProdId.setForeground(new Color(Display.getCurrent(), new RGB(255, 0, 0))); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; errorMessageFinalProdId.setLayoutData(gd); // 5/////////////////////////////////////////////////////////// elemNameLabel = new Label(composite, SWT.LEFT); elemNameLabel.setText("Name of new InfElement:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; elemNameLabel.setLayoutData(gd); elemNameText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; elemNameText.setLayoutData(gd); KeyListener elementListener = new KeyAdapter() { public void keyReleased(KeyEvent e) { setElementTexts(); } }; elemNameText.addKeyListener(elementListener); new Label(composite, SWT.NONE); // 6//////////////////////////////////////////////////////////////////////////////////// elemIdLabel = new Label(composite, SWT.LEFT); elemIdLabel.setText("Id of new InfElement:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; elemIdLabel.setLayoutData(gd); elemIdText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; elemIdText.setLayoutData(gd); elemIdText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validate(); } }); errorMessageElemId = new Label(composite, SWT.LEFT); errorMessageElemId .setText(" "); errorMessageElemId.setForeground(new Color(Display.getCurrent(), new RGB(255, 0, 0))); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; errorMessageElemId.setLayoutData(gd); // 7////////////////////////////////////////////////////////////////////////////////////// refInTextIdLabel = new Label(composite, SWT.LEFT); refInTextIdLabel.setText("InfElemtRef in text:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; refInTextIdLabel.setLayoutData(gd); refInTextIdText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; refInTextIdText.setLayoutData(gd); refInTextIdText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validate(); } }); errorMessageTextRefId = new Label(composite, SWT.LEFT); errorMessageTextRefId .setText(" "); errorMessageTextRefId.setForeground(new Color(Display.getCurrent(), new RGB(255, 0, 0))); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; errorMessageTextRefId.setLayoutData(gd); // 8////////////////////////////////////////////////////////////////////////////////////// refInProductIdLabel = new Label(composite, SWT.LEFT); refInProductIdLabel.setText("InfElemtRef in InfProduct:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; refInProductIdLabel.setLayoutData(gd); refInProductIdText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; refInProductIdText.setLayoutData(gd); refInProductIdText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validate(); } }); errorMessageProductRefId = new Label(composite, SWT.LEFT); errorMessageProductRefId .setText(" "); errorMessageProductRefId.setForeground(new Color(Display.getCurrent(), new RGB(255, 0, 0))); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; errorMessageProductRefId.setLayoutData(gd); //9//////////////////////////////////////////////////////////////////////////////// productFileLabel = new Label(composite, SWT.LEFT); productFileLabel.setText("InfProduct file:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; productFileLabel.setLayoutData(gd); productFileText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; productFileText.setLayoutData(gd); productFileText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validate(); } }); errorMessageProductFile = new Label(composite, SWT.LEFT); errorMessageProductFile .setText(" "); errorMessageProductFile.setForeground(new Color(Display.getCurrent(), new RGB(255, 0, 0))); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; errorMessageProductFile.setLayoutData(gd); // 10//////////////////////////////////////////////////////////////////////////////////// finalFileLabel = new Label(composite, SWT.LEFT); finalFileLabel.setText("FinalInfProduct File:"); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; finalFileLabel.setLayoutData(gd); finalFileText = new Text(composite, SWT.SINGLE | SWT.BORDER); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; finalFileText.setLayoutData(gd); finalFileText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validate(); } }); errorMessageFinalFile = new Label(composite, SWT.LEFT); errorMessageFinalFile .setText(" "); errorMessageFinalFile.setForeground(new Color(Display.getCurrent(), new RGB(255, 0, 0))); gd = new GridData(); gd.horizontalAlignment = SWT.FILL; gd.verticalAlignment = SWT.FILL; gd.grabExcessHorizontalSpace = true; errorMessageFinalFile.setLayoutData(gd); return composite; } public int open() { int res = super.open(); return res; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); Point size = new Point(600, 500); newShell.setSize(size); Shell p = getParentShell(); newShell.setLocation( p.getLocation().x + p.getSize().x / 2 - size.x / 2, p .getLocation().y + p.getSize().y / 2 - size.y / 2); newShell.setText(SelectIntoInfProductAction.refactName); } protected void okPressed() { infProdName = prodNameText.getText(); infProdId = prodIdText.getText(); finalInfProdId = finalProdIdText.getText(); infElemId = elemIdText.getText(); infElemName = elemNameText.getText(); infElemRefInText = refInTextIdText.getText(); infElemRefInProduct = refInProductIdText.getText(); productFile = productFileText.getText(); finalFile = finalFileText.getText(); super.okPressed(); } private void setProductTexts() { String prodName = prodNameText.getText(); if (prodName.length() > 0) { prodIdText.setText(prodName + "_id"); finalProdIdText.setText(prodName + "_finalProd"); elemIdText.setText(prodName + "_elem_id"); elemNameText.setText(prodName + "_elem"); refInTextIdText.setText(prodName + "_textRef"); refInProductIdText.setText(prodName + "_productRef"); productFileText.setText(prodName + ".drl"); finalFileText.setText(prodName + "_finalProd.drl"); validate(); } else { prodIdText.setText(""); finalProdIdText.setText(""); elemIdText.setText(""); elemNameText.setText(""); refInTextIdText.setText(""); refInProductIdText.setText(""); productFileText.setText(""); finalFileText.setText(""); } } private void setElementTexts() { String elemName = elemNameText.getText(); if (elemName.length() > 0) { elemIdText.setText(elemName + "_elem_name"); refInTextIdText.setText(elemName + "_textRef"); refInProductIdText.setText(elemName + "_productRef"); validate(); } else { elemIdText.setText(""); refInTextIdText.setText(""); refInProductIdText.setText(""); } } private void validate() { isValideProdId = true; for (String otherId : infProdIds) { if (prodIdText.getText().equals(otherId)) { isValideProdId = false; break; } } if (!isValideProdId) { errorMessageProdId.setText("Bad infProduct id"); getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorMessageProdId.setText(""); getButton(IDialogConstants.OK_ID).setEnabled(true); } // ////////////////////////////////////////////////////////////////// isValideFinalProdId = true; for (String otherId : finalInfProdIds) { if (finalProdIdText.getText().equals(otherId)) { isValideFinalProdId = false; break; } } if (!isValideFinalProdId) { errorMessageFinalProdId.setText("Bad finalInfProduct id"); getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorMessageFinalProdId.setText(""); getButton(IDialogConstants.OK_ID).setEnabled(true); } // ////////////////////////////////////////////////////////////////// isValideElemId = true; for (String otherId : infElemIds) { if (elemIdText.getText().equals(otherId)) { isValideElemId = false; break; } } if (!isValideElemId) { errorMessageElemId.setText("Bad infElement id"); getButton(IDialogConstants.OK_ID).setEnabled(false); } else { errorMessageElemId.setText(""); getButton(IDialogConstants.OK_ID).setEnabled(true); } // ////////////////////////////////////////////////////////////////// isValideTextRefId = true; for (String otherId : infElemRefIds) { if (refInTextIdText.getText().equals(otherId)) { isValideTextRefId = false; break; } } if (!isValideTextRefId) { errorMessageTextRefId.setText("Bad infElementRef id"); getButton(IDialogConstants.OK_ID).setEnabled(false); ; } else { errorMessageTextRefId.setText(""); getButton(IDialogConstants.OK_ID).setEnabled(true); } // ////////////////////////////////////////////////////////////////// isValideProdRefId = true; for (String otherId : infElemRefIds) { if (refInProductIdText.getText().equals(otherId)) { isValideProdRefId = false; break; } } if (!isValideProdRefId) { errorMessageProductRefId.setText("Bad infElementRef id"); getButton(IDialogConstants.OK_ID).setEnabled(false); ; } else { errorMessageProductRefId.setText(""); getButton(IDialogConstants.OK_ID).setEnabled(true); } //validate files//////////////////////////////////////////////////// String productMessage = validateProductFile(); if (productMessage!= null) { errorMessageProductFile.setText(productMessage); getButton(IDialogConstants.OK_ID).setEnabled(false); ; } else { errorMessageProductFile.setText(""); getButton(IDialogConstants.OK_ID).setEnabled(true); } // ////////////////////////////////////////////////////////////////// String finalMessage = validateFinalFile(); if (finalMessage != null) { errorMessageFinalFile.setText(finalMessage); getButton(IDialogConstants.OK_ID).setEnabled(false); ; } else { errorMessageFinalFile.setText(""); getButton(IDialogConstants.OK_ID).setEnabled(true); } } private String validateProductFile() { String message = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IContainer container = (IContainer) root.findMember(containerPath); message = NewDrlFilePage.validateFileName(productFileText.getText(), "InfProduct file"); if (message != null) return message; IFile docCoreFile = container.getFile(new Path(productFileText.getText())); if (docCoreFile.exists()) return productFileText.getText() + " file exists in project"; return null; } private String validateFinalFile() { String message = null; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IContainer container = (IContainer) root.findMember(containerPath); message = NewDrlFilePage.validateFileName(finalFileText.getText(), "FinalProduct file"); if (message != null) return message; IFile productDocFile = container.getFile(new Path(finalFileText.getText())); if (productDocFile.exists()) return finalFileText.getText() + " file exists in project"; return null; } public String getInfElemId() { return infElemId; } public String getInfElemName() { return infElemName; } public String getInfprodName() { return infProdName; } public String getInfprodId() { return infProdId; } public String getInfElemRefInText() { return infElemRefInText; } public String getInfElemRefInProduct() { return infElemRefInProduct; } public String getFinInfProdId() { return finalInfProdId; } public String getFinalProdFile() { return finalFile; } public String getInfProdFile() { return productFile; } public void addInfProdIds(String id) { infProdIds.add(id); } public void addFinInfProdIds(String id) { finalInfProdIds.add(id); } public void addInfElemId(String id) { infElemIds.add(id); } public void addInfElemRefId(String id) { infElemRefIds.add(id); } }
Markdown
UTF-8
692
3.03125
3
[]
no_license
# Nondeterministic Impressionism Algorithm that uses .NET graphics library and pseudo-randomness to produce an image based on a reference that appears like a drawn version of the original. Comparisons are made after each stroke, and if the stroke has made the image more different from the reference than the previous state, it is reverted. Written in C# in the Visual Studio Community 2017 IDE. All source code in `Nondeterministic Impressionism/Form1.cs`. Here is an example reference image and drawing produced with sampling mode, stroke drawing mode, and colour matching. Reference: ![Reference](https://i.imgur.com/g46SahS.png) Drawing: ![Drawing](https://i.imgur.com/NtLaH4o.png)
Python
UTF-8
914
2.953125
3
[]
no_license
import random def gcdex(a, b): if b == 0: return a, 1, 0 d, y, x = gcdex(b, a % b) return d, x, y - (a // b) * x def encrypting(letter): return str((int(letter) ** public_key_e) % public_key_n) p, q = 11, 47 el = (p - 1) * (q - 1) public_key_n = p * q # public_key_n = 517 public_key_e = random.choice([text_of_num for text_of_num in range(1, el) if gcdex(el, text_of_num)[0] == 1]) print([text_of_num for text_of_num in range(1, el) if gcdex(el, text_of_num)[0] == 1]) # public_key_e = 3 private_key = gcdex(el, public_key_e)[2] % el text_of_num = "".join(list(map(str, map(ord, open("text", "r").read())))) text_of_num = "100" print(" ".join(list(map(encrypting, text_of_num)))) open("encrypted", "w").write(" ".join(list(map(encrypting, text_of_num)))) open("public_key", "w").write("%s %s" % (str(public_key_e), str(public_key_n))) open("private_key", "w").write(str(private_key))
Java
UTF-8
260
2.015625
2
[]
no_license
// Use this enum to use as a flag type for what characteristic is in play // Also for a field in the trump card class public enum CardPlayType { NULL, ECONOMIC_VALUE, CRUSTAL_ABUNDANCE, HARDNESS, CLEAVAGE, SPECIFIC_GRAVITY, TRUMP }
Python
UTF-8
1,149
2.984375
3
[]
no_license
# Import the relevent modules from sense_hat import SenseHat import time # Set up the sense hat sense = SenseHat() sense.set_rotation(270) sense.set_imu_config(False, True, False) # gyroscope only # Loop around forever #while(True): # temp = round( sense.get_temperature_from_humidity(), 1 ) # sense.show_message( str(temp)) # time.sleep(0.5) while(True): # Read values from Gyro gyro_only = sense.get_gyroscope() # Roll is left to right (on defalt mission zero emulator). Scale -> 0 - 8 roll = int(gyro_only['roll']) if roll > 180: roll = roll - 360 # Now have -90 - 90 roll = int((roll + 90) / 22.5) print('R:', roll) # Roll is left to right (on defalt mission zero emulator). Scale -> 0 - 8 pitch = int(gyro_only['pitch']) if pitch > 180: pitch = pitch - 360 # Now have -90 - 90 pitch = int((pitch + 90) / 22.5) print('P:', pitch) sense.set_pixel(roll, pitch, 255, 0, 255) #if #print("p: {pitch}, r: {roll}, y: {yaw}".format(**gyro_only)) # alternatives #print(sense.gyro) #print(sense.gyroscope) time.sleep(0.5) sense.set_pixel(roll, pitch, 0, 0, 0)
Java
UTF-8
3,398
2.265625
2
[]
no_license
package org.community.controller; import org.community.domain.Criteria; import org.community.domain.ReplyPageDTO; import org.community.domain.ReplyVO; import org.community.service.ReplyService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; 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.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/devReplies/*") public class DevReplyController { Logger log = LoggerFactory.getLogger(DevReplyController.class); private ReplyService service; @Autowired private void setDevReplyService(ReplyService devReplyService) { this.service = devReplyService; } @PreAuthorize("isAuthenticated()") @PostMapping(value = "/new", consumes = "application/json", produces = {MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> register(@RequestBody ReplyVO vo){ log.info("DevReplyVO : " + vo); int insertCount = service.register(vo); log.info("insert Count : " + insertCount); return insertCount == 1 ? new ResponseEntity<String>("Success", HttpStatus.OK) : new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } @GetMapping(value = "/{rno}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE}) public ResponseEntity<ReplyVO> get(@PathVariable("rno") Long rno){ log.info("get rno : " + rno); return new ResponseEntity<ReplyVO>(service.get(rno), HttpStatus.OK); } @PreAuthorize("principal.username == #vo.replyer") @RequestMapping(method = {RequestMethod.PUT, RequestMethod.PATCH}, value ="/{rno}", consumes = "application/json", produces = {MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> modify(@PathVariable("rno")Long rno, @RequestBody ReplyVO vo){ vo.setRno(rno); log.info("modify rno :" + rno); return service.modify(vo) == 1 ? new ResponseEntity<String>("Success", HttpStatus.OK) : new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } @PreAuthorize("principal.username == #vo.replyer") @DeleteMapping(value = "/{rno}", produces = {MediaType.TEXT_PLAIN_VALUE}) public ResponseEntity<String> remove(@PathVariable("rno") Long rno, @RequestBody ReplyVO vo){ log.info("remove rno : " + rno); return service.remove(rno) == 1 ? new ResponseEntity<String>("Success", HttpStatus.OK) : new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR); } @GetMapping(value = "/pages/{bno}/{page}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE}) public ResponseEntity<ReplyPageDTO> getList(@PathVariable("page") int page, @PathVariable("bno") Long bno){ Criteria cri = new Criteria(page, 10); return new ResponseEntity<ReplyPageDTO>(service.getList(cri, bno), HttpStatus.OK); } }
Python
UTF-8
1,372
3.953125
4
[]
no_license
""" Solution for July LeetCoding Challenges Week 1 Day 6: Plus One """ class Solution1: """ Use carry boolean to check if one is carried over - Number of digits: M, N - Space Complexity: O(1) - Time Complexity: O(max(M, N)) Runtime: 56 ms / 7.05% Memory Usage: 13.7 MB / 78.16% """ def plusOne(self, digits: List[int]) -> List[int]: carry = False for i in range(len(digits)-1, -1, -1): if digits[i] == 9: carry = True digits[i] = 0 else: carry = False digits[i] += 1 break if carry: return [1] + digits else: return digits class Solution2: """ Infer carried one without an explicit boolean. - Number of digits: M, N - Space Complexity: O(1) - Time Complexity: O(max(M, N)) Runtime: 52 ms / 10.12% Memory Usage: 13.8 MB / 52.25% """ def plusOne(self, digits: List[int]) -> List[int]: if len(digits) == 1 and digits[0] == 0: return [1] for i in range(len(digits)-1, -1, -1): if digits[i] == 9: digits[i] = 0 else: digits[i] += 1 break if digits[0] == 0: return [1] + digits else: return digits
C#
UTF-8
2,719
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ParkMeter { public partial class ParkingTicketForm : Form { public ParkingTicketForm() { InitializeComponent(); //Set Parking Ticket Issue Date/Time and Expiry Date/Time //SET TICKET NUMBER Ticket.tick(); ticketNumber.Text = "Ticket Number:" + Ticket.getTicketNumber().ToString(); //SET ISSUE TIME Time.setIssueTime(DateTime.Now); issueDate.Text = "Issue Date/Time:" + Time.getIssueTime().ToString(); //SET EXPIRY TIME Time.setExpiryTime(Payment.getHours(), Payment.getMinutes()); expiryDate.Text = "Expiry Date/Time:" +Time.getExpiryTime().ToString(); //SET AMOUNT PAID amountPaid.Text = "Amount Paid: " + Payment.formatMoney(Payment.getAmountOwing()); //Text Send Message Time.setExpiryTime(Payment.getHours(), Payment.getMinutes()); string Coincheck = CoinDispenseForm.printPhoneNumber; string Cardcheck = PrintTicketForm.printPhoneNumber; string Cardpart = CoinDispenseForm.Cardcheck; //Coin check if (Coincheck==null) { //get phone number from CoinDispenseForm TextSend.Text = " "; } else { string phoneNumber = CoinDispenseForm.phoneNumber; TextSend.Text = "Text will be Sent at : " + Time.getExpiryTime().AddMinutes(-10).ToString() + " to " + phoneNumber; } // gets sysdate for comparing DateTime Sysdate=DateTime.Now; if ((Cardcheck.Equals("yes") ||Coincheck.Equals("yes"))&& (Sysdate== Time.getExpiryTime().AddMinutes(-10))) { MessageBox.Show("your parking ticket will expire in 10 minutes"); } //Card check if (Cardcheck.Equals("yes")) { //get phone number from CoinDispenseForm string phoneNumber = PrintTicketForm.phoneNumber; TextSend.Text = "Text will be Sent at : " + Time.getExpiryTime().AddMinutes(-10).ToString() + " to " + phoneNumber; } else { TextSend.Text = " "; } //RESET NEW HOURS AND NEW MINUTES FROM MODIFY FORM Payment.setHours(0); Payment.setMinutes(0); } } }
Swift
UTF-8
587
4.15625
4
[ "MIT" ]
permissive
//: [Previous : Protocol in Swift](@previous) /*: # Error Handling in Swift */ enum GuessNumberGameError : Error { case wrongNumber } class GuessNumberGame { var targetNumber = 10 func guess(number: Int) throws { guard number == targetNumber else { throw GuessNumberGameError.wrongNumber } print("Guess the right number: \(targetNumber)") } } do{ try GuessNumberGame().guess(number: 20) } catch GuessNumberGameError.wrongNumber { print("Wrong number!") }
Python
UTF-8
169
2.734375
3
[]
no_license
import cv2 img = cv2.imread("bird.jfif") img_cropped = img[0:200,0:200] cv2.imshow("Original image", img) cv2.imshow("Cropped image", img_cropped) cv2.waitKey(2000)
Java
UTF-8
543
2.578125
3
[]
no_license
package com.practicalunittesting.chp06.threadsafe; import org.junit.Test; import static org.junit.Assert.assertNotEquals; /** * Practical Unit Testing with JUnit and Mockito - source code for examples. * Visit http://practicalunittesting.com for more information. * * @author Tomek Kaczanowski */ public class AtomicIdGeneratorTest { private IdGenerator idGen = new AtomicIdGenerator(); // will usually pass @Test public void idsShouldBeUnique() { Long idA = idGen.nextId(); Long idB = idGen.nextId(); assertNotEquals(idA, idB); } }
C++
UTF-8
5,685
2.78125
3
[]
no_license
#include <fstream> #include <iostream> #include <istream> #include <map> #include <ostream> #include <set> #include <string> #include <vector> using field_t = std::vector<std::string>; using point_t = std::array<int, 2>; using portals_t = std::map<point_t, point_t>; using data_t = std::tuple<field_t, portals_t, point_t, point_t>; using access_t = std::set<point_t>; bool isalpha(char c) { return 'A' <= c && c <= 'Z'; } std::istream &read_field(std::istream &stream, field_t &field) { std::string line; std::size_t width = 0; while (std::getline(stream, line)) { if (!std::empty(line)) { width = std::max(width, std::size(line)); field.push_back(std::move(line)); } } for (std::size_t i = 0; i != std::size(field); ++i) { field[i].resize(width); } return stream; } data_t read_data(const char *filename) { data_t data; std::ifstream stream(filename); auto &[field, portals, begin, end] = data; read_field(stream, field); std::map<std::string, std::pair<point_t, point_t>> mouths; for (int i = 2; i != (int)std::size(field) - 2; ++i) { for (int j = 2; j != (int)std::size(field[i]) - 2; ++j) { if (field[i][j] == '.') { std::map<std::string, std::pair<point_t, point_t>> new_mouths; if (isalpha(field[i - 1][j])) { std::string name{field[i - 2][j], field[i - 1][j]}; new_mouths[name] = {point_t{i - 1, j}, point_t{i, j}}; } if (isalpha(field[i + 1][j])) { std::string name{field[i + 1][j], field[i + 2][j]}; new_mouths[name] = {point_t{i + 1, j}, point_t{i, j}}; } if (isalpha(field[i][j - 1])) { std::string name{field[i][j - 2], field[i][j - 1]}; new_mouths[name] = {point_t{i, j - 1}, point_t{i, j}}; } if (isalpha(field[i][j + 1])) { std::string name{field[i][j + 1], field[i][j + 2]}; new_mouths[name] = {point_t{i, j + 1}, point_t{i, j}}; } for (const auto &mouth : new_mouths) { const auto &[name, points] = mouth; const auto &[in, out] = points; if (name == "AA") { begin = out; } else if (name == "ZZ") { end = out; } else if (auto iter = mouths.find(name); iter != mouths.end()) { portals[in] = iter->second.second; portals[iter->second.first] = out; } else { mouths.insert(mouth); } } } } } return data; } std::ostream &operator<<(std::ostream &stream, const point_t &point) { auto [x, y] = point; return stream << "(" << x << "," << y << ")"; } int part_one(data_t data) { auto &[field, portals, begin, end] = data; field[begin[0]][begin[1]] = '@'; int distance = 0; for (access_t access = {begin}; !std::empty(access); ++distance) { access_t new_access; for (auto p : access) { point_t next[4] = { {p[0] - 1, p[1]}, {p[0] + 1, p[1]}, {p[0], p[1] - 1}, {p[0], p[1] + 1}, }; for (auto p : next) { if (p == end) { return distance + 1; } if (auto iter = portals.find(p); iter != portals.end()) { p = iter->second; } if (field[p[0]][p[1]] == '.') { field[p[0]][p[1]] = '@'; new_access.insert(p); } } } std::swap(access, new_access); } throw "UNREACHABLE"; } using level_access_t = std::set<std::pair<int, point_t>>; int part_two(const data_t &data, int limit) { const auto &[field, portals, begin, end] = data; std::vector<field_t> levels = {field}; levels[0][begin[0]][begin[1]] = '@'; int distance = 0; int level = 0; for (level_access_t access = {{0, begin}}; !std::empty(access); ++distance) { level_access_t new_access; for (const auto [l, p] : access) { point_t next[4] = { {p[0] - 1, p[1]}, {p[0] + 1, p[1]}, {p[0], p[1] - 1}, {p[0], p[1] + 1}, }; for (auto p : next) { level = l; if (level == 0 && p == end) { return distance + 1; } if (auto iter = portals.find(p); iter != portals.end()) { if (p[1] < 2 || p[1] >= (int)std::size(field[p[0]]) - 2 || p[0] < 2 || p[0] >= (int)std::size(field) - 2) { if (level == 0) { continue; } --level; } else { if (level == limit) { continue; } ++level; if (level == (int)std::size(levels)) { levels.push_back(field); } } p = iter->second; } if (levels[level][p[0]][p[1]] == '.') { levels[level][p[0]][p[1]] = '@'; new_access.insert({level, p}); } } } std::swap(access, new_access); } throw "UNREACHABLE"; } void do_it() try { for (auto filename : {"20-test.data", "20.data"}) { std::cout << "Processing " << filename << std::endl; auto data = read_data(filename); std::cout << "Part one answer " << part_one(data) << std::endl; } for (auto filename : {"20-test-2.data", "20.data"}) { std::cout << "Processing " << filename << std::endl; auto data = read_data(filename); std::cout << "Part two answer " << part_two(data, 100) << std::endl; } } catch (const char *e) { std::cout << e << std::endl; } int main() { do_it(); return 0; } int wmain() { do_it(); return 0; }
PHP
UTF-8
3,002
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class Permission extends Model { use HasFactory; /** * The table associated with the model. * * @var string */ protected $table = 'permissions'; /** * The attributes that are mass assignable. * * @var array $fillable */ protected $fillable = [ 'name', 'module', 'description', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'archived_at' => 'datetime', ]; public function setModuleAttribute($value) { $this->attributes['module'] = strtolower($value); } public function setNameAttribute($value) { $this->attributes['name'] = strtolower($value); } public function roles() { return $this->belongsToMany('App\Models\Role', 'permission_role', 'permission_id', 'role_id'); } public static function defaultPermissions() { return [ ...self::generateModulePermissionList('roles'), ...self::generateModulePermissionList('countries'), ...self::generateModulePermissionList('states'), ...self::generateModulePermissionList('users'), ...self::generateModulePermissionList('employers'), ...self::generateModulePermissionList('talents'), ...self::generateModulePermissionList('affiliates'), ...self::generateModulePermissionList('admins'), ...self::generateModulePermissionList('cvs'), ...self::generateModulePermissionList('campaigns'), ]; } private static function generateModulePermissionList($module) { $name_singular = Str::singular($module); $name_plural = Str::plural($module); $module = Str::slug(Str::plural($module)); return [ [ 'module' =>$module, 'name' => Str::slug("view-all-{$name_singular}"), 'description' => "View list of {$name_plural}." ], [ 'module' => $module, 'name' => Str::slug("view-{$name_singular}"), 'description' => "View {$name_singular} information." ], [ 'module' => $module, 'name' => Str::slug("create-{$name_singular}"), 'description' => "Create {$name_singular}." ], [ 'module' => $module, 'name' => Str::slug("update-{$name_singular}"), 'description' => "Update {$name_singular}." ], [ 'module' => $module, 'name' => Str::slug("delete-{$name_singular}"), 'description' => "Delete {$name_singular}." ], ]; } }
Python
UTF-8
586
2.5625
3
[]
no_license
from collections import deque from math import inf def solution(N, road, K): dic = {} for n in road: dic[n[0]] = dic.get(n[0], []) + [[n[1], n[2]]] dic[n[1]] = dic.get(n[1], []) + [[n[0], n[2]]] dist = {i: inf if i != 1 else 0 for i in range(1, N + 1)} que = deque([1]) while que: cur = que.popleft() for nxt in dic[cur]: if dist[nxt[0]] > dist[cur] + nxt[1]: dist[nxt[0]] = dist[cur] + nxt[1] que.append(nxt[0]) answer = len([1 for _, a in dist.items() if a <= K]) return answer
Python
UTF-8
371
2.96875
3
[]
no_license
char_list = ["a", "n", "t", "a", "a", "t", "n", "n", "a", "x", "u", "g", "a", "x", "a"] i=0 l=[] while i<len(char_list): j=0 b=[] count=0 while j<len(char_list): if char_list[i]==char_list[j]: count=count+1 j=j+1 b.append(char_list[i]) b.append(count) if b not in l: l.append(b) i=i+1 print(l)