language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,253
3.171875
3
[]
no_license
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Enumeration; /* * * Fragment kodu zrodlowego * public class JDBC implements Driver { public static final String PREFIX = "jdbc:sqlite:"; static { try { DriverManager.registerDriver(new JDBC()); } catch (SQLException e) { e.printStackTrace(); } } */ public class Driver { public static void main(String[] args) { try { Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ); Class.forName( "org.sqlite.JDBC" ); Class.forName( "org.postgresql.Driver" ); Class.forName( "com.mysql.jdbc.Driver" ); } catch ( ClassNotFoundException e ) { e.printStackTrace(); } // przegladamy zarejestrowane sterowniki do bazy danych Enumeration<java.sql.Driver> drivers = DriverManager.getDrivers(); for ( ; drivers.hasMoreElements();) System.out.println( drivers.nextElement() ); // ustanawiamy polaczenie z baza danych try { Connection con = DriverManager.getConnection( "jdbc:sqlite:/tmp/sample.db" ); System.out.println( "\nPolaczenie z baza danych con = " + con ); } catch (SQLException e) { e.printStackTrace(); } } }
TypeScript
UTF-8
4,139
2.859375
3
[]
no_license
import { Produccion } from "../analisis/Produccion"; import { Termino } from "../analisis/Termino"; import { NoTerminal } from "./NoTerminal"; export class PrimerosCalculator { private prodInicial: string; private producciones: Array<Produccion>; private noTerminalsTable: Array<NoTerminal>; constructor(proInicial: string, producciones: Array<Produccion>, noTerminalsTable: Array<NoTerminal>) { this.prodInicial = proInicial; this.producciones = producciones; this.noTerminalsTable = noTerminalsTable; } public getPrimeros() { let name: string = this.prodInicial; let pTemp: Array<Produccion> = new Array<Produccion>(); this.addProduccionesTemp(pTemp, name); this.calcularPrimeros(name, pTemp, 0); for (let i = 0; i < this.noTerminalsTable.length; i++) { let name: string = this.noTerminalsTable[i].getName(); let pTemp: Array<Produccion> = new Array<Produccion>(); this.addProduccionesTemp(pTemp, name); this.calcularPrimeros(name, pTemp, 0); }; } private calcularPrimeros(nameLeft: string, pTemp: Array<Produccion>, indexRight: number) { let nTermTblLeft: NoTerminal = this.getNoTermTbl(nameLeft); for (let p of pTemp) { let right: Termino = p.getRightSide()[indexRight]; if (right.getNombre() != 'lambda') { if (right.getIsTerminal()) { this.addToPrimeros(nTermTblLeft.getPrimeros(), right.getNombre()); } else { if (!nTermTblLeft.getIsNulable()) { if (nameLeft != right.getNombre()) { this.addPrimerosDeNoTerminal(right, nTermTblLeft); } } else { if (nameLeft != right.getNombre()) { this.addPrimerosDeNoTerminal(right, nTermTblLeft); if (indexRight < (p.getRightSide().length - 1)) { right = p.getRightSide()[++indexRight]; let nTermTblRight: NoTerminal = this.getNoTermTbl(right.getNombre()); if (nTermTblRight.getPrimeros().length == 0) { let left = right.getNombre(); let prodTemp: Array<Produccion> = []; this.addProduccionesTemp(prodTemp, left); this.calcularPrimeros(left, prodTemp, 0); } nTermTblRight.getPrimeros().forEach(p => { this.addToPrimeros(nTermTblLeft.getPrimeros(), p); }); } } else { //Evaluar solo siguientes siguientes } } } } } } private getNoTermTbl(nameNT: string): NoTerminal { return this.noTerminalsTable.find(e => e.getName() == nameNT); } private addToPrimeros(array: Array<string> , element: string) { if (array.find(e => e == element) == undefined) { array.push(element); } } private addProduccionesTemp(temp: Array<Produccion>, nameLeft: string) { this.producciones.forEach(p => { if (p.getLeftSide() == nameLeft) { temp.push(p); } }); } private addPrimerosDeNoTerminal(right: Termino, nTermTblLeft: NoTerminal) { let nTermTblRight: NoTerminal = this.getNoTermTbl(right.getNombre()); if (nTermTblRight.getPrimeros().length == 0) { let left = right.getNombre(); let prodTemp: Array<Produccion> = []; this.addProduccionesTemp(prodTemp, left); this.calcularPrimeros(left, prodTemp, 0); } nTermTblRight.getPrimeros().forEach(p => { this.addToPrimeros(nTermTblLeft.getPrimeros(), p); }); } }
C#
UTF-8
3,190
2.84375
3
[]
no_license
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Confluent.Kafka; using Microsoft.Extensions.DependencyInjection; using Kafka.Public; using Kafka.Public.Loggers; using System.Text; namespace SimpleHostedService { class Program { static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } //Register the consumer first so its ready and listening when the producer kicks off private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((context, collection) => { collection.AddHostedService<ConsumerHostedService>(); collection.AddHostedService<ProducerHostedService>(); }); } //Our consumer is using the Kafka-Sharp lib as an alternative to the official Confluence.Kafka lib //purely for learning expi public class ConsumerHostedService : IHostedService { private readonly ILogger<ConsumerHostedService> logger; private ClusterClient _cluster; public ConsumerHostedService(ILogger<ConsumerHostedService> logger) { this.logger = logger; _cluster = new ClusterClient(new Configuration { Seeds = "localhost:9092" }, new ConsoleLogger()); } public async Task StartAsync(CancellationToken cancellationToken) { _cluster.ConsumeFromLatest(topic: "SimpleHostedService"); _cluster.MessageReceived += record => { logger.LogInformation($"Receieved {Encoding.UTF8.GetString(record.Value as byte[])}"); }; } public Task StopAsync(CancellationToken cancellationToken) { _cluster?.Dispose(); return Task.CompletedTask; } } //Our producer is using the official Confluence.Kafka lib public class ProducerHostedService : IHostedService { private readonly ILogger<ProducerHostedService> logger; private IProducer<Null, string> _producer; public ProducerHostedService(ILogger<ProducerHostedService> logger) { this.logger = logger; var config = new ProducerConfig { BootstrapServers = "localhost:9092" }; _producer = new ProducerBuilder<Null, string>(config).Build(); } public async Task StartAsync(CancellationToken cancellationToken) { for (int i = 0; i < 100; i++) { var value =$"Hello World {i}"; logger.LogInformation(value); await _producer.ProduceAsync(topic: "SimpleHostedService", new Message<Null, string>() { Value = value }, cancellationToken); } _producer.Flush(TimeSpan.FromSeconds(10)); } public Task StopAsync(CancellationToken cancellationToken) { _producer?.Dispose(); return Task.CompletedTask; } } }
Python
UTF-8
185
3.140625
3
[]
no_license
names = ['marlon', 'Karla', 'Ursula'] print(f'Invite to dinner with me {names[0].title()}') print(f'Invite to dinner with me {names[1]}') print(f'Invite to dinner with me {names[2]}')
C++
UTF-8
2,393
3.671875
4
[]
no_license
#include <iostream> #include "Deck.h" #include "Card.h" using namespace std; int main() { srand(time(NULL)); // randomizes the seed for rand() function int userChoice = 0; Deck deck; while (userChoice != 5){ cout << endl << "Welcome to Solitaire Prime!\n" << "1) New Deck\n" << "2) Display Deck\n" << "3) Shuffle Deck\n" << "4) Play Solitaire Prime\n" << "5) Exit\n\n"; cin >> userChoice; if (userChoice == 1){ deck.refreshDeck(); } if (userChoice == 2){ deck.showDeck(); } if (userChoice == 3){ deck.shuffle(); } if (userChoice == 4){ bool isPrime; // will be used to determine whether to start a new pile or not int numPiles = 0; // number of piles in the game int sum = 0; // sum of cards in a pile Card cardDealt; // reference to the card that is dealt from the deck cout << "Playing Solitaire Prime!!!\n\n"; while (deck.cardsLeft() > 0){ cardDealt = deck.deal(); sum += cardDealt.getValue(); cardDealt.showCard(); cout << ", "; // Checking if our sum is a prime value isPrime = true; if (sum == 1) { isPrime = false; } else { for (int i = 2; i <= sum / 2; i++) { if (sum % i == 0) { // checking if the sum is a prime number isPrime = false; break; } } } if (isPrime){ cout << "Prime:" << sum << endl; // displays the prime sum of the pile sum = 0; // resetting the sum to prepare for the next pile numPiles++; // updating the number of piles by 1 if (deck.cardsLeft() == 0){ cout << "\nWinner in " << numPiles << " piles!" << endl; break; } } if (deck.cardsLeft() == 0) { cout << " Loser" << endl; } } } } return 0; }
TypeScript
UTF-8
2,750
2.515625
3
[ "Apache-2.0" ]
permissive
import { BaseURL } from '../../../Common/Roblox.Common/BaseUrl'; import { HttpClientInvoker } from '../../../Http/HttpClientInvoker/Roblox.Http.HttpClientInvoker/Implementation/HttpClientInvoker'; import { HttpRequestMethodEnum } from '../../../Http/Roblox.Http/Enumeration/HttpRequestMethodEnum'; import { Task } from '../../../../System/Threading/Task'; import { IUser } from '../../../Platform/Membership/Roblox.Platform.Membership/IUser'; import { IUniverse } from '../../../Platform/Universes/Roblox.Platform.Universes/IUniverse'; export class PointsClient { /** * This method checks the status of the api service. * @param isRequestSecure Request via a secure Url. * @returns {Task<[Boolean, Number, String]>} Returns a task that describes the status. */ public static async CheckHealth(isRequestSecure: boolean = true): Task<[Boolean, Number, String, String]> { return new Promise<[Boolean, Number, String, String]>(async (resumeFunction) => { const CheckHealthUrl = BaseURL.ConstructServicePathFromSubDomainSimple('points.api', 'checkhealth', isRequestSecure); const Client = new HttpClientInvoker({ Url: CheckHealthUrl, QueryString: { ApiKey: 'E3C6F569-496C-47F4-A76E-4F699DF453C4', }, AdditionalHeaders: {}, Payload: '', Method: HttpRequestMethodEnum.GET, }); const [Success, Response] = await Client.ExecuteAsync(); return resumeFunction([Success, Response.StatusCode, Response.StatusMessage, CheckHealthUrl]); }); } /** * Get the alltime points for the given IUser in the given IUniverse. * @param {IUser} user The user to check. * @param {IUniverse} universe The universe to check. * @param {boolean} isRequestSecure Is the request secure * @returns {Task<[Boolean, Number, String]>} Returns a Task the checks if the response was successful or not. */ public static async GetUserAllTimePoints( user: IUser, universe: IUniverse, isRequestSecure: boolean = true, ): Task<[Boolean, Number, any, Error]> { return new Promise<[Boolean, Number, any, Error]>(async (resumeFunction) => { const Url = BaseURL.ConstructServicePathFromSubDomainSimple('points.api', 'v1/GetUserAllTimePoints', isRequestSecure); const Payload = { universe, user, }; const Client = new HttpClientInvoker({ Url: Url, QueryString: { ApiKey: 'E3C6F569-496C-47F4-A76E-4F699DF453C4', }, AdditionalHeaders: { 'Content-Type': 'application/json' }, Payload: JSON.stringify(Payload), Method: HttpRequestMethodEnum.POST, FailedMessage: `Error getting the alltime points for the user ${user.Id} in the universe ${universe.Id}`, }); const [Success, Response, Error] = await Client.ExecuteAsync(); return resumeFunction([Success, Response.StatusCode, Response.ResponsePayload, Error]); }); } }
Python
UTF-8
1,292
4.09375
4
[]
no_license
'''exercise 10.8 birthday paradox''' from random import randint #returns true if a list has duplicate items in it , else false def has_duplicates(_list): for item in _list: if _list.count(item) > 1: return True return False #generates a class of 23 students with their birthdays as elements def generate_class(): _class=[] for i in range(23): _class.append(randint(1,365)) return _class #count the number of instances when a class has students with same birthdays in 1000 classes def count_duplicates(): count = 0 for index in range(1000): _class=generate_class() if has_duplicates(_class): count += 1 return count #Calculates the probability of birthday paradox by taking the average of 750 iterations def birthday_paradox(): _sum=0 for i in range(750): count=count_duplicates() _sum += count average = _sum / 750 probability = average/1000.0 * 100 print 'The chance that in a class of 23 students two having the same birthday is {}!'.format(probability) def repeat(): while True: birthday_paradox() prompt="continue?yes/no:" string=raw_input(prompt) if string=='no': print "Bye!" break def main(): repeat() if __name__=='__main__': print '*'*30,'\n' main() print '\n','*'*30
Shell
UTF-8
869
3.625
4
[]
no_license
#!/bin/sh -x CURRENT_DIR=$(dirname "$0") WORKING_DIR="$(dirname "$CURRENT_DIR")" CLASSPATH="$WORKING_DIR/lib/*:$WORKING_DIR/bin" # get java if [ -z "$JAVACMD" ] ; then if [ -n "$JAVA_HOME" ] ; then JAVACMD="$JAVA_HOME/bin/java" else JAVACMD="$(command -v java)" fi fi for src in "$@" do dir=$(dirname "$src") filename=$(basename -- "$src") filename="${filename%.*}" txt_file=$dir/$filename.txt json_file=$dir/$filename.json simp_file=$dir/$filename"_simp.txt" echo $src $txt_file $json_file $simp_file python scripts/docx2text.py "$src" "$txt_file" $JAVACMD -Xmx1024m -classpath "$CLASSPATH" main.Console -json "$txt_file" "$json_file" python scripts/generate_sentences.py "$json_file" "$simp_file" done #set -- "$@" #$JAVACMD -Xmx1024m -classpath "$CLASSPATH" main.Console -json $1 $2 #python scripts/generate_sentences.py $2 $3
Markdown
UTF-8
3,205
2.90625
3
[]
no_license
--- ID: 21353 post_title: > 5 reasons why your Dark Spot cream is not working like you thought it would. author: CureSkin staff post_excerpt: "" layout: post permalink: > https://cureskin.com/5-reasons-why-your-dark-spot-cream-is-not-working-like-you-thought-it-would/ published: true post_date: 2019-02-01 06:55:56 --- <span style="font-weight: 400;"><em>“Only fever and emergency situations need a doctor”</em> this is what you all must have thought. It’s a general trend among us to take self-treatments for small skin issues. But <em><strong>Dark Spots</strong></em> isn’t a one that can be healed with <em><strong>OTC medicines</strong></em> and <em><strong>home remedies</strong></em>. </span> <span style="font-weight: 400;"> </span><span style="font-weight: 400;">1.</span><em><b> With no proper prescription:</b></em><span style="font-weight: 400;"> You must have tried around 5 versions of the same over-the-counter products. Most dark spots require prescription medication, and only then it can make real progress once you start an appropriate, individualized treatment plan. </span><span style="font-weight: 400;"> </span><span style="font-weight: 400;"> </span><span style="font-weight: 400;">2.  </span><em><b>Too much or Too little:</b></em><span style="font-weight: 400;"> Dark spots requires only a thin layer of medication. Applying more will dry out your skin and will not cure dark spots.  Even applying too little cannot solve your problem. This is where you need an expert’s directions. </span><span style="font-weight: 400;"> </span><span style="font-weight: 400;"> </span><span style="font-weight: 400;">3. </span><em><b>Using mixed products on the spot and mixing products within regimen:</b></em><span style="font-weight: 400;"> you must be following a treatment your local doctor said but along with that, you must be using your daily skin products. Both these products have strong chemicals that can go react badly and leave your face with more dark spots.</span><span style="font-weight: 400;"> </span><span style="font-weight: 400;"> </span><span style="font-weight: 400;">4.</span><em><b> Not bothered about the “After”:</b></em><span style="font-weight: 400;"> You must have solved the issue partly and then once you start seeing your clear face you go back to your daily routine and slowly neglect the aftercare like applying sunscreen or finishing the medications course. Thus the issue bounces back in no time.</span><span style="font-weight: 400;"> </span><span style="font-weight: 400;"> </span><span style="font-weight: 400;">5. </span><em><b>Too late and Too wrong:</b></em><span style="font-weight: 400;"> you must have waited a long time to finally address your issue and act upon it. Along with it, you get all the wrong medications. Now your condition has worsened beyond self-care. And thus the dark spots stay.</span><span style="font-weight: 400;"> </span><span style="font-weight: 400;"> </span><em><strong>It is very important to get a Dermatologist to have a look at it and decide the treatment and that too as early as possible before things go wrong. Use the Cure Skin App wisely to solve all your skin problems.</strong></em>
Java
UTF-8
1,741
2.625
3
[]
no_license
package socs.network.node; import socs.network.util.Configuration; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.net.ServerSocket; import java.net.UnknownHostException; import java.net.SocketTimeoutException; public class ClientHandler implements Runnable { //private RouterDescription cr; private RouterDescription cr; public ClientHandler(RouterDescription cr) { this.cr = cr; //System.out.println(cr.simulatedIPAddress); } public void run() { //System.out.println("Starting Client to: " + cr.simulatedIPAddress.toString()); while(true){ try{ //System.out.println("HELLO"); Socket client = new Socket(cr.simulatedIPAddress, cr.processPortNumber); // set cr state to INIT or to TWO-WAY System.out.println("Just connected to" + client.getRemoteSocketAddress()); DataOutputStream out = new DataOutputStream(client.getOutputStream()); out.writeUTF("HELLO from" + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); }catch(SocketTimeoutException s){ System.out.println("Socket timed out!"); break; }catch(IOException e){ e.printStackTrace(); break; }catch(Exception e){ e.printStackTrace(); break; } } } }
PHP
UTF-8
695
2.765625
3
[]
no_license
<?php require('./db/db_connect.php'); function password_check($password,$pdo){ $today = date("Y-m-d"); $req = $pdo->query("SELECT count,date FROM pass_count WHERE date='$today'"); $req->bindColumn(1, $count); if(!$req->fetch(PDO::FETCH_BOUND)){ $pdo->query("INSERT INTO pass_count (count,date) VALUES ('0','$today')"); $count = 0; } if($count > 2) return "error: no more attempts for today."; if( !password_verify($password,APP_PASSWORD) ){ $count++; $pdo->query("UPDATE pass_count SET count = '$count' WHERE date='$today'"); return "error: wrong password, ".(3-$count)." attempts left."; } return "ok"; }
Python
UTF-8
3,423
3.078125
3
[]
no_license
import numpy as np MAX_PIXEL_CONSTANT = 255.0 BLUE_INDEX = 0 GREEN_INDEX = 1 RED_INDEX = 2 def d_max(bgr): hsv = np.array([0.0, 0.0, 0.0]) red = bgr[RED_INDEX] / MAX_PIXEL_CONSTANT blue = bgr[BLUE_INDEX] / MAX_PIXEL_CONSTANT green = bgr[GREEN_INDEX] / MAX_PIXEL_CONSTANT hsv[2] = max(red, blue, green) delta = hsv[2] - min(red, blue, green) if (hsv[2] == 0): hsv[1] = 0 else: hsv[1] = delta / hsv[2] return hsv def r_max(bgr): hsv = np.array([0.0, 0.0, 0.0]) red = bgr[RED_INDEX] / MAX_PIXEL_CONSTANT blue = bgr[BLUE_INDEX] / MAX_PIXEL_CONSTANT green = bgr[GREEN_INDEX] / MAX_PIXEL_CONSTANT hsv[2] = max(red, blue, green) delta = hsv[2] - min(red, blue, green) hsv[0] = (60 * ((green - blue) / delta)) % 360 * MAX_PIXEL_CONSTANT / 360 if (hsv[2] == 0): hsv[1] = 0 else: hsv[1] = delta / hsv[2] return hsv def g_max(bgr): hsv = np.array([0.0, 0.0, 0.0]) red = bgr[RED_INDEX] / MAX_PIXEL_CONSTANT blue = bgr[BLUE_INDEX] / MAX_PIXEL_CONSTANT green = bgr[GREEN_INDEX] / MAX_PIXEL_CONSTANT hsv[2] = max(red, blue, green) delta = hsv[2] - min(red, blue, green) hsv[0] = (60 * ((blue - red) / delta + 2)) * MAX_PIXEL_CONSTANT / 360 if (hsv[2] == 0): hsv[1] = 0 else: hsv[1] = delta / hsv[2] return hsv def b_max(bgr): hsv = np.array([0.0, 0.0, 0.0]) red = bgr[RED_INDEX] / MAX_PIXEL_CONSTANT blue = bgr[BLUE_INDEX] / MAX_PIXEL_CONSTANT green = bgr[GREEN_INDEX] / MAX_PIXEL_CONSTANT hsv[2] = max(red, blue, green) delta = hsv[2] - min(red, blue, green) hsv[0] = (60 * ((red - green) / delta + 4)) * MAX_PIXEL_CONSTANT / 360 if (hsv[2] == 0): hsv[1] = 0 else: hsv[1] = delta / hsv[2] return hsv def convert_pixel_to_hsv(bgr): red = bgr[RED_INDEX] blue = bgr[BLUE_INDEX] green = bgr[GREEN_INDEX] location = bgr.argmax(axis=0) if (max(red, blue, green) - min(red, blue, green) == 0): hsv = d_max(bgr) elif (location == 2): hsv = r_max(bgr) elif (location == 0): hsv = b_max(bgr) else: hsv = g_max(bgr) return hsv class BGRToHSV: def __init__(self, image_array): self.image_array = image_array self.image_height = image_array.shape[0] self.image_width = image_array.shape[1] self.hue = np.zeros([image_array.shape[0], image_array.shape[1], 3]) self.saturation = np.zeros([image_array.shape[0], image_array.shape[1], 3]) self.value = np.zeros([image_array.shape[0], image_array.shape[1], 3]) def extract_hsv_images(self): for current_height in range( self.image_height): # traverses through height of the image for current_width in range( self.image_width): # traverses through width of the image hsv_pixel = convert_pixel_to_hsv(self.image_array[ current_height][current_width]) hsv_int = np.array( [int(hsv_pixel[0]), int(hsv_pixel[1] * 255), int(hsv_pixel[2] * 255)]) self.hue[current_height][current_width] = hsv_int[0] self.saturation[current_height][current_width] = hsv_int[1] self.value[current_height][current_width] = hsv_int[2]
JavaScript
UTF-8
362
4.34375
4
[ "MIT" ]
permissive
const arr = [1,2,3,4,5] function map(arr) { const newArr = []; for(let i = 0; i < arr.length; i++) { newArr.push([arr[i] * i, arr])//what you want } return newArr } //what we made const mappedValue = arr.map((v, i, arr) => { return [v * i, arr] }) console.log(mappedValue) const functionValue = map(arr) console.log(functionValue)
Java
UTF-8
2,658
2.96875
3
[]
no_license
package methodEmbedding.Cookie_Clicker_Alpha.S.LYD67; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.*; import java.util.StringTokenizer; /** * * @author Hemang Jangle */ public class CookieClicker { static BufferedReader in; static PrintWriter out; static int numCases; static double c; static double f; static double x; static double speed; public static void main(String[] args) throws IOException { in = new BufferedReader(new FileReader("cookieClicker.in")); out = new PrintWriter(new FileWriter("cookieClicker.out")); speed = 2; numCases = Integer.parseInt(in.readLine()); for (int i = 1; i <= numCases; i++) { speed = 2; StringTokenizer st = new StringTokenizer(in.readLine()); c = Double.parseDouble(st.nextToken()); f = Double.parseDouble(st.nextToken()); x = Double.parseDouble(st.nextToken()); double time = x / speed; boolean done = false; while (!done) { speed += f; System.out.println("time1: " + time); double oldTime = time; time -= x / (speed - f); time += c / (speed - f); time += x / (speed); System.out.println(time); if (oldTime < time) { done = true; time = oldTime; System.out.println(""); } } out.println("Case #" + i + ": " + time); } /* * for(int i = 1; i <= numCases; i++){ StringTokenizer st = new * StringTokenizer(in.readLine()); c = * Double.parseDouble(st.nextToken()); f = * Double.parseDouble(st.nextToken()); x = * Double.parseDouble(st.nextToken()); out.println("Case #" + i + ": " + * evaluateTime()); } */ out.close(); System.exit(0); } /* public static double evaluateTime() { double time = 0; int i = 1; boolean done = false; while (!done) { if (i < (c * f + c * speed + f * x) / (c * f)) { done = true; } } time = x / (speed + i * f) + summation(i - 1); return time; } public static double summation(int high) { double sum = 0; for (int i = 0; i <= high; i++) { sum += c / (speed + i * f); } return sum; } * */ }
Java
UTF-8
2,680
1.960938
2
[ "MIT" ]
permissive
package com.dyteam.testApps.webserver.controller; import java.util.Map; import com.dyteam.testApps.webserver.entity.ApplicationPaths; import com.dyteam.testApps.webserver.entity.EmailConfigurations; import com.dyteam.testApps.webserver.repository.ApplicationPathsRepository; import com.dyteam.testApps.webserver.repository.EmailConfigurationsRepository; import com.dyteam.testApps.webserver.security.LoginUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; 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.RestController; @RestController @RequestMapping("/applicationPaths") public class ApplicationPathsController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired ApplicationPathsRepository applicationPathsRepository; @PostMapping("/save") public ApplicationPaths save(@RequestBody ApplicationPaths applicationPaths, @AuthenticationPrincipal final LoginUser loggedInUser) { logger.info("save ApplicationPaths = " + applicationPaths); applicationPaths.setAddedBy(loggedInUser.getUserId()); return applicationPathsRepository.save(applicationPaths); } @PostMapping("/edit") public ApplicationPaths edit(@RequestBody ApplicationPaths applicationPaths, @AuthenticationPrincipal final LoginUser loggedInUser) { applicationPathsRepository.deleteById(applicationPaths.getId()); logger.info("save ApplicationPaths = " + applicationPaths); applicationPaths.setAddedBy(loggedInUser.getUserId()); return applicationPathsRepository.save(applicationPaths); } @DeleteMapping(value = "/delete/{id}") public boolean delete(@AuthenticationPrincipal final LoginUser loggedInUser, @PathVariable(value = "id") Long id) { logger.info("id" + id); applicationPathsRepository.deleteById(id); return true; } @GetMapping(value = "/all") public Iterable<Map<String, Object>> getAllApplicationPaths() { logger.info("Inside getAllApplicationPaths"); Iterable<Map<String, Object>> applicationPaths = applicationPathsRepository.fetchAll(); return applicationPaths; } }
JavaScript
UTF-8
224
3.484375
3
[]
no_license
// Task #5 function reverseNumber(a) { let arr = '' + Math.abs(a); let num = ''; for(let i = arr.length - 1; i >= 0; i--) { num += arr[i]; } return a < 0 ? -num : +num; } reverseNumber(-456);
C
UTF-8
720
3.5625
4
[]
no_license
#include <stdio.h> void error_message(void); int get_month(void); void error_message(void){ printf("入力ミスです!\n"); } int get_month(void){ int month; do{ printf("月:"); scanf("%d",&month); if(month<1||month>12) error_message(); }while(month<1||month>12); return month; } int main(){ int birth,month; printf("<誕生日の月>\n"); birth=get_month(); printf("<現在の月>\n"); month=get_month(); if(birth==month){ printf("今月が誕生日ですね\n"); }else if(month>birth){ printf("誕生日まであと%dヶ月ですね\n",12-month+birth); }else{ printf("誕生日まであと%dヶ月ですね\n",12-birth+month); } return 0; }
Markdown
UTF-8
20,589
2.921875
3
[]
no_license
Chaincode for Developers ======================== What is Chaincode? ------------------ Chaincode is a program, written in [Go](https://golang.org), [node.js](https://nodejs.org), that implements a prescribed interface. Eventually, other programming languages such as Java, will be supported. Chaincode runs in a secured Docker container isolated from the endorsing peer process. Chaincode initializes and manages the ledger state through transactions submitted by applications. A chaincode typically handles business logic agreed to by members of the network, so it similar to a \"smart contract\". Ledger state created by a chaincode is scoped exclusively to that chaincode and can\'t be accessed directly by another chaincode. Given the appropriate permission, a chaincode may invoke another chaincode to access its state within the same network. In the following sections, we will explore chaincode through the eyes of an application developer. We\'ll present a simple chaincode sample application and walk through the purpose of each method in the Chaincode Shim API. Chaincode API ------------- Every chaincode program must implement the `Chaincode interface`: > - [Go](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#Chaincode) > - [node.js](https://fabric-shim.github.io/ChaincodeInterface.html) whose methods are called in response to received transactions. In particular the `Init` method is called when a chaincode receives an `instantiate` or `upgrade` transaction so that the chaincode may perform any necessary initialization, including initialization of application state. The `Invoke` method is called in response to receiving an `invoke` transaction to process transaction proposals. The other interface in the chaincode \"shim\" APIs is the `ChaincodeStubInterface`: > - [Go](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeStub) > - [node.js](https://fabric-shim.github.io/ChaincodeStub.html) which is used to access and modify the ledger, and to make invocations between chaincodes. In this tutorial, we will demonstrate the use of these APIs by implementing a simple chaincode application that manages simple \"assets\". ::: {#Simple Asset Chaincode} Simple Asset Chaincode ---------------------- ::: Our application is a basic sample chaincode to create assets (key-value pairs) on the ledger. ### Choosing a Location for the Code If you haven\'t been doing programming in Go, you may want to make sure that you have [Golang]{role="ref"} installed and your system properly configured. Now, you will want to create a directory for your chaincode application as a child directory of `$GOPATH/src/`. To keep things simple, let\'s use the following command: ``` {.sourceCode .bash} mkdir -p $GOPATH/src/sacc && cd $GOPATH/src/sacc ``` Now, let\'s create the source file that we\'ll fill in with code: ``` {.sourceCode .bash} touch sacc.go ``` ### Housekeeping First, let\'s start with some housekeeping. As with every chaincode, it implements the [Chaincode interface](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#Chaincode) in particular, `Init` and `Invoke` functions. So, let\'s add the go import statements for the necessary dependencies for our chaincode. We\'ll import the chaincode shim package and the [peer protobuf package](http://godoc.org/github.com/hyperledger/fabric/protos/peer). Next, let\'s add a struct `SimpleAsset` as a receiver for Chaincode shim functions. ``` {.sourceCode .go} package main import ( "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" "github.com/hyperledger/fabric/protos/peer" ) // SimpleAsset implements a simple chaincode to manage an asset type SimpleAsset struct { } ``` ### Initializing the Chaincode Next, we\'ll implement the `Init` function. ``` {.sourceCode .go} // Init is called during chaincode instantiation to initialize any data. func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response { } ``` ::: {.note} ::: {.admonition-title} Note ::: Note that chaincode upgrade also calls this function. When writing a : chaincode that will upgrade an existing one, make sure to modify the `Init` function appropriately. In particular, provide an empty \"Init\" method if there\'s no \"migration\" or nothing to be initialized as part of the upgrade. ::: Next, we\'ll retrieve the arguments to the `Init` call using the [ChaincodeStubInterface.GetStringArgs](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeStub.GetStringArgs) function and check for validity. In our case, we are expecting a key-value pair. > ``` {.sourceCode .go} > // Init is called during chaincode instantiation to initialize any > // data. Note that chaincode upgrade also calls this function to reset > // or to migrate data, so be careful to avoid a scenario where you > // inadvertently clobber your ledger's data! > func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response { > // Get the args from the transaction proposal > args := stub.GetStringArgs() > if len(args) != 2 { > return shim.Error("Incorrect arguments. Expecting a key and a value") > } > } > ``` Next, now that we have established that the call is valid, we\'ll store the initial state in the ledger. To do this, we will call [ChaincodeStubInterface.PutState](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeStub.PutState) with the key and value passed in as the arguments. Assuming all went well, return a peer.Response object that indicates the initialization was a success. ``` {.sourceCode .go} // Init is called during chaincode instantiation to initialize any // data. Note that chaincode upgrade also calls this function to reset // or to migrate data, so be careful to avoid a scenario where you // inadvertently clobber your ledger's data! func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response { // Get the args from the transaction proposal args := stub.GetStringArgs() if len(args) != 2 { return shim.Error("Incorrect arguments. Expecting a key and a value") } // Set up any variables or assets here by calling stub.PutState() // We store the key and the value on the ledger err := stub.PutState(args[0], []byte(args[1])) if err != nil { return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0])) } return shim.Success(nil) } ``` ### Invoking the Chaincode First, let\'s add the `Invoke` function\'s signature. ``` {.sourceCode .go} // Invoke is called per transaction on the chaincode. Each transaction is // either a 'get' or a 'set' on the asset created by Init function. The 'set' // method may create a new asset by specifying a new key-value pair. func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response { } ``` As with the `Init` function above, we need to extract the arguments from the `ChaincodeStubInterface`. The `Invoke` function\'s arguments will be the name of the chaincode application function to invoke. In our case, our application will simply have two functions: `set` and `get`, that allow the value of an asset to be set or its current state to be retrieved. We first call [ChaincodeStubInterface.GetFunctionAndParameters](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeStub.GetFunctionAndParameters) to extract the function name and the parameters to that chaincode application function. ``` {.sourceCode .go} // Invoke is called per transaction on the chaincode. Each transaction is // either a 'get' or a 'set' on the asset created by Init function. The Set // method may create a new asset by specifying a new key-value pair. func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response { // Extract the function and args from the transaction proposal fn, args := stub.GetFunctionAndParameters() } ``` Next, we\'ll validate the function name as being either `set` or `get`, and invoke those chaincode application functions, returning an appropriate response via the `shim.Success` or `shim.Error` functions that will serialize the response into a gRPC protobuf message. ``` {.sourceCode .go} // Invoke is called per transaction on the chaincode. Each transaction is // either a 'get' or a 'set' on the asset created by Init function. The Set // method may create a new asset by specifying a new key-value pair. func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response { // Extract the function and args from the transaction proposal fn, args := stub.GetFunctionAndParameters() var result string var err error if fn == "set" { result, err = set(stub, args) } else { result, err = get(stub, args) } if err != nil { return shim.Error(err.Error()) } // Return the result as success payload return shim.Success([]byte(result)) } ``` ### Implementing the Chaincode Application As noted, our chaincode application implements two functions that can be invoked via the `Invoke` function. Let\'s implement those functions now. Note that as we mentioned above, to access the ledger\'s state, we will leverage the [ChaincodeStubInterface.PutState](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeStub.PutState) and [ChaincodeStubInterface.GetState](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeStub.GetState) functions of the chaincode shim API. ``` {.sourceCode .go} // Set stores the asset (both key and value) on the ledger. If the key exists, // it will override the value with the new one func set(stub shim.ChaincodeStubInterface, args []string) (string, error) { if len(args) != 2 { return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value") } err := stub.PutState(args[0], []byte(args[1])) if err != nil { return "", fmt.Errorf("Failed to set asset: %s", args[0]) } return args[1], nil } // Get returns the value of the specified asset key func get(stub shim.ChaincodeStubInterface, args []string) (string, error) { if len(args) != 1 { return "", fmt.Errorf("Incorrect arguments. Expecting a key") } value, err := stub.GetState(args[0]) if err != nil { return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err) } if value == nil { return "", fmt.Errorf("Asset not found: %s", args[0]) } return string(value), nil } ``` ::: {#Chaincode Sample} ### Pulling it All Together ::: Finally, we need to add the `main` function, which will call the [shim.Start](http://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#Start) function. Here\'s the whole chaincode program source. ``` {.sourceCode .go} package main import ( "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" "github.com/hyperledger/fabric/protos/peer" ) // SimpleAsset implements a simple chaincode to manage an asset type SimpleAsset struct { } // Init is called during chaincode instantiation to initialize any // data. Note that chaincode upgrade also calls this function to reset // or to migrate data. func (t *SimpleAsset) Init(stub shim.ChaincodeStubInterface) peer.Response { // Get the args from the transaction proposal args := stub.GetStringArgs() if len(args) != 2 { return shim.Error("Incorrect arguments. Expecting a key and a value") } // Set up any variables or assets here by calling stub.PutState() // We store the key and the value on the ledger err := stub.PutState(args[0], []byte(args[1])) if err != nil { return shim.Error(fmt.Sprintf("Failed to create asset: %s", args[0])) } return shim.Success(nil) } // Invoke is called per transaction on the chaincode. Each transaction is // either a 'get' or a 'set' on the asset created by Init function. The Set // method may create a new asset by specifying a new key-value pair. func (t *SimpleAsset) Invoke(stub shim.ChaincodeStubInterface) peer.Response { // Extract the function and args from the transaction proposal fn, args := stub.GetFunctionAndParameters() var result string var err error if fn == "set" { result, err = set(stub, args) } else { // assume 'get' even if fn is nil result, err = get(stub, args) } if err != nil { return shim.Error(err.Error()) } // Return the result as success payload return shim.Success([]byte(result)) } // Set stores the asset (both key and value) on the ledger. If the key exists, // it will override the value with the new one func set(stub shim.ChaincodeStubInterface, args []string) (string, error) { if len(args) != 2 { return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value") } err := stub.PutState(args[0], []byte(args[1])) if err != nil { return "", fmt.Errorf("Failed to set asset: %s", args[0]) } return args[1], nil } // Get returns the value of the specified asset key func get(stub shim.ChaincodeStubInterface, args []string) (string, error) { if len(args) != 1 { return "", fmt.Errorf("Incorrect arguments. Expecting a key") } value, err := stub.GetState(args[0]) if err != nil { return "", fmt.Errorf("Failed to get asset: %s with error: %s", args[0], err) } if value == nil { return "", fmt.Errorf("Asset not found: %s", args[0]) } return string(value), nil } // main function starts up the chaincode in the container during instantiate func main() { if err := shim.Start(new(SimpleAsset)); err != nil { fmt.Printf("Error starting SimpleAsset chaincode: %s", err) } } ``` ### Building Chaincode Now let\'s compile your chaincode. ``` {.sourceCode .bash} go get -u --tags nopkcs11 github.com/hyperledger/fabric/core/chaincode/shim go build --tags nopkcs11 ``` Assuming there are no errors, now we can proceed to the next step, testing your chaincode. ### Testing Using dev mode Normally chaincodes are started and maintained by peer. However in "dev mode\", chaincode is built and started by the user. This mode is useful during chaincode development phase for rapid code/build/run/debug cycle turnaround. We start \"dev mode\" by leveraging pre-generated orderer and channel artifacts for a sample dev network. As such, the user can immediately jump into the process of compiling chaincode and driving calls. Install Hyperledger Fabric Samples \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-- If you haven\'t already done so, please install the [samples]{role="doc"}. Navigate to the `chaincode-docker-devmode` directory of the `fabric-samples` clone: ``` {.sourceCode .bash} cd chaincode-docker-devmode ``` Download Docker images ---------------------- We need four Docker images in order for \"dev mode\" to run against the supplied docker compose script. If you installed the `fabric-samples` repo clone and followed the instructions to [binaries]{role="ref"}, then you should have the necessary Docker images installed locally. ::: {.note} ::: {.admonition-title} Note ::: If you choose to manually pull the images then you must retag them as : `latest`. ::: Issue a `docker images` command to reveal your local Docker Registry. You should see something similar to following: ``` {.sourceCode .bash} docker images REPOSITORY TAG IMAGE ID CREATED SIZE hyperledger/fabric-tools latest e09f38f8928d 4 hours ago 1.32 GB hyperledger/fabric-tools x86_64-1.0.0 e09f38f8928d 4 hours ago 1.32 GB hyperledger/fabric-orderer latest 0df93ba35a25 4 hours ago 179 MB hyperledger/fabric-orderer x86_64-1.0.0 0df93ba35a25 4 hours ago 179 MB hyperledger/fabric-peer latest 533aec3f5a01 4 hours ago 182 MB hyperledger/fabric-peer x86_64-1.0.0 533aec3f5a01 4 hours ago 182 MB hyperledger/fabric-ccenv latest 4b70698a71d3 4 hours ago 1.29 GB hyperledger/fabric-ccenv x86_64-1.0.0 4b70698a71d3 4 hours ago 1.29 GB ``` ::: {.note} ::: {.admonition-title} Note ::: If you retrieved the images through the [binaries]{role="ref"}, : then you will see additional images listed. However, we are only concerned with these four. ::: Now open three terminals and navigate to your `chaincode-docker-devmode` directory in each. Terminal 1 - Start the network ------------------------------ ``` {.sourceCode .bash} docker-compose -f docker-compose-simple.yaml up ``` The above starts the network with the `SingleSampleMSPSolo` orderer profile and launches the peer in \"dev mode\". It also launches two additional containers -one for the chaincode environment and a CLI to interact with the chaincode. The commands for create and join channel are embedded in the CLI container, so we can jump immediately to the chaincode calls. Terminal 2 - Build & start the chaincode ---------------------------------------- ``` {.sourceCode .bash} docker exec -it chaincode bash ``` You should see the following: ``` {.sourceCode .bash} root@d2629980e76b:/opt/gopath/src/chaincode# ``` Now, compile your chaincode: ``` {.sourceCode .bash} cd sacc go build ``` Now run the chaincode: ``` {.sourceCode .bash} CORE_PEER_ADDRESS=peer:7052 CORE_CHAINCODE_ID_NAME=mycc:0 ./sacc ``` The chaincode is started with peer and chaincode logs indicating successful registration with the peer. Note that at this stage the chaincode is not associated with any channel. This is done in subsequent steps using the `instantiate` command. Terminal 3 - Use the chaincode ------------------------------ Even though you are in `--peer-chaincodedev` mode, you still have to install the chaincode so the life-cycle system chaincode can go through its checks normally. This requirement may be removed in future when in `--peer-chaincodedev` mode. We\'ll leverage the CLI container to drive these calls. ``` {.sourceCode .bash} docker exec -it cli bash ``` ``` {.sourceCode .bash} peer chaincode install -p chaincodedev/chaincode/sacc -n mycc -v 0 peer chaincode instantiate -n mycc -v 0 -c '{"Args":["a","10"]}' -C myc ``` Now issue an invoke to change the value of \"a\" to \"20\". ``` {.sourceCode .bash} peer chaincode invoke -n mycc -c '{"Args":["set", "a", "20"]}' -C myc ``` Finally, query `a`. We should see a value of `20`. ``` {.sourceCode .bash} peer chaincode query -n mycc -c '{"Args":["query","a"]}' -C myc ``` Testing new chaincode --------------------- By default, we mount only `sacc`. However, you can easily test different chaincodes by adding them to the `chaincode` subdirectory and relaunching your network. At this point they will be accessible in your `chaincode` container. Chaincode encryption -------------------- In certain scenarios, it may be useful to encrypt values associated with a key in their entirety or simply in part. For example, if a person\'s social security number or address was being written to the ledger, then you likely would not want this data to appear in plaintext. Chaincode encryption is achieved by leveraging the [entities extension](https://github.com/hyperledger/fabric/tree/master/core/chaincode/shim/ext/entities) which is a BCCSP wrapper with commodity factories and functions to perform cryptographic operations such as encryption and elliptic curve digital signatures. For example, to encrypt, the invoker of a chaincode passes in a cryptographic key via the transient field. The same key may then be used for subsequent query operations, allowing for proper decryption of the encrypted state values. For more information and samples, see the [Encc Example](https://github.com/hyperledger/fabric/tree/master/examples/chaincode/go/enccc_example) within the `fabric/examples` directory. Pay specific attention to the `utils.go` helper program. This utility loads the chaincode shim APIs and Entities extension and builds a new class of functions (e.g. `encryptAndPutState` & `getStateAndDecrypt`) that the sample encryption chaincode then leverages. As such, the chaincode can now marry the basic shim APIs of `Get` and `Put` with the added functionality of `Encrypt` and `Decrypt`.
C
UTF-8
1,410
3.546875
4
[]
no_license
#include <stdio.h> #define MAGICR 5 #define MAGICC 5 int main() { int magic[MAGICR][MAGICC] = {{17,24,1,8,15}, {23,5,7,14,16}, {4,6,13,20,22}, {10,12,19,21,3}, {11,18,25,2,9}}; int i,j; //print out the table for ( i = 0; i < 5; i++) { for ( j = 0; j < 5; j++) { if (j!=4) { printf("%d\t", magic[i][j]); } else printf("%d\n", magic[i][j]); } } int row,col,rsum=0,csum=0; /*caculate the sum and compare them*/ printf("let's caculate row sum first\n"); for(col=0;col<MAGICC;col++) { for(row=0;row<MAGICR;row++) { rsum += magic[row][col]; } printf("row sum is :%d\n",rsum ); if(col<MAGICC) rsum = 0; } printf("now lt's caculate the col sum\n"); for(row=0;row<MAGICR;row++) { for(col=0;col<MAGICC;col++) { csum += magic[row][col]; } printf("col sum is :%d\n",csum ); if(row<MAGICR) csum = 0; } printf("what about the diagonals?\n"); //caculate the dia sum to see if they match int dsum = 0; for(row=0;row<MAGICR;row++) { dsum += magic[row][row]; if(row==MAGICR-1) printf("dia sum is :%d\n",dsum ); } dsum = 0; for(col=0;col<MAGICC;col++) { dsum += magic[col][col]; if(col==MAGICC-1) printf("dia sum is :%d\n",dsum ); } if(rsum==csum&&csum==dsum) printf("this is a magic squre.\n"); else printf("sorry.this isn't a magic squre.\n"); return 0; }
C++
UTF-8
1,035
2.8125
3
[]
no_license
string Solution::longestPalindrome(string A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details int maxlength=1; int start=0; int length=A.size(); for(int i=1;i<length;i++){ int low=i-1; int high=i; while(low>=0 && high<length && A[low]==A[high]){ if(high-low+1>maxlength){ maxlength=high-low+1; start=low; } low--; high++; } low=i-1; high=i+1; while(low>=0 && high<length && A[low]==A[high]){ if(high-low+1>maxlength){ maxlength=high-low+1; start=low; } low--; high++; } } string out; for(int i=start;i<start+maxlength;i++) out=out+A[i]; return out; }
JavaScript
UTF-8
7,046
2.71875
3
[]
no_license
//Object holding food items at various stages var items={ nutriFood:[], mealFood:[], mealLabel:[], //Holds objects containing calorie total per mealtype mealLabelIndex:0, getMapData:function(query){ //Fn that fetches chart axis data points var arr=[]; if(query==='label'){ this.mealLabel.forEach(function(value){ arr.push(value.name); }); } else{ this.mealLabel.forEach(function(value){ arr.push(value.calories); }); } return arr; } }; //Object for searching food items var handler={ find:function(){ var foodType=document.getElementById("foodType"); var exists=false; items.mealLabel.forEach(function(obj,index){ if(obj.name===foodType.value){ items.mealLabelIndex=index; exists=true; } }); if(!exists){ items.mealLabel.push({ name:foodType.value, calories:0 }); } var searchField=document.getElementById("search"); connection.searchPara=encodeURIComponent(searchField.value); connection.nutritionix(foodType.value,items.mealLabelIndex); foodType.value=""; items.mealLabelIndex++; //Ready for next mealType }, }; // Object containing display methods var display={ showNutriFood:function(){ var list=document.getElementById('nutriFoodList'); //Clear list and meal Btns list.innerHTML=''; document.getElementById('mealBtnContainer').style.display='none'; //Populate List items.nutriFood.forEach(function(obj,index){ var listItem=document.createElement('li'); listItem.textContent='Name: '+obj.brand_name+' Calories: '+obj.nf_calories+' Fat: '+obj.nf_total_fat+' Total:'+obj.count; listItem.id=index; listItem.className='nutriList' listItem.setAttribute('data-foodId',obj.id); list.appendChild(listItem); }); }, showMealOptions:function(){ //Clear list var list=document.getElementById('nutriFoodList'); list.innerHTML=''; //Populate Btns var mealBtnDiv=document.getElementById('mealBtnContainer'); mealBtnDiv.style.display='initial'; mealBtnDiv.innerHTML=''; items.mealLabel.forEach(function(val){ var newBtn=document.createElement('button'); newBtn.textContent=val.name; mealBtnDiv.appendChild(newBtn); }); }, showMealFood:function(type){ var list=document.getElementById('nutriFoodList'); list.innerHTML=''; items.mealFood.forEach(function(obj){ //Check button type with meal Type if(obj.foodType===type){ var listItem=document.createElement('li'); listItem.textContent=' Name: '+obj.brand_name+' Calories: '+obj.nf_calories+' Fat: '+obj.nf_total_fat+' Total:'+obj.count; list.appendChild(listItem); } }); }, drawChart: function(){ var chartData = { labels: items.getMapData('label'), datasets: [ { label: "My First dataset", fill: false, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 3 , pointHitRadius: 10, data: items.getMapData('cals'), spanGaps: false, } ] }; //Draw chart on every selection new Chart(ctx, { type: 'line', data: chartData, options:{ responsive:true, scaleShowVerticalLines: false, scaleShowHorizontalLines: false, scales: { xAxes:[{ gridLines: { display: false, color:'rgba(255,255,255,0.57)' } }], yAxes: [{ display: true, ticks: { suggestedMin: 0, beginAtZero: true }, gridLines:{ display: true , color:'rgba(255,255,255,0.2)'} }] } } }); } //End draw chart } //Nutrtionix API Parameters & Connection var connection={ fields:{ fields:'item_name,item_id,brand_name,nf_calories,nf_total_fat', appId:'34049f5a', appKey:'327ef7cf036f1136b3aeea53dc207ffe' }, url:'https://api.nutritionix.com/v1_1/search/', nutritionix:function(foodType,mealLabelIndex){ $.ajax({ url:this.url+this.searchPara, type:'get', data:this.fields, success:function(res){ items.nutriFood=[]; res.hits.forEach(function(val){ items.nutriFood.push({ id:val._id, brand_name: val.fields.brand_name, nf_calories: val.fields.nf_calories, nf_total_fat: val.fields.nf_total_fat, foodType:foodType, count:1, mealLabelIndex:mealLabelIndex }); }); //End foreach display.showNutriFood(); } //End success }); //End ajax } //End nutritionic fn }; //IIFE for detecting Selection List events (function(){ var list=document.getElementById('nutriFoodList'); list.addEventListener('click',function(event){ var listItem=event.target; if(listItem.className==='nutriList'){ var itemExists=false; //If food exists,incr count and calories items.mealFood.forEach(function(obj){ if(obj.id===listItem.getAttribute('data-foodId')){ itemExists=true; obj.count++; obj.nf_calories+=obj.nf_calories; obj.nf_total_fat+=obj.nf_total_fat; } }); //End foreach //Otherwise just push it in array if(!itemExists) items.mealFood.push(items.nutriFood[listItem.id]); //Incr cals for mealType of selected item var index=items.nutriFood[listItem.id].mealLabelIndex; items.mealLabel[index].calories+=items.nutriFood[listItem.id].nf_calories; display.showNutriFood(); //Build chart data on every click display.drawChart(); } });//End of event listener })(); //End of iife //IIFE for activating find button (function(){ var foodType=document.getElementById("foodType"); foodType.addEventListener('keyup',function(){ var findBtn=document.querySelector("input[type='button']"); if(this.value!=="") findBtn.disabled=false; else findBtn.disabled=true; }); })();//End of IIFE //IIFE for detecting Meal Button Events (function(){ var mealBtnDiv=document.getElementById('mealBtnContainer'); mealBtnDiv.addEventListener('click',function(event){ //Show food items for selected Meal Type if(event.target.tagName='BUTTON'){ display.showMealFood(event.target.textContent); } });//End event listener })();//End of IIFE var ctx=document.getElementById('mealChart').getContext('2d'); Chart.defaults.global.defaultFontColor = '#ecf0f1'; Chart.defaults.global.defaultFontSize =14; Chart.defaults.global.maintainAspectRatio = false; Chart.defaults.global.elements.line.borderWidth=4.5;
Java
UTF-8
1,229
3.390625
3
[]
no_license
package friend; public abstract class Friend { private String name; // 친구의 이름 private String phoneNumber; // 전화번호 private String addr; // 주소 // 생성자를 통해서 인스턴스 변수들을 초기화 Friend(String name, String pNum, String addr){ this.name=name; this.phoneNumber=pNum; this.addr=addr; } public String getName() { return name; } public String getPhoneNumber() { return phoneNumber; } public String getAddr() { return addr; } // 오버라이딩 처리 : 상속하는 클래스의 추가 속성을 출력 public void showData() { System.out.println("이름 : " + name); System.out.println("전화 : " + phoneNumber); System.out.println("주소 : " + addr); } // 오버라이딩 : 비어있는 처리부에 기능을 추가(자손클래스에서) // public void showBasicInfo() { // // } public abstract void showBasicInfo(); }
Java
UTF-8
2,580
2.15625
2
[ "Apache-2.0" ]
permissive
package cjlu.skyline.ecms_data_annotator.api.controller; import java.util.Arrays; import java.util.Map; import cjlu.skyline.ecms_data_annotator.common.utils.PageUtils; import cjlu.skyline.ecms_data_annotator.common.utils.R; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import cjlu.skyline.ecms_data_annotator.api.entity.DocLabelEntity; import cjlu.skyline.ecms_data_annotator.api.service.DocLabelService; /** * * * @author jinpenglin * @email nsp4289@autuni.ac.nz * @date 2021-01-11 15:35:16 */ @RestController @RequestMapping("annotator/doclabel") public class DocLabelController { @Autowired private DocLabelService docLabelService; /** * 列表 */ @ApiOperation("Get document's annotations list") @ApiImplicitParam(name = "params", value = "documents' annotations") @GetMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = docLabelService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @ApiOperation("Get document annotations by ID") @ApiImplicitParam(name = "docLabelId", value = "document annotation's ID") @GetMapping("/info/{docLabelId}") public R info(@PathVariable("docLabelId") Long docLabelId){ DocLabelEntity docLabel = docLabelService.getById(docLabelId); return R.ok().put("docLabel", docLabel); } /** * 保存 */ @ApiOperation("Save new document labels") @ApiImplicitParam(name = "docLabel",value = "document label") @PostMapping("/save") public R save(@RequestBody DocLabelEntity docLabel){ docLabelService.save(docLabel); return R.ok(); } /** * 修改 */ @ApiOperation("Update document labels") @ApiImplicitParam(name = "docLabel",value = "document label") @PostMapping("/update") public R update(@RequestBody DocLabelEntity docLabel){ docLabelService.updateById(docLabel); return R.ok(); } /** * 删除 */ @ApiOperation("Delete document labels") @ApiImplicitParam(name = "docLabelIds",value = "document label IDs") @PostMapping("/delete") public R delete(@RequestBody Long[] docLabelIds){ docLabelService.removeByIds(Arrays.asList(docLabelIds)); return R.ok(); } }
Python
UTF-8
6,683
2.59375
3
[ "MIT" ]
permissive
import asyncio import logging from typing import Any, Dict, List, Set from warnings import warn from discord import RawReactionActionEvent, User from discord.ext.commands import Context from dpymenus import ButtonMenu, ButtonsError, EventError, PagesError, SessionError from dpymenus.hooks import call_hook class Poll(ButtonMenu): """Represents a Poll menu. :param ctx: A reference to the command context. """ def __init__(self, ctx: Context): super().__init__(ctx) self.voted: Set[User] = set() def __repr__(self): return f'Poll(pages={[p.__str__() for p in self.pages]}, page={self.page.index}, timeout={self.timeout}, data={self.data})' # Utility Methods async def results(self) -> Dict[str, int]: """Utility method to get a dictionary of poll results.""" return {choice: len(voters) for choice, voters in self.data.items()} async def add_results_fields(self): """Utility method to add new fields to your next page automatically.""" for choice, voters in self.data.items(): next_page = self.pages[self.page.index + 1] next_page.add_field(name=choice, value=str(len(voters))) async def generate_results_page(self): """Utility method to build your entire results page automatically.""" next_page = self.pages[self.page.index + 1] await self.add_results_fields() highest_value = max(self.data.values()) winning_key = {choice for choice, voters in self.data.items() if voters == highest_value} if len(highest_value) == 0: next_page.description = ' '.join([next_page.description, f'It\'s a draw!']) else: next_page.description = ' '.join([next_page.description, f'{str(next(iter(winning_key)))} wins!']) async def open(self): """The entry point to a new Poll instance; starts the main menu loop. Manages gathering user input, basic validation, sending messages, and cancellation requests.""" try: self._validate_callbacks() await super()._open() except SessionError as exc: logging.info(exc.message) else: await self._set_data() await self._add_buttons() await call_hook(self, '_hook_after_open') pending = set() while self.active: try: _, pending = await asyncio.wait( [ asyncio.create_task(self._get_vote_add()), asyncio.create_task(self._get_vote_remove()), asyncio.create_task(self._poll_timer()), ], return_when=asyncio.FIRST_COMPLETED, ) finally: for task in pending: task.cancel() await self._finish_poll() # Internal Methods async def _get_vote_add(self): """Watches for a user adding a reaction on the Poll. Adds them to the relevant state_field values.""" while True: try: reaction_event = await self.ctx.bot.wait_for( 'raw_reaction_add', timeout=self.timeout, check=self._check_reaction ) except asyncio.TimeoutError: return else: if reaction_event.emoji.name in self.page.buttons_list: self.data[reaction_event.emoji.name].add(reaction_event.user_id) async def _get_vote_remove(self): """Watches for a user removing a reaction on the Poll. Removes them from the relevant state_field values.""" while True: try: reaction_event = await self.ctx.bot.wait_for( 'raw_reaction_remove', timeout=self.timeout, check=self._check_reaction, ) except asyncio.TimeoutError: return else: if reaction_event.emoji.name in self.page.buttons_list: self.data[reaction_event.emoji.name].remove(reaction_event.user_id) def _check_reaction(self, event: RawReactionActionEvent) -> bool: """Returns true only if the reaction event member is not a bot (ie. excludes self from counts).""" return event.member is not None and event.member.bot is False async def _poll_timer(self): """Handles poll duration.""" await asyncio.sleep(self.timeout) async def _finish_poll(self): """Removes multi-votes and calls the Page on_next function when finished.""" cheaters = await self._get_cheaters() for voters in self.data.values(): voters -= cheaters await self.output.clear_reactions() await self.page.on_next_event(self) async def _get_cheaters(self) -> Set[int]: """Returns a set of user ID's that appear in more than one state_field value.""" seen = set() repeated = set() for voters in self.data.values(): for voter in voters: repeated.add(voter) if voter in seen else seen.add(voter) return repeated async def _set_data(self): """Internally sets data field keys and values based on the current Page button properties.""" self._validate_buttons() self.set_data({}) for button in self.page.buttons_list: self.data.update({button: set()}) def _validate_buttons(self): """Checks that Poll objects always have more than two buttons.""" if len(self.page.buttons_list) < 2: raise ButtonsError( f'A Poll primary page must have at least two buttons. Expected at least 2, found {len(self.page.buttons_list)}.' ) if len(self.page.buttons_list) > 5: warn('Adding more than 5 buttons to a page at once may result in discord.py throttling the bot client.') @staticmethod def _validate_pages(pages: List[Any]): """Checks that the Menu contains at least one Page.""" if len(pages) != 2: raise PagesError(f'A Poll can only have two pages. Expected 2, found {len(pages)}.') def _validate_callbacks(self): if self.page.on_cancel_event or self.page.on_fail_event or self.page.on_timeout_event: raise EventError('A Poll can not capture a `cancel`, `fail`, or `timeout` event.') @staticmethod async def get_voters(users: Set[User]) -> Set[User]: """Returns a set of user ID's.""" return {user.id for user in users}
Python
UTF-8
321
3.28125
3
[ "MIT" ]
permissive
from abc import ABCMeta, abstractmethod class AbstractMemoryInstruction: __metaclass__ = ABCMeta def __init__(self, value): self._value = value @abstractmethod def generate(self): pass def __str__(self): return '{} {}'.format(self.__class__.__name__.upper(), self._value)
Markdown
UTF-8
2,334
2.9375
3
[ "MIT" ]
permissive
![header-image](https://i.ibb.co/6Pdkwm1/twitter-nuke-01-min.png) # Twitter Nuke Quickly and efficiently delete your entire tweet history with the help of your Twitter archive without worrying about the puny and pointless 3200 tweet limit imposed by Twitter. ### About The script uses multithreading to speed up the deletion process by simultaneously running multiple instances of the Twitter API. By utilising this modification the speed can be improved upto **~50-60 times** the single threaded performance (~1 tweet per sec). ### Features - Set the number of likes and retweets as threshold above which the tweets will not be deleted. - Set the batch size for threads - Your deleted tweets and skipped tweets will be outputted in corresponding files. ### Usage - Apply for Twitter Developer program and generate your API keys and tokens. - Download your Twitter data by following [these steps](https://help.twitter.com/en/managing-your-account/how-to-download-your-twitter-archive). - Download the latest release of the script as a ZIP file and decompress it to a folder. - Navigate to the folder you just unpacked your archive to by typing the following command in your terminal: `cd PATH/TO/YOUR/FOLDER` - Install necessary Python packages by running `pip3 -r requirements.txt` in terminal. - Edit the script with your Twitter API tokens and your preferences. - Run it in your terminal using `python3 deleter-script.py` (**Note:** Post September 2020, due to the high-profile Twitter attack of July 2020, the Twitter data might take anywhere from 24 hours to 4 days to be generated. Keep this in mind.) ### Caution This script will delete **all** of your tweets and the action cannot be reversed. The script **DOES NOT** ask for your confirmation before executing the delete command. Run this script only if you are absolutely sure about it. The creator is not responsible for any loss in data and all the liabilities are held by the person running this script. ### Donate Donate to the creator here -> [Buy Me a Coffee](https://buymeacoffee.com/mayurbhoi) ### Other Credits Photo by [Brett Jordan](https://unsplash.com/@brett_jordan?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/twitter?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText).
Java
UTF-8
8,744
2.15625
2
[]
no_license
package dw.dw.dw.web.rest; import dw.dw.dw.Demografia2App; import dw.dw.dw.domain.SubSisGrupo; import dw.dw.dw.repository.SubSisGrupoRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Integration tests for the {@link SubSisGrupoResource} REST controller. */ @SpringBootTest(classes = Demografia2App.class) @AutoConfigureMockMvc @WithMockUser public class SubSisGrupoResourceIT { private static final String DEFAULT_GID_DESIGNA = "AAAAAAAAAA"; private static final String UPDATED_GID_DESIGNA = "BBBBBBBBBB"; private static final String DEFAULT_GID_GRUPO = "AAAAAAAAAA"; private static final String UPDATED_GID_GRUPO = "BBBBBBBBBB"; @Autowired private SubSisGrupoRepository subSisGrupoRepository; @Autowired private EntityManager em; @Autowired private MockMvc restSubSisGrupoMockMvc; private SubSisGrupo subSisGrupo; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static SubSisGrupo createEntity(EntityManager em) { SubSisGrupo subSisGrupo = new SubSisGrupo() .gidDesigna(DEFAULT_GID_DESIGNA) .gidGrupo(DEFAULT_GID_GRUPO); return subSisGrupo; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static SubSisGrupo createUpdatedEntity(EntityManager em) { SubSisGrupo subSisGrupo = new SubSisGrupo() .gidDesigna(UPDATED_GID_DESIGNA) .gidGrupo(UPDATED_GID_GRUPO); return subSisGrupo; } @BeforeEach public void initTest() { subSisGrupo = createEntity(em); } @Test @Transactional public void createSubSisGrupo() throws Exception { int databaseSizeBeforeCreate = subSisGrupoRepository.findAll().size(); // Create the SubSisGrupo restSubSisGrupoMockMvc.perform(post("/api/sub-sis-grupos") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(subSisGrupo))) .andExpect(status().isCreated()); // Validate the SubSisGrupo in the database List<SubSisGrupo> subSisGrupoList = subSisGrupoRepository.findAll(); assertThat(subSisGrupoList).hasSize(databaseSizeBeforeCreate + 1); SubSisGrupo testSubSisGrupo = subSisGrupoList.get(subSisGrupoList.size() - 1); assertThat(testSubSisGrupo.getGidDesigna()).isEqualTo(DEFAULT_GID_DESIGNA); assertThat(testSubSisGrupo.getGidGrupo()).isEqualTo(DEFAULT_GID_GRUPO); } @Test @Transactional public void createSubSisGrupoWithExistingId() throws Exception { int databaseSizeBeforeCreate = subSisGrupoRepository.findAll().size(); // Create the SubSisGrupo with an existing ID subSisGrupo.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail restSubSisGrupoMockMvc.perform(post("/api/sub-sis-grupos") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(subSisGrupo))) .andExpect(status().isBadRequest()); // Validate the SubSisGrupo in the database List<SubSisGrupo> subSisGrupoList = subSisGrupoRepository.findAll(); assertThat(subSisGrupoList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllSubSisGrupos() throws Exception { // Initialize the database subSisGrupoRepository.saveAndFlush(subSisGrupo); // Get all the subSisGrupoList restSubSisGrupoMockMvc.perform(get("/api/sub-sis-grupos?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(subSisGrupo.getId().intValue()))) .andExpect(jsonPath("$.[*].gidDesigna").value(hasItem(DEFAULT_GID_DESIGNA))) .andExpect(jsonPath("$.[*].gidGrupo").value(hasItem(DEFAULT_GID_GRUPO))); } @Test @Transactional public void getSubSisGrupo() throws Exception { // Initialize the database subSisGrupoRepository.saveAndFlush(subSisGrupo); // Get the subSisGrupo restSubSisGrupoMockMvc.perform(get("/api/sub-sis-grupos/{id}", subSisGrupo.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(subSisGrupo.getId().intValue())) .andExpect(jsonPath("$.gidDesigna").value(DEFAULT_GID_DESIGNA)) .andExpect(jsonPath("$.gidGrupo").value(DEFAULT_GID_GRUPO)); } @Test @Transactional public void getNonExistingSubSisGrupo() throws Exception { // Get the subSisGrupo restSubSisGrupoMockMvc.perform(get("/api/sub-sis-grupos/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateSubSisGrupo() throws Exception { // Initialize the database subSisGrupoRepository.saveAndFlush(subSisGrupo); int databaseSizeBeforeUpdate = subSisGrupoRepository.findAll().size(); // Update the subSisGrupo SubSisGrupo updatedSubSisGrupo = subSisGrupoRepository.findById(subSisGrupo.getId()).get(); // Disconnect from session so that the updates on updatedSubSisGrupo are not directly saved in db em.detach(updatedSubSisGrupo); updatedSubSisGrupo .gidDesigna(UPDATED_GID_DESIGNA) .gidGrupo(UPDATED_GID_GRUPO); restSubSisGrupoMockMvc.perform(put("/api/sub-sis-grupos") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(updatedSubSisGrupo))) .andExpect(status().isOk()); // Validate the SubSisGrupo in the database List<SubSisGrupo> subSisGrupoList = subSisGrupoRepository.findAll(); assertThat(subSisGrupoList).hasSize(databaseSizeBeforeUpdate); SubSisGrupo testSubSisGrupo = subSisGrupoList.get(subSisGrupoList.size() - 1); assertThat(testSubSisGrupo.getGidDesigna()).isEqualTo(UPDATED_GID_DESIGNA); assertThat(testSubSisGrupo.getGidGrupo()).isEqualTo(UPDATED_GID_GRUPO); } @Test @Transactional public void updateNonExistingSubSisGrupo() throws Exception { int databaseSizeBeforeUpdate = subSisGrupoRepository.findAll().size(); // If the entity doesn't have an ID, it will throw BadRequestAlertException restSubSisGrupoMockMvc.perform(put("/api/sub-sis-grupos") .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(subSisGrupo))) .andExpect(status().isBadRequest()); // Validate the SubSisGrupo in the database List<SubSisGrupo> subSisGrupoList = subSisGrupoRepository.findAll(); assertThat(subSisGrupoList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteSubSisGrupo() throws Exception { // Initialize the database subSisGrupoRepository.saveAndFlush(subSisGrupo); int databaseSizeBeforeDelete = subSisGrupoRepository.findAll().size(); // Delete the subSisGrupo restSubSisGrupoMockMvc.perform(delete("/api/sub-sis-grupos/{id}", subSisGrupo.getId()) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<SubSisGrupo> subSisGrupoList = subSisGrupoRepository.findAll(); assertThat(subSisGrupoList).hasSize(databaseSizeBeforeDelete - 1); } }
Java
UTF-8
1,101
2.640625
3
[]
no_license
package com.sharing.entity; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.MappedSuperclass; @MappedSuperclass public class BaseEntity { private String dateFormat; public String getDateFormat(Date originalDate){ SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); String newDate=""; if(originalDate==null){ newDate= ""; } else{ try { newDate= formatter.format(originalDate); } catch (Exception e) { e.printStackTrace(); } } return newDate; } public String getBigDateFormat(Date originalDate){ SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm"); String newDate=""; if(originalDate==null){ newDate= "Pas de réception"; } else{ try { newDate= formatter.format(originalDate); } catch (Exception e) { e.printStackTrace(); } } return newDate; } public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } }
C
UTF-8
2,559
3.28125
3
[ "MIT" ]
permissive
/* ** EPITECH PROJECT, 2017 ** my_sokoban ** File description: ** move_up */ #include "my.h" #include "header_SOKOBAN.h" #include <stdlib.h> void move_up(char **map) { position_t *position = search_player(map); char letter; switch (map[position->y - 1][position->x]) { case ' ': map[position->y - 1][position->x] = 'P'; map[position->y][position->x] = ' '; break; case 'O': map[position->y - 1][position->x] = 'P'; map[position->y][position->x] = ' '; break; case 'X': letter = map[position->y - 2][position->x]; if (letter == ' ' || letter == 'O') { map[position->y - 2][position->x] = 'X'; map[position->y - 1][position->x] = 'P'; map[position->y][position->x] = ' '; } } free (position); } void move_down(char **map) { position_t *position = search_player(map); char letter; switch (map[position->y + 1][position->x]) { case ' ': map[position->y + 1][position->x] = 'P'; map[position->y][position->x] = ' '; break; case 'O': map[position->y + 1][position->x] = 'P'; map[position->y][position->x] = ' '; break; case 'X': letter = map[position->y + 2][position->x]; if (letter == ' ' || letter == 'O') { map[position->y + 2][position->x] = 'X'; map[position->y + 1][position->x] = 'P'; map[position->y][position->x] = ' '; } break; } free (position); } void move_right(char **map) { position_t *position = search_player(map); char letter; switch (map[position->y][position->x + 1]) { case ' ': map[position->y][position->x + 1] = 'P'; map[position->y][position->x] = ' '; break; case 'O': map[position->y][position->x + 1] = 'P'; map[position->y][position->x] = ' '; break; case 'X': letter = map[position->y][position->x + 2]; if (letter == ' ' || letter == 'O') { map[position->y][position->x + 2] = 'X'; map[position->y][position->x + 1] = 'P'; map[position->y][position->x] = ' '; } break; } free (position); } void move_left(char **map) { position_t *position = search_player(map); char letter; switch (map[position->y][position->x - 1]) { case ' ': map[position->y][position->x - 1] = 'P'; map[position->y][position->x] = ' '; break; case 'O': map[position->y][position->x - 1] = 'P'; map[position->y][position->x] = ' '; break; case 'X': letter = map[position->y][position->x - 2]; if (letter == ' ' || letter == 'O') { map[position->y][position->x - 2] = 'X'; map[position->y][position->x - 1] = 'P'; map[position->y][position->x] = ' '; } break; } free (position); }
Shell
UTF-8
3,470
2.828125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash ## 创建必要的文件夹 echo -e "\033[31m 创建jars和jmods目录...... \033[0m" mkdir jars mkdir jmods ## 设置jdk9路径 echo -e "\033[31m 设置jdk路9路径...... \033[0m" export JDK9_HOME=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home ## 编译java9-sample模块及子模块 echo -e "\033[31m 编译java9-sample模块及子模块...... \033[0m" cd ../. && mvn clean install && cd jlink-exe ## 生成sercie目录下子模块 echo -e "\033[31m 生成sercie目录下子模块...... \033[0m" rm -rf jmods/org.eugene.service.prime* jar --create --verbose --file jars/org.eugene.service.prime.jar -C ../service/service-prime/target/classes . $JDK9_HOME/bin/jmod create --class-path jars/org.eugene.service.prime.jar jmods/org.eugene.service.prime.jmod jar --create --verbose --file jars/org.eugene.service.prime.generic.jar -C ../service/service-prime-generic/target/classes . $JDK9_HOME/bin/jmod create --class-path jars/org.eugene.service.prime.generic.jar jmods/org.eugene.service.prime.generic.jmod jar --create --verbose --file jars/org.eugene.service.prime.faster.jar -C ../service/service-prime-faster/target/classes . $JDK9_HOME/bin/jmod create --class-path jars/org.eugene.service.prime.faster.jar jmods/org.eugene.service.prime.faster.jmod jar --create --verbose --file jars/org.eugene.service.prime.probable.jar -C ../service/service-prime-probable/target/classes . $JDK9_HOME/bin/jmod create --class-path jars/org.eugene.service.prime.probable.jar jmods/org.eugene.service.prime.probable.jmod jar --create --verbose --file jars/org.eugene.service.prime.client.jar -C ../service/service-prime-client/target/classes . $JDK9_HOME/bin/jmod create --class-path jars/org.eugene.service.prime.client.jar jmods/org.eugene.service.prime.client.jmod ## 使用jlink生成可执行文件 rm -rf exe echo -e "\033[31m 使用jlink生成可执行文件...... \033[0m" $JDK9_HOME/bin/jlink --module-path jmods:$JDK9_HOME/jmods --add-modules org.eugene.service.prime.client,org.eugene.service.prime.generic,org.eugene.service.prime.faster --launcher runprimecheck=org.eugene.service.prime.client/org.eugene.service.prime.client.Main --output exe ## 验证可执行文件 exe/bin/java --list-modules exe/bin/java --module org.eugene.service.prime.client/org.eugene.service.prime.client.Main exe/bin/runprimecheck ## 使用suggest-providers显示服务提供者 echo -e "\033[31m 使用suggest-providers显示服务提供者...... \033[0m" $JDK9_HOME/bin/jlink --module-path jmods:$JDK9_HOME/jmods --add-modules org.eugene.service.prime.client --suggest-providers org.eugene.service.prime.PrimeChecker ## 使用bind-services参数构建jlink rm -rf exe-bind-service echo -e "\033[31m 使用bind-services参数构建jlink...... \033[0m" $JDK9_HOME/bin/jlink --module-path jmods:$JDK9_HOME/jmods --add-modules org.eugene.service.prime.client --launcher runprimecheck=org.eugene.service.prime.client/org.eugene.service.prime.client.Main --bind-services --output exe-bind-service exe-bind-service/bin/runprimecheck ## 使用jlink plugins构建 rm -rf exe-with-plugin echo -e "\033[31m 使用jlink plugins构建...... \033[0m" $JDK9_HOME/bin/jlink --module-path jmods:$JDK9_HOME/jmods --compress 2 --strip-debug --add-modules org.eugene.service.prime.client --launcher runprimecheck=org.eugene.service.prime.client/org.eugene.service.prime.client.Main --bind-services --output exe-with-plugin exe-with-plugin/bin/runprimecheck
Java
UTF-8
2,732
2.125
2
[]
no_license
package com.example.besocial.utils; public interface ConstantValues { //database root childs String EVENTS = "Events"; String USERS = "users"; String EVENTS_WITH_ATTENDINGS = "EventsWithAttending"; String USERS_ATTENDING_TO_EVENTS = "UsersAttendingToEvents"; String BENEFITS = "Benefits"; String USERS_LIST = "UsersList"; String USER_PHOTOS = "UserPhotos"; String POSTS = "Posts"; String CHAT_CONVERSATIONS = "ChatConversations"; String CHAT_MESSAGES = "ChatMessages"; //categories String CATEGORY = "eventCategory"; String GENERAL = "General"; String HELP_ME = "Help Me!"; //events String EVENT_ID = "eventId"; String EVENT_TITLE = "title"; String EVENT_HOST_UID = "eventCreatorUid"; String BEGIN_DATE = "beginDate"; String BEGIN_TIME = "beginTime"; String FINISH_DATE = "finishDate"; String FINISH_TIME = "finishTime"; String IS_CHECKED_IN = "isCheckedIn"; //users String PROFILE_PHOTO = "profileImage"; String USER_ID = "userId"; String USER_FIRST_NAME = "userFirstName"; String USER_LAST_NAME = "userLastName"; //user levels String USER_LEVEL_1 = "Shy Socializer"; String USER_LEVEL_2 = "Out Of The Shell Socializer"; String USER_LEVEL_3 = "Academic Socializer"; String USER_LEVEL_4 = "Socialized Ninja Turtle"; String USER_LEVEL_5 = "Socialosaurus"; long USER_LEVEL_2_POINTS = 200 ; long USER_LEVEL_3_POINTS = 800; long USER_LEVEL_4_POINTS = 2600; long USER_LEVEL_5_POINTS = 6000; //times in milliseconds int SECOND = 1000; int MINUTE = 60 * 1000; int HOUR = 3600 * 1000; String IS_HELP_EVENT = "isHelpEvent"; float GEOFENCE_RADIUS = 70; String IS_COMPANY_EVENT = "companyManagmentEvent"; String LOGGED_USER_ID = "loggedUserId"; //chats String CHAT_ID = "chatId"; String LIKES = "Likes"; String IS_FINISHED = "finished"; String APPROVED = "approved"; //notifications String NOTIFICATIONS = "Notifications"; //tpyes of notifications String EVENT = "Event"; String NEW_CONVERSTION = "New Conversation"; String NEW_RANK = "New rank"; String RELATED_NAME = "relatedName"; // likes also a type // notification bodies String EVENT_NOTIFICATION_BODY1 = "You have arrived to: \""; String EVENT_NOTIFICATION_BODY2 = "\".\n Have a good time!.\nReceived points: "; String NEW_CONVERSATION_NOTIFICATION_BODY1 = "Congratulation on connecting with "; String NEW_CONVERSATION_NOTIFICATION_BODY2 = "\nReceived points: "; String LIKE_NOTIFICATION_BODY = "People have liked your post"; String NEW_RANK_BODY = "Congratulations on reaching the new level:\n"; }
Shell
UTF-8
249
3.03125
3
[]
no_license
#!/bin/bash read input name=${input%% *} output=$(sqlite3 ~/.menu/main.sqlite "UPDATE commands SET weight = weight+1 WHERE name='$name';SELECT cmd FROM commands WHERE name='$name';") if [[ $input == $name ]]; then echo $output else echo $input fi
Java
UTF-8
557
1.828125
2
[]
no_license
package parttime.pt.com.basic.login.model; import parttime.pt.com.model.CommonVO; public class LoginVO extends CommonVO{ private static final long serialVersionUID = 5627981987701506596L; private String loginCode = ""; private String loginMsg = ""; public String getLoginCode() { return loginCode; } public void setLoginCode(String loginCode) { this.loginCode = loginCode; } public String getLoginMsg() { return loginMsg; } public void setLoginMsg(String loginMsg) { this.loginMsg = loginMsg; } }
Markdown
UTF-8
5,908
3.046875
3
[]
no_license
# Project: DataPipeline with Airflow A music streaming company, Sparkify, has decided that it is time to introduce more automation and monitoring to their data warehouse ETL pipelines and come to the conclusion that the best tool to achieve this is Apache Airflow. They have decided to bring you into the project and expect you to create high grade data pipelines that are dynamic and built from reusable tasks, can be monitored, and allow easy backfills. They have also noted that the data quality plays a big part when analyses are executed on top the data warehouse and want to run tests against their datasets after the ETL steps have been executed to catch any discrepancies in the datasets. ### Project Description The source data resides in S3 and needs to be processed in Sparkify's data warehouse in Amazon Redshift. The source datasets consist of JSON logs that tell about user activity in the application and JSON metadata about the songs the users listen to. ### Airflow UI Connection Here, we'll use Airflow's UI to configure your AWS credentials and connection to Redshift. 1. Click on the Admin tab and select Connections. ![image](https://video.udacity-data.com/topher/2019/February/5c5aaca1_admin-connections/admin-connections.png) 2. On the create connection page, enter the following values: - **Conn Id**: Enter ```aws_credentials```. - **Conn Type**: Enter ```Amazon Web Services```. - **Login**: Enter your **Access key ID** from the IAM User credentials you downloaded earlier. - **Password**: Enter your **Secret access key** from the IAM User credentials you downloaded earlier. Once you've entered these values, select **Save and Add Another**. ![image](https://video.udacity-data.com/topher/2019/February/5c5aaefe_connection-aws-credentials/connection-aws-credentials.png) 3. On the next create connection page, enter the following values: - **Conn Id**: Enter ```redshift```. - **Conn Type**: Enter ```Postgres```. - **Host**: Enter the endpoint of your Redshift cluster, excluding the port at the end. You can find this by selecting your cluster in the **Clusters** page of the Amazon Redshift console. See where this is located in the screenshot below. IMPORTANT: Make sure to NOT include the port at the end of the Redshift endpoint string. - **Schema**: Enter ```dev```. This is the Redshift database you want to connect to. - **Login**: Enter ```awsuser```. - **Password**: Enter the password you created when launching your Redshift cluster. - **Port**: Enter ```5439```. Once you've entered these values, select Save. ![image](https://video.udacity-data.com/topher/2019/February/5c5aaf07_connection-redshift/connection-redshift.png) ### Airflow Dependencies Working DAG with correct task dependencies graph view. ![image](https://video.udacity-data.com/topher/2019/January/5c48ba31_example-dag/example-dag.png) The DAG includes four different operators that will stage the data, transform the data, and run checks on data quality: #### Stage Operator The stage operator is expected to be able to load any JSON formatted files from S3 to Amazon Redshift. The operator creates and runs a SQL COPY statement based on the parameters provided. The operator's parameters should specify where in S3 the file is loaded and what is the target table. The parameters should be used to distinguish between JSON file. Another important requirement of the stage operator is containing a templated field that allows it to load timestamped files from S3 based on the execution time and run backfills. #### Fact and Dimension Operators With dimension and fact operators, you can utilize the provided SQL helper class to run data transformations. Most of the logic is within the SQL transformations and the operator is expected to take as input a SQL statement and target database on which to run the query against. You can also define a target table that will contain the results of the transformation. Dimension loads are often done with the truncate-insert pattern where the target table is emptied before the load. Thus, you could also have a parameter that allows switching between insert modes when loading dimensions. Fact tables are usually so massive that they should only allow append type functionality. #### Data Quality Operator The final operator to create is the data quality operator, which is used to run checks on the data itself. The operator's main functionality is to receive one or more SQL based test cases along with the expected results and execute the tests. For each the test, the test result and expected result needs to be checked and if there is no match, the operator should raise an exception and the task should retry and fail eventually. For example one test could be a SQL statement that checks if certain column contains NULL values by counting all the rows that have NULL in the column. We do not want to have any NULLs so expected result would be 0 and the test would compare the SQL statement's outcome to the expected result. ### Project Files `udac_example_dag.py` - contains the tasks and dependencies of the DAG.\ `create_tables.sql` - contains the SQL queries used to create all the required tables in Redshift.\ `sql_queries.py` - contains the SQL queries used in the ETL process. ##### The following operator files should be placed in the plugins/operators directory: `stage_redshift.py` - contains StageToRedshiftOperator, Copy data from S3 buckets to redshift cluster into staging tables.\ `load_dimension.py` - contains LoadDimensionOperator, loads data into dimensional tables from staging events and song data table(s).\ `load_fact.py` - contains LoadFactOperator, loads data as fact table from both staging events and songs table(s).\ `data_quality.py` - contains DataQualityOperator, performs data quality checks on dimension tables records. #### run `udac_example_dag.py` to initiate the project
Python
UTF-8
2,374
3.171875
3
[]
no_license
import numpy as np import random as rnd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # alpha = 0.1*np.pi theta0 = rnd.uniform(0,np.pi) phi0 = rnd.uniform(0,2*np.pi) # x0 = np.sin(theta0)*np.cos(phi0) # y0 = np.sin(theta0)*np.sin(phi0) # z0 = np.cos(theta0) rho = 0.5 r = 1 theta_back = np.pi-theta0 phi_back = np.pi+phi0 x_back = np.sin(theta_back)*np.cos(phi_back) y_back = np.sin(theta_back)*np.sin(phi_back) z_back = np.cos(theta_back) #In local coordinate system with "going back" vector as z axis: #Generate new bead center alpha = np.arccos((r**2 + r**2 - (2*rho) ** 2) / (2*r*r)) theta = rnd.uniform(alpha, np.pi) phi = rnd.uniform(0, 2*np.pi) #Translate bead center position into global coordinate system. # First: define the local coordinate system in terms of the global z_hat = [np.sin(theta_back) * np.cos(phi_back), np.sin(theta_back) * np.sin(phi_back),np.cos(theta_back)] # vector between the most recent two beads y_hat = [-np.sin(phi_back), np.cos(phi_back), 0] # changed x->y # x_hat = [x_hat[i]* 1 / np.sin(theta_back) for i in range(3)] # Orthogonal to z_hat x_hat = [-np.cos(theta_back) * np.cos(phi_back),-np.cos(theta_back) * np.sin(phi_back), np.sin(theta_back)] # Orthogonal to z_hat, x_hat #changed y->x # y_hat = [y_hat[i]* 1 / np.sin(theta_back) for i in range(3)] # Orthogonal to z_hat theta_list = [] phi_list=[] for i in range(5000): theta_list.append(rnd.uniform(alpha,np.pi)) phi_list.append(rnd.uniform(0,2*np.pi)) # print(theta_list,phi_list) #print(sum([y_hat[i] * y_hat[i] for i in range(3)])) #Second: project the bead center position onto the global axes and translate it to origo x=[] y=[] z=[] for i in range(len(theta_list)): x.append(r*(np.cos(theta_list[i])*z_hat[0]+np.sin(theta_list[i])*np.cos(phi_list[i])*y_hat[0]+np.sin(theta_list[i])*np.sin(phi_list[i])*x_hat[0])) y.append(r*(np.cos(theta_list[i])*z_hat[1]+np.sin(theta_list[i])*np.cos(phi_list[i])*y_hat[1]+np.sin(theta_list[i])*np.sin(phi_list[i])*x_hat[1])) z.append(r*(np.cos(theta_list[i])*z_hat[2]+np.sin(theta_list[i])*np.cos(phi_list[i])*y_hat[2]+np.sin(theta_list[i])*np.sin(phi_list[i])*x_hat[2])) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot(x,y,z,'.') ax.plot(x_back,y_back,z_back,'*') ax.plot(0,0,0,'*') # origo ax.set_xlabel('$X$') ax.set_ylabel('$Y$') ax.set_zlabel('$Z$') plt.show()
Go
UTF-8
1,768
2.953125
3
[ "Apache-2.0" ]
permissive
package bitbucketserver import ( "net/url" "strings" bitbucketv1 "github.com/gfleury/go-bitbucket-v1" "github.com/pkg/errors" ) func (b *BitbucketServer) convertRepository(bitbucketRepository *bitbucketv1.Repository, defaultBranch bitbucketv1.Branch) (*repository, error) { var cloneURL string if b.sshAuth { cloneURL = findLinkType(bitbucketRepository.Links.Clone, cloneSSHType) if cloneURL == "" { return nil, errors.Errorf("unable to find clone url for repository %s using clone type %s", bitbucketRepository.Name, cloneSSHType) } } else { httpURL := findLinkType(bitbucketRepository.Links.Clone, cloneHTTPType) if httpURL == "" { return nil, errors.Errorf("unable to find clone url for repository %s using clone type %s", bitbucketRepository.Name, cloneHTTPType) } parsedURL, err := url.Parse(httpURL) if err != nil { return nil, err } parsedURL.User = url.UserPassword(b.username, b.token) cloneURL = parsedURL.String() } repo := repository{ name: bitbucketRepository.Slug, project: bitbucketRepository.Project.Key, defaultBranch: defaultBranch.DisplayID, cloneURL: cloneURL, } return &repo, nil } func findLinkType(links []bitbucketv1.CloneLink, cloneType string) string { for _, clone := range links { if strings.EqualFold(clone.Name, cloneType) { return clone.Href } } return "" } // repository contains information about a bitbucket repository type repository struct { name string project string defaultBranch string cloneURL string } func (r repository) CloneURL() string { return r.cloneURL } func (r repository) DefaultBranch() string { return r.defaultBranch } func (r repository) FullName() string { return r.project + "/" + r.name }
Python
UTF-8
651
2.578125
3
[ "MIT" ]
permissive
import unittest from unittest.mock import patch from cdf_548B import CodeforcesTask548BSolution class TestCDF548B(unittest.TestCase): def test_548B_acceptance_1(self): mock_input = ['5 4 5', '0 1 1 0', '1 0 0 1', '0 1 1 0', '1 0 0 1', '0 0 0 0', '1 1', '1 4', '1 1', '4 2', '4 3'] expected = '3\n4\n3\n3\n4' with patch('builtins.input', side_effect=mock_input): Solution = CodeforcesTask548BSolution() Solution.read_input() Solution.process_task() actual = Solution.get_result() self.assertEqual(expected, actual) if __name__ == "__main__": unittest.main()
Python
UTF-8
1,477
2.6875
3
[]
no_license
import pyaudio import wave import datetime import time import math import os import config #length of chunk in seconds chunk_length = 5 def record_chunk(RECORD_SECONDS = 5, WAVE_OUTPUT_FILENAME = "file.wav"): FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 16000 CHUNK = 1024 audio = pyaudio.PyAudio() stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data) stream.stop_stream() stream.close() audio.terminate() waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') waveFile.setnchannels(CHANNELS) waveFile.setsampwidth(audio.get_sample_size(FORMAT)) waveFile.setframerate(RATE) waveFile.writeframes(b''.join(frames)) waveFile.close() def record_conversation(convo_length = 60*15): #print("STARTED RECORDING") config.record_const=0 number_of_files = math.ceil(convo_length/chunk_length) f=open('file_name.txt','r') file_name_base=f.read() f.close() list_of_filenames = [file_name_base + str(index+10) + ".wav" for index in range(int(number_of_files))] #print(list_of_filenames) for filename in list_of_filenames: if config.record_const==0: record_chunk(RECORD_SECONDS = chunk_length, WAVE_OUTPUT_FILENAME = filename) else: record_chunk(RECORD_SECONDS = 3, WAVE_OUTPUT_FILENAME = file_name_base+"_x.wav") print('record stopped') return print("SR_Loaded_and_Done")
C++
UTF-8
1,206
3.1875
3
[]
no_license
#include<iostream> #include<string> #include<vector> using std::vector; using std::cin; using std::cout; using std::endl; using std::string; void main(){ int n,m; cin >> n; vector<int> ivec(n); int num; for (int i = 0; i < n; i++){ cin >> num; ivec[i] = num; } cin >> m; vector<string> exp(m); string str; int operation; for (int i = 0; i < m; i++){ cin >> str; if (str == "add"){ cin >> operation; for (int j = 0; j < n; j++) ivec[j] += operation; } else if (str == "sub"){ cin >> operation; for (int j = 0; j < n; j++) ivec[j] -= operation; } else if (str == "mul"){ cin >> operation; for (int j = 0; j < n; j++) ivec[j] *= operation; } else if (str == "pow"){ cin >> operation; for (int j = 0; j < n; j++) ivec[j] = (int)pow(ivec[j], operation); } else if (str == "sqa"){ int sum = 0; for (int j = 0; j < n; j++){ int temp = ivec[j] * ivec[j]; sum += temp; } cout << sum << endl; } else if (str == "print"){ for (int i = 0; i < n; i++) if (i != n - 1) cout << ivec[i] << " "; else cout << ivec[i]<<" "; } } }
Java
UTF-8
814
2.71875
3
[]
no_license
public class Candidato extends Eleitor implements Candidatura { int qtdVotos = 0; int numeroCandidatura; String cargo; public Candidato(String nome, String cpf, String datanasc, String titulo, int numeroCandidatura, String cargo) { super(nome, cpf, datanasc, titulo); this.numeroCandidatura = numeroCandidatura; this.cargo = cargo; } @Override public int numeroCandidatura() { return numeroCandidatura; } public void adicionarVoto() { qtdVotos++; } public int getVotos() { return qtdVotos; } public void setCandidatura(int n) { numeroCandidatura = n; } public void setCargo(String cargo) { this.cargo = cargo; } public String getCargo() { return this.cargo; } }
PHP
UTF-8
1,794
2.921875
3
[ "MIT" ]
permissive
<?php /** * Swiss Payment Slip PDF * * @license http://www.opensource.org/licenses/mit-license.php MIT License * @copyright 2012-2015 Some nice Swiss guys * @author Marc Würth <ravage@bluewin.ch> * @author Manuel Reinhard <manu@sprain.ch> * @author Peter Siska <pesche@gridonic.ch> * @link https://github.com/ravage84/SwissPaymentSlipPdf/ */ namespace SwissPaymentSlip\SwissPaymentSlipPdf\Examples; use SwissPaymentSlip\SwissPaymentSlipPdf\PaymentSlipPdf; /** * An example implementation of PaymentSlipPdf */ class ExamplePaymentSlipPdf extends PaymentSlipPdf { protected function displayImage($background) { echo sprintf('Display the background image "%s"<br>', $background); } protected function setFont($fontFamily, $fontSize, $fontColor) { echo sprintf('Set the font "%s" "%s" "%s"<br>', $fontFamily, $fontSize, $fontColor); } protected function setBackground($background) { echo sprintf('Set the background "%s"<br>', $background); } protected function setPosition($posX, $posY) { echo sprintf('Set the position to "%s"/"%s"<br>', $posX, $posY); } protected function createCell($width, $height, $line, $textAlign, $fill) { echo sprintf( 'Create a cell; width: "%s"; height: "%s"; line: "%s"; textAlign: "%s"; fill: "%s"<br>', $width, $height, $line, $textAlign, $fill ); } /** * Normally it is not necessary to overwrite this method * * {@inheritDoc} */ protected function writePaymentSlipLines($elementName, $element) { echo sprintf('Write the element "%s"<br>', $elementName); parent::writePaymentSlipLines($elementName, $element); echo '<br>'; return $this; } }
Markdown
UTF-8
803
2.734375
3
[]
no_license
Exercícios Exercícios Teste o problema de deadlock quando é utilizado o locking pessimista. Adicione a seguinte classe no pacote testes. public class TestaDeadLock { public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("K21_topicos_avancados"); EntityManager manager1 = factory.createEntityManager(); EntityManager manager2 = factory.createEntityManager(); manager1.getTransaction().begin(); manager2.getTransaction().begin(); manager1.find(Produto.class, 100L, LockModeType.PESSIMISTIC_WRITE); manager2.find(Produto.class, 100L, LockModeType.PESSIMISTIC_WRITE); manager1.getTransaction().commit(); manager2.getTransaction().commit(); manager1.close(); manager2.close(); factory.close(); } } Execute e aguarde até ocorrer uma exception.
C
UTF-8
2,457
3.484375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> /* Definition of macros and constants. */ #define MAX_CHARS_LINE 2 /* Definition of structures. */ typedef struct { int entero; } numero; /* Declaration of functions (prototypes). */ int getTotNumeros(numero *comp,FILE *f); void readNumbers(numero *comp, FILE *f); void showNumbers(numero *comp, FILE *f); void *perfecto(void *param); int totNumeros = 0; int main(int argc, char* argv[]) { FILE *inFile; char *fileName; numero *numeros; int i; if(argc != 2){ printf("error arguments\n"); printf("./a.out <nombre archivo> \n"); exit(1); } fileName = argv[1]; inFile = fopen(fileName, "r"); if(inFile == NULL){ printf("No se puede abrir el fichero: %s\n", fileName); exit(EXIT_FAILURE); } /*Invo functions*/ numeros = (numero *)malloc(sizeof(numero) * totNumeros); totNumeros = getTotNumeros(numeros, inFile); showNumbers(numeros, inFile); pthread_t id[totNumeros]; numero str_n[totNumeros]; //invocando la función perfecto for(i = 0; i < totNumeros; i++){ str_n[i].entero = numeros[i].entero; pthread_create(&id[i], NULL, perfecto, (void *)&str_n[i]); } /*Esperando los hilos for(i = 0; i < totNumeros; i++){ pthread_join(id[i], (void**)&results[i]); }*/ /*Close*/ fclose(inFile); return 0; } /* Implementation of functions. */ int getTotNumeros(numero *comp, FILE *f) { int num = 0; char buffer[100]; char *pch; //Lectura de datos del archivo csv if (fgets(buffer , 100 , f) != NULL ){ puts (buffer); } if ( fgets (buffer , 100 , f) != NULL ){ pch = strtok(buffer, ";"); while(pch != NULL){ //Leyendo datos y contando comp->entero = atoi(pch); pch=strtok(NULL, ";"); num++; comp++; } } return num; } void showNumbers(numero *comp, FILE *f){ int i = 0; printf("|%-12s|\n", "Números"); for (i = 0; i < totNumeros; i++) { printf("|%-12d|\n", comp->entero); comp++; } } void *perfecto(void *param){ numero str_n = *((numero *) param); int i; int sum = 0; int mod = 0; for(i = 0; i < str_n.entero; i++) { mod = str_n.entero%i; if(mod == 0) { sum+=i; } } /*sum se compara sum con num */ if(sum==str_n.entero){ printf("El numero %d es perfecto.\n", str_n.entero); } else{ printf("El numero %d NO es perfecto.\n", str_n.entero); } return 0; }
Markdown
UTF-8
7,077
3.40625
3
[]
no_license
# soal-shift-sisop-modul-4-A12-2021 Praktikum Sisop Modul 4 Semester genap 2021 <hr> ## Soal nomor 1 ### Penjelasan Soal Untuk soal nomor 1, kita perlu membuat metode encoding dimana jika terdapat file atau folder di dalam folder ter-encode, maka nama file tersebut harus ter-encode dengan menggunakan atbash cipher, yaitu alfabet dipetakan ke kebalikannya (a menjadi z). ### Soal 1a Untuk soal 1a, jika sebuah direktori dibuat dengan awalan “AtoZ_”, maka direktori tersebut akan menjadi direktori ter-encode. ### Kendala ```c int check(char string1[], char string2[]){ int j=0; for(int i=0; i<strlen(string1); i++){ if(string1[i]==string2[j]) j++; else j=0; if(j==strlen(string2)) return 1; } return 0; } static int xmp_mkdir(const char *path, mode_t mode) { char fpath[1000]; if(strcmp(path,"/") == 0) { path=dirpath; sprintf(fpath,"%s",path); } else sprintf(fpath, "%s%s",dirpath,path); int res; res = mkdir(fpath, mode); if (res == -1) return -errno; char newname[2000]; char filename[1000]; sprintf(filename,"%s",path); char prefix[10]="/AtoZ_"; if(check(fpath,prefix)==1){ char nama[1000]; sprintf(nama,"%s",filename); for(int i=0;nama[i]!='\0';i++){ if(nama[i]>='A'&&nama[i]<='Z') nama[i]='Z'-nama[i]+'A'; if(nama[i]>='a'&&nama[i]<='z') nama[i]='z'-nama[i]+'a'; } sprintf(newname,"%s%s",dirpath,nama); printf("%s\n",fpath); printf("%s\n",newname); rename(fpath, newname); } return 0; } ``` Dengan kode yang sudah dibuat ini, file dengan awalan "AtoZ_" akan langsung diencode padahal seharusnya file atau folder dalam folder tersebut yang seharusnya diencode. Disini, fpath dari file yang dibuat dicek jika memiliki awalah "AtoZ_" dan jika iya, maka setiap alfabet dipetakan mnejadi kebalikannya dan nama folder tersebut direname. ![image](https://user-images.githubusercontent.com/7587945/121809512-40845e00-cc87-11eb-88c1-6777e746e7c5.png) ![image](https://user-images.githubusercontent.com/7587945/121809530-4e39e380-cc87-11eb-96a9-3248e293c98a.png) ### Soal 1b Untuk soal 1b, jika sebuah direktori di-rename dengan awalan “AtoZ_”, maka direktori tersebut akan menjadi direktori ter-encode. ```c static int xmp_rename(const char *from, const char *to) { char fpath[1000]; char tpath[1000]; if(strcmp(from,"/") == 0) { from=dirpath; sprintf(fpath,"%s",from); sprintf(tpath,"%s",to); } else { sprintf(fpath, "%s%s",dirpath,from); sprintf(tpath, "%s%s",dirpath,to); } int res; res = rename(fpath, tpath); if (res == -1) return -errno; DIR *dir; struct dirent *ent; char oldname[2000], newname[2000]; char prefix[10]="/AtoZ_"; if(check(tpath,prefix)==1){ if ((dir = opendir (tpath)) != NULL) { while ((ent = readdir (dir)) != NULL) { char nama[1000]; sprintf(nama,"%s",ent->d_name); for(int i=0;nama[i]!='\0';i++){ if(nama[i]>='A'&&nama[i]<='Z') nama[i]='Z'-nama[i]+'A'; if(nama[i]>='a'&&nama[i]<='z') nama[i]='z'-nama[i]+'a'; } sprintf(oldname,"%s/%s",tpath,ent->d_name); sprintf(newname,"%s/%s",tpath,nama); rename(oldname, newname); } closedir (dir); } } return 0; } ``` Di sini jika folder direname, cek jika nama baru memiliki awalan "AtoZ_", jika iya, buka folder tersebut dan encode setiap file dan folder dan tutup folder tersebut. ![image](https://user-images.githubusercontent.com/7587945/121809716-1aab8900-cc88-11eb-80ac-bf5e1d8bc27c.png) ![image](https://user-images.githubusercontent.com/7587945/121809729-27c87800-cc88-11eb-932d-2734a538d28f.png) ![image](https://user-images.githubusercontent.com/7587945/121809740-39aa1b00-cc88-11eb-8c46-640bc1f91e96.png) <hr> ## Soal Nomor 2 <hr> ## Soal Nomor 3 <hr> ## Soal Nomor 4 Untuk soal ini kita diminta untuk membuat log system dari segala program yang telah dieksekusi yang bertujuan agar mudah untuk memonitoring kegiatan dan kejadian yang ada pada jalannya program. terdapat 2 jenis log yang bida ditulis dalam sebuah file system log yang bernama `SinSeiFS.log`. Fungsi ini akan menuliskan sebuah log-log kenalam file log tersebut dengan format yang telah tientukan sebelumnya. namun disini dibuat 2 jenis fungsi yaitu 'logging' dan 'logging2' sebenrnya sama saja, namun dikarenakan ada output dengan parameter yang berbeda maka hanya berbeda di beberapa bagian kecil saja. ```c void logging(char *nama, char *fpath) { time_t rawtime; struct tm *timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); ``` pada potonggan kode diatas yaitu untuk mencari waktu dari secara Real-Time dari segala kegiatan eksekusi file dalam program. ```c char text[1000]; FILE *file; file = fopen("/home/kelvin/SinSeiFS.log", "a"); if (strcmp(nama, "RMDIR") == 0 || strcmp(nama, "UNLINK") == 0) sprintf(text, "WARNING::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, nama, fpath); else sprintf(text, "INFO::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, nama, fpath); ``` selanjutnya kita inisialisai sebuah arrat `text` yang nantinya akan digunakan untuk menyimpah suatu log secara sementara lalu akan ditaru pada file log yang telah dibuat sebelumnya. untuk 3 baris berikutnya yang diatas merupakan persyaratan dimana itu untuk membedakan level yang ada antara `INFO` dan `WARNING`. ```c fputs(text, file); fclose(file); return; } ``` lalu kita inputkan ke file dan kita tutup file tersebut. untuk `logging2 sma saja dan hanya berbeda sedikit seperti yang diucapkan tadi. code fungsi `logging2()` sebagai berikut : ```c void logging2(char *nama, char *fpath, char *ke) { time_t rawtime; struct tm *timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); char text[1000]; FILE *file; file = fopen("/home/kelvin/SinSeiFS.log", "a"); if (strcmp(nama, "RMDIR") == 0 || strcmp(nama, "UNLINK") == 0) sprintf(text, "WARNING::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, nama, fpath, ke); else sprintf(text, "INFO::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, nama, fpath, ke); fputs(text, file); fclose(file); return; } ``` lalu ada contoh dari log dimana program system nomor 1 dijalankan sebagai berikut : ![conoth no1 modul 4](https://user-images.githubusercontent.com/75328763/121812670-f6a17500-cc92-11eb-8e4f-1c0022f5a568.png)
C++
UTF-8
971
2.515625
3
[]
no_license
// // Created by chrustkiran on 6/13/19. // #include "Window.h" #include "StreamProcessor.h" /* void Window::checkInputEvent() { unique_lock<mutex> m_lock(m_mutex); while(this->inputCounter >= this->condVariable){ m_condition.wait(m_lock); } this->inputCounter++; //implemented for time window */ /* if(inputCounter == condVariable){ testVar = inputCounter; }*//* m_lock.unlock(); } */ long Window::getCondVariable() const { return condVariable; } void Window::setCondVariable(long condVariable) { this->condVariable = condVariable; } void Window::checkOutputEvent() { unique_lock<mutex> m_lock_out(m_mutex); this->outputCounter++; if(this->outputCounter == this->totalInput){ OutputEmitter::emitData(); StreamProcessor::processor->reset(); this->inputCounter = 0; this->outputCounter = 0; this->m_condition.notify_all(); } m_lock_out.unlock(); }
Java
UTF-8
6,066
2.140625
2
[]
no_license
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.core.io.parser.ascii; import java.io.BufferedReader; import java.io.IOException; import java.io.LineNumberReader; import org.caleydo.core.io.IDTypeParsingRules; import org.caleydo.core.io.MatrixDefinition; import org.caleydo.core.manager.GeneralManager; import org.caleydo.core.util.logging.Logger; import org.caleydo.data.loader.ResourceLoader; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; /** * Base class for text parsers. * * @author Alexander Lex * @author Marc Streit */ public abstract class ATextParser { /** * The path of the file to parse * * @deprecated should be replaced with the matrixDefinition */ @Deprecated protected final String filePath; /** * the loader to use for locating the file */ protected final ResourceLoader loader; /** * Contains the number of lines of the number of lines in the file to be parsed, after * {@link #calculateNumberOfLinesInFile()} was called. */ protected int numberOfLinesInFile = -1; /** * Defines at which line to start the parsing. This is, e.g., useful to ignore headers. Must be positive. Defaults * to 0, the first line. */ protected int startParsingAtLine = 0; /** * Defines at which line to stop parsing. Is set to parse all lines by default. */ protected int stopParsingAtLine = Integer.MAX_VALUE; /** The meta-data about the file */ private MatrixDefinition matrixDefinition; /** * Constructor. */ public ATextParser(final String filePath, MatrixDefinition matrixDefinition) { this.filePath = filePath; this.loader = GeneralManager.get().getResourceLoader(); this.matrixDefinition = matrixDefinition; } /** * @param startParsingAtLine * setter, see {@link #startParsingAtLine} */ public void setStartParsingAtLine(int startParsingAtLine) { if (startParsingAtLine < 0) throw new IllegalArgumentException("Can not start parsing at a negative line: " + startParsingAtLine); this.startParsingAtLine = startParsingAtLine; } /** * Setter for the line at which to stop parsing. If attribute is <0, all lines in the file are parsed. * * @param stopParsingAtLine * setter, see {@link #stopParsingAtLine} * */ public void setStopParsingAtLine(int stopParsingAtLine) { if (stopParsingAtLine < 0) this.stopParsingAtLine = Integer.MAX_VALUE; else this.stopParsingAtLine = stopParsingAtLine; } /** * Reads the file and counts the numbers of lines to be read. */ protected final int calculateNumberOfLinesInFile() { try { LineNumberReader lnr; lnr = new LineNumberReader(loader.getResource(filePath)); // no checks for the header lines - they can contain arbitrary stuff. if (matrixDefinition != null) { for (int lineCount = 0; lineCount < matrixDefinition.getNumberOfHeaderLines(); lineCount++) { lnr.readLine(); } } String line = null; while (true) { line = lnr.readLine(); if (line == null || line.isEmpty()) { numberOfLinesInFile = lnr.getLineNumber() - 1; if (line == null) { numberOfLinesInFile++; } break; } } // checking whether there is still some stuff (other than empty lines) after we encountered and empty line while (true) { line = lnr.readLine(); if (line == null) { break; } if (!line.isEmpty()) { lnr.close(); System.out.println("Fail" + numberOfLinesInFile); throw new IllegalStateException("File has empty line at line number " + numberOfLinesInFile + 1 + "\n File: " + matrixDefinition.getDataSourcePath()); } } lnr.close(); } catch (IOException ioe) { throw new IllegalStateException("Could not read from file: " + filePath); } return numberOfLinesInFile; } /** * Triggers the actual loading and parsing of the data specified. * * @return */ public boolean loadData() { try { Logger.log(new Status(IStatus.INFO, GeneralManager.PLUGIN_ID, "Start loading file " + filePath + "...")); BufferedReader reader = loader.getResource(filePath); this.parseFile(reader); if (reader != null) { reader.close(); } } catch (Exception e) { Logger.log(new Status(IStatus.ERROR, this.toString(), "Could not read data file.", e)); throw new IllegalStateException(e.getMessage(), e); } Logger.log(new Status(IStatus.INFO, toString(), "File " + filePath + " successfully loaded.")); return true; } protected abstract void parseFile(BufferedReader reader) throws IOException; /** * Converts a sourceID based on the {@link IDTypeParsingRules} specified and returns a new string with the converted * ID * * @param sourceID * @param idTypeParsingRules * @return a new String with the converted ID */ public static String convertID(String sourceID, IDTypeParsingRules idTypeParsingRules) { if (idTypeParsingRules == null) return sourceID; if (idTypeParsingRules.isToLowerCase()) sourceID = sourceID.toLowerCase(); else if (idTypeParsingRules.isToUpperCase()) sourceID = sourceID.toUpperCase(); if (idTypeParsingRules.getReplacingExpressions() != null) { for (String replacingExpression : idTypeParsingRules.getReplacingExpressions()) { sourceID = sourceID.replaceAll(replacingExpression, idTypeParsingRules.getReplacementString()); } } if (idTypeParsingRules.getSubStringExpression() != null) { String[] splitID = sourceID.split(idTypeParsingRules.getSubStringExpression()); // first one found used for (String result : splitID) { if (!result.isEmpty()) { sourceID = result; break; } } } return sourceID; } @Override public String toString() { return "Parser for " + filePath; } }
Python
UTF-8
956
3.953125
4
[]
no_license
#!/usr/bin/python # Version 1 print (30 * '-') print (" M A I N - M E N U") print (30 * '-') print ("1. Add Game") print ("2. View Current Game List") print ("3. Exit") print (30 * '-') ########################### ## Robust error handling ## ## only accept int ## ########################### ## Wait for valid input in while...not ### is_valid=0 while not is_valid : try : choice = int ( raw_input('Enter your choice [1-3] : ') ) is_valid = 1 ## set it to 1 to validate input and to terminate the while..not loop except ValueError, e : print ("'%s' is not a valid integer." % e.args[0].split(": ")[1]) ### Take action as per selected menu-option ### if choice == 1: print ("Adding Game...") elif choice == 2: print ("Viewing Current Game List...") elif choice == 3: print ("Exiting Application...") else: print ("Invalid number. Try again...")
Shell
UTF-8
1,090
3.53125
4
[]
no_license
#!/usr/bin/bash DIR=$(pwd) BUILDDIR="${DIR}/build" if [ -d "$BUILDDIR" ]; then rm -r "${BUILDDIR}" fi mkdir ${DIR}/build cd $DIR/build if [[ ( "$#" -ge 1 && "$1" == "--java" ) || "$#" < 1 ]]; then printf 'Building Java TCP server and Client: ' (while :; do for c in / - \\ \|; do printf '\b%s' "$c"; sleep 1; done; done) & cp ${DIR}/JavaFiles/* ${BUILDDIR} sleep 3 javac *.java > /dev/null { printf '\n'; kill $! && wait $!; } 2>/dev/null printf 'Java Server and Client Built.\n\n' fi if [ $# -ge 1 ] && [ "$1" == "--cserv" ] ; then printf 'Configuring and building C TCP client and Server: ' (while :; do for c in / - \\ \|; do printf '\b%s' "$c"; sleep 1; done; done) & sleep 3 cmake -DCSERVERBUILD=ON .. > /dev/null make >/dev/null { printf '\n'; kill $! && wait $!; } 2>/dev/null else printf 'Configuring and building C TCP client and Server: ' (while :; do for c in / - \\ \|; do printf '\b%s' "$c"; sleep 1; done; done) & sleep 3 cmake -DCSERVERBUILD=ON .. > /dev/null make >/dev/null { printf '\n'; kill $! && wait $!; } 2>/dev/null fi printf 'C Client and Server Built.\n\n'
TypeScript
UTF-8
2,793
3.265625
3
[]
no_license
import { validateEmptyProperties, ValidateEmptyPropertiesOutput } from "../src/validateEmptyProperties" describe("Testando a função validateEmptyProperties", () => { test("Erro quando alguma chave é uma string vazia", () => { const result: ValidateEmptyPropertiesOutput = validateEmptyProperties({ name: "" }) expect(result.isValid).toBe(false) expect(result.errors).toHaveLength(1) expect(result.errors.length).toBe(1) // mesmo teste do de cima expect(result.errors).toContainEqual({ key: "name", value: "" }) // {} === {} }) test("Erro quando alguma chave é zero", () => { const result: ValidateEmptyPropertiesOutput = validateEmptyProperties({ age: 0 }) expect(result.isValid).toBe(false) expect(result.errors).toHaveLength(1) expect(result.errors.length).toBe(1) // mesmo teste do de cima expect(result.errors).toContainEqual({ key: "age", value: 0 }) // {} === {} }) test("Erro quando alguma chave é undefined", () => { const result: ValidateEmptyPropertiesOutput = validateEmptyProperties({ name: undefined }) expect(result.isValid).toBe(false) expect(result.errors).toHaveLength(1) expect(result.errors.length).toBe(1) // mesmo teste do de cima expect(result.errors).toContainEqual({ key: "name", value: undefined }) // {} === {} }) test("Erro quando alguma chave é nula", () => { const result: ValidateEmptyPropertiesOutput = validateEmptyProperties({ email: null }) expect(result.isValid).toBe(false) expect(result.errors).toHaveLength(1) expect(result.errors.length).toBe(1) // mesmo teste do de cima expect(result.errors).toContainEqual({ key: "email", value: null }) // {} === {} }) test("Erro quando uma chave é válida e várias são inválidas", () => { const result: ValidateEmptyPropertiesOutput = validateEmptyProperties({ name: "", age: 0, email: undefined, password: null, id:"123-456" }) expect(result.isValid).toBe(false) expect(result.errors).toHaveLength(4) expect(result.errors.length).toBe(4) // mesmo teste do de cima }) test("Objeto válido", () => { const result: ValidateEmptyPropertiesOutput = validateEmptyProperties({ name: "astrodev", age: 110, email: "Astrodev@gmail.com", password: "dfsdfdsfsdf", id:"123-456" }) expect(result.isValid).toBe(true) expect(result.errors).toHaveLength(0) expect(result.errors.length).toBe(0) // mesmo teste do de cima }) })
TypeScript
UTF-8
328
3.453125
3
[ "MIT" ]
permissive
/* @internal */ export class IterateIterable<T> implements Iterable<T> { constructor(private readonly f: (x: T) => T, private readonly x: T) {} [Symbol.iterator]() { return iterate(this.f, this.x) } } function* iterate<T>(f: (x: T) => T, x: T) { while (true) { yield x x = f(x) } }
Java
UTF-8
1,341
2.265625
2
[ "MIT" ]
permissive
package com.refinedmods.refinedstorage.command.network.autocrafting; import com.mojang.brigadier.builder.ArgumentBuilder; import com.mojang.brigadier.context.CommandContext; import com.refinedmods.refinedstorage.api.autocrafting.task.ICraftingTask; import com.refinedmods.refinedstorage.api.network.INetwork; import com.refinedmods.refinedstorage.command.network.NetworkCommand; import net.minecraft.command.CommandSource; import net.minecraft.command.Commands; import net.minecraft.command.arguments.UUIDArgument; import java.util.UUID; public class CancelSingleAutocraftingCommand extends NetworkCommand { public static ArgumentBuilder<CommandSource, ?> register() { return Commands.argument("id", UUIDArgument.func_239194_a_()).suggests(new AutocraftingIdSuggestionProvider()) .executes(new CancelSingleAutocraftingCommand()); } @Override protected int run(CommandContext<CommandSource> context, INetwork network) { UUID id = UUIDArgument.func_239195_a_(context, "id"); int count = 0; ICraftingTask task = network.getCraftingManager().getTask(id); if (task != null) { count = 1; network.getCraftingManager().cancel(task.getId()); } CancelAllAutocraftingCommand.sendCancelMessage(context, count); return 0; } }
Python
UTF-8
2,665
3.84375
4
[]
no_license
from infrastructure import * import random class Player(object): def __init__(self, name): self.hand = [] self.name = name self.wins = 0 def __str__(self): return str(self.name) # gives a card back to a player def takeCard(self, card): if card != None: self.hand.append(card) else: print "takeCard: no card drawn. This seems like trouble -- investigate" def won(self): if len(self.hand) == 0: self.wins += 1 return True else: return False def clearHand(self, deck=None): """ If there is a deck, return the card to it. Else, simply clear the hand """ if (deck == None): self.hand = [] else: for card in self.hand: deck.append(card) # THIS IS WHAT THE GAME CALLS TO ASK FOR A PLAYER'S ACTION # removes and returns a card def takeAction(self, lastCard): """ the Game class calls this method on the player when it wants the player to submit a card for legality evaluation. the "last card" -- ie, the most recent faceup card -- is supplied as an argument. this method also handles modification of the player's "hand" returns the card that was chosen. """ card = self.chooseCard(lastCard) self.hand.remove(card) return card # Agent Method def modifyRule(self, game): """ The Game calls this method when a player wins, and is allowed to change a rule """ pass #AI METHOD HERE. Returns a card. DOES NOT REMOVE IT! def chooseCard(self, lastCard): """ AI implemented method for determining which card to return Default behavior: returns first card Return """ pass def screwOpponent(self, playerList): """ AI implemented method -- let's players screw over an opponent """ pass # AI IMPLEMENTED METHOD def notify(self, notification, game): """ notified when the state of the game changes, allows for analysis opportunity (ie updating beliefs) """ pass def getFeedback(self, isLegal): """ the player gets feedback from the game on whether their card was legal or not """ pass #tests # basic player taking action # d = Deck() # p = Player("j", True) # p.takeCard(d.drawCard()) # p.takeCard(d.drawCard()) # print p.takeAction()
JavaScript
UTF-8
1,546
3.609375
4
[]
no_license
var a = ['a','b','c','d'] for(i=0;i<a.length;i++){ console.log(a[i] + 1) } a.map((data) => { console.log(data+1)}) var a = ['a','b','c','d'] for(i=0;i<a.length;i++){ console.log(a[i] + 1) } VM94:4 a1 VM94:4 b1 VM94:4 c1 VM94:4 d1 undefined a.map((data) => { return data+1}) (4) ["a1", "b1", "c1", "d1"] a.map((data) => { console.log(data+1)}) VM105:1 a1 VM105:1 b1 VM105:1 c1 VM105:1 d1 var b = [28,14,22,51,47,23,17] b.filter((data) => {return data>20}) b.map((data) => {return data>20}) var b = [28,14,22,51,47,23,17] b.filter((data) => {return data>20}) (5) [28, 22, 51, 47, 23] b.map((data) => {return data>20}) (7) [true, false, true, true, true, true, false] --------------------------- var a =[0,1,2,3] a.map((item) => {return item*2}) a.filter((item) => {return item*2}) var a =[0,1,2,3] a.map((item) => {return item*2}) (4) [0, 2, 4, 6] a.filter((item) => {return item*2}) (3) [1, 2, 3] /* var => We can redeclare and reassign let => We cannot redecalare but can reassign const => We cannot redecalre nor reassign */ var a = 10 undefined a 10 var a = 11 undefined a 11 a=12 12 var a //declare a=10 //assigment let r = 10 undefined r 10 let r = 11 VM425:1 Uncaught SyntaxError: Identifier 'r' has already been declared at <anonymous>:1:1 (anonymous) @ VM425:1 r = 11 11 r 11 const d = 10 undefined d 10 const d = 11 VM559:1 Uncaught SyntaxError: Identifier 'd' has already been declared at <anonymous>:1:1 d=11 VM574:1 Uncaught TypeError: Assignment to constant variable. at <anonymous>:1:2
Java
UTF-8
563
2.984375
3
[]
no_license
package animations; import biuoop.DrawSurface; import other.Counter; /** * You Win screen class. */ public class YouWinScreen implements Animation { private Counter score; /** * Instantiates a new Pause screen. * * @param score the score to print */ public YouWinScreen(Counter score) { this.score = score; } @Override public void doOneFrame(DrawSurface d) { d.drawText(70, d.getHeight() / 2, "You Win! Your score is " + this.score.getValue(), 50); } @Override public boolean shouldStop() { return false; } }
Markdown
UTF-8
3,444
2.515625
3
[ "CC-BY-3.0", "MIT" ]
permissive
**Are you the copyright holder or authorized to act on the copyright owner's behalf?** Yes, I am authorized to act on the copyright owner's behalf. **Please describe the nature of your copyright ownership or authorization to act on the owner's behalf.** I am Legal Counsel at Bending Spoons, the copyright owner. **Please provide a detailed description of the original copyrighted work that has allegedly been infringed. If possible, include a URL to where it is posted online.** The original copyrighted work includes the entire repository that can be found at the following link: [private] The copyrighted work also includes the text in the README.md file hosted therein which are instructions to complete our proprietary test. The README file also has a "Copyright & Non-Disclosure Agreement" that was purposefully removed from the infringing content, and that stated: "Do not disclose this challenge, or any solution to it, to anyone in any form. All rights are reserved by Bending Spoons S.p.A." The same document, in its original form, now states: "By undertaking this challenge, you agree not to disclose any part of it, nor any solution to it, to anyone in any form. All rights are reserved by Bending Spoons S.p.A.." **What files should be taken down? Please provide URLs for each file, or if the entire repository, the repository’s URL.** The entire repository available at the following link is an unauthorized copy and should be taken down: https://github.com/cremig92/treasurer-challenge-cremig92 **Have you searched for any forks of the allegedly infringing files or repositories? Each fork is a distinct repository and must be identified separately if you believe it is infringing and wish to have it taken down.** To our knowledge, there are no forks of the infringing repository. **Is the work licensed under an open source license? If so, which open source license? Are the allegedly infringing files being used under the open source license, or are they in violation of the license?** The work is not licensed under an open source license. **What would be the best solution for the alleged infringement? Are there specific changes the other person can make other than removal? Can the repository be made private?** We have made several attempts at contacting the user directly to no avail. The infringing repository is an unauthorized copy and should be deleted in its entirety. **Do you have the alleged infringer’s contact information? If so, please provide it.** https://github.com/cremig92 **I have a good faith belief that use of the copyrighted materials described above on the infringing web pages is not authorized by the copyright owner, or its agent, or the law.** **I have taken <a href="https://www.lumendatabase.org/topics/22">fair use</a> into consideration.** **I swear, under penalty of perjury, that the information in this notification is accurate and that I am the copyright owner, or am authorized to act on behalf of the owner, of an exclusive right that is allegedly infringed.** **I have read and understand GitHub's <a href="https://help.github.com/articles/guide-to-submitting-a-dmca-takedown-notice/">Guide to Submitting a DMCA Takedown Notice</a>.** **So that we can get back to you, please provide either your telephone number or physical address.** [private] [private] [private] **Please type your full legal name below to sign this request.** [private]
C++
UTF-8
881
3.3125
3
[]
no_license
//Given an integer array A of N elements. You need to find the sum of two elements such that sum is closest to zero. #include <bits/stdc++.h> using namespace std; int sum_closest_to_zero(int a[], int n){ int i, sum = 0, min = INT_MAX; int l = 0, r = n-1; int min_l = l, min_r = n-1; sort(a, a+n); while(l < r) { sum = a[l] + a[r]; if(abs(sum) < abs(min)) { min = sum; min_l = l; min_r = r; } if(sum < 0) l++; else r--; } return a[min_l]+ a[min_r]; } int main() { int t; scanf("%d", &t); while(t--) { int n, i; scanf("%d", &n); int a[n]; for(i = 0; i < n; i++) scanf("%d", &a[i]); printf("%d\n",sum_closest_to_zero(a, n)); } }
JavaScript
UTF-8
1,528
2.65625
3
[]
no_license
/* istanbul ignore file */ // @ts-ignore const AWS = require('aws-sdk'); // @ts-ignore const fs = require('fs'); // @ts-ignore const {S3_BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, NODE_ENV} = process.env; const params = { Bucket: S3_BUCKET, CreateBucketConfiguration: { // Set your region here LocationConstraint: "eu-west-1" } }; const s3 = new AWS.S3({ accessKeyId: AWS_ACCESS_KEY_ID, secretAccessKey: AWS_SECRET_ACCESS_KEY }); // @ts-ignore const uploadFile = (targetFile, fileName, buketName = S3_BUCKET) => { // Read content from the file if (!targetFile && !fileName) { console.error('targetFile and targetfilename required to upload file'); return 'targetFile and fileName required to upload file'; } const fileContent = fs.readFileSync(targetFile); // Setting up S3 upload parameters const params = { Bucket: S3_BUCKET, Key: fileName, // File name you want to save as in S3 Body: fileContent }; // Uploading files to the bucket // @ts-ignore console.log(targetFile, fileName); if (NODE_ENV !== 'local') { // @ts-ignore s3.upload(params, (err, data) => { if (err) { console.error(err); } else { // @ts-ignore fs.unlink(targetFile, err => { if (err) console.error(err); // if no error, file has been deleted successfully }); console.log(`File uploaded successfully. ${data.Location}`); } }); } }; //usage /*uploadFile('./storage/realfile1.txt', 'accountname/realfile1.txt'); */ // @ts-ignore module.exports = {uploadFile: uploadFile};
Java
UTF-8
716
2.46875
2
[]
no_license
package com.dao; import com.model.Role; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; @Repository @Transactional public class RoleDaoImpl implements RoleDao { @PersistenceContext private EntityManager entityManager; @Override public Role getRoleByName(String name) { return entityManager.createQuery("from Role", Role.class).getSingleResult(); } @Override public Role getRoleByID(Long id) { return entityManager.find(Role.class, id); } @Override public void addRole(Role role) { entityManager.persist(role); } }
Markdown
UTF-8
3,709
3.875
4
[]
no_license
# thread1 thread program 2. Write a multithreaded program that calculates various statistical values for a list of numbers. This program will be passed a series of numbers on the command line and will then create three separate worker threads. One thread will determine the average of the numbers, the second will determine the maximum value, and the third will determine the minimum value. For example, suppose your program is passed the integers 90 81 78 95 79 72 85 The program will report The average value is 82 The minimum value is 72 The maximum value is 95 The variables representing the average, minimum, and maximum values will be stored globally. The worker threads will set these values, and the parent thread will output the values once the workers have exited. #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *avg(void *str); void *min(void *ptr); void *max(void *ptr); double avg; int min; int max; typedef struct datastruct { int size; int * values; }datastruct; main(int a, char *r[]) { printf("\n\nWelcome to paheeThredz, by Sean Staz\n\n"); while(argc <=1) { printf("Incorrect input. No arguments entered.\n"); printf("Please enter one or more inputs.\n"); exit(0); } int i = 0; int copy[a-1]; for(i; i < (a -1); i++) { copy[i] = atoi(r[i+1]); } pthread_t thread1, thread2, thread3; const char *message1 = "This is Thread 1"; const char *message2 = "This is Thread 2"; const char *message3 = "This is Thread 3"; int t1, t2, t3; printf("Running: %s\n\n", argv[0]); datastruct ds = {a - 1, copy}; t1 = pthread_create(&thread1, NULL, (void *) avg, (void *) &ds); if(t1) { fprintf(stderr,"Error - pthread_create() return code: %d\n", t1); exit(EXIT_FAILURE); } t2 = pthread_create(&thread2, NULL, (void *) min, (void *) &ds); if(t2) { fprintf(stderr,"Error - pthread_create() return code: %d\n",t2); exit(EXIT_FAILURE); } t3 = pthread_create(&thread3, NULL, (void *) max, (void *) &ds); if(t3) { fprintf(stderr,"Error - pthread_create() return code: %d\n", t3); exit(EXIT_FAILURE); } printf("pthread_create() for Thread 1 returns: %d\n",t1); printf("pthread_create() for Thread 2 returns: %d\n",t2); printf("pthread_create() for Thread 3 returns: %d\n\n",t3); /* Wait till threads are complete before main continues. */ pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); printf("The average: %g\n", avg); printf("The minimum: %d\n", min); printf("The maximum: %d\n", max); exit(EXIT_SUCCESS); } void *avg(void *ptr) { datastruct * copy; copy = (datastruct *) ptr; int sz = copy->size; int i; for(i = 0; i < sz; i++) { avg += (copy->values[i]); } avg = (int)(avg / sz); } void *min(void *ptr) { datastruct * copy; copy = (datastruct *) ptr; int sz = copy->size; int i; min = (copy->values[0]); for(i = 1; i < sz; i++) { if(min > (copy->values[i])) { min = (copy->values[i]); } } } void *max(void *ptr) { datastruct * copy; copy = (datastruct *) ptr; int sz = copy->size; int i; max = copy->values[0]; for(i = 1; i < sz; i++) { if(max < copy->values[i]) { max = copy->values[i]; } } }
Python
UTF-8
1,105
3.8125
4
[]
no_license
'''Implement Merge algorithm to sort an integer array in ascending order''' def merge_sort(alist): '''merge sort of list''' if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] merge_sort(lefthalf) merge_sort(righthalf) i = 0 j = 0 k = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k] = lefthalf[i] i = i+1 else: alist[k] = righthalf[j] j = j+1 k = k+1 while i < len(lefthalf): alist[k] = lefthalf[i] i = i+1 k = k+1 while j < len(righthalf): alist[k] = righthalf[j] j = j+1 k = k+1 return alist # Driver code to test above NUM_IN = int(input()) for _ in range(NUM_IN): user_input = input() list_ = user_input.split() arr = [] for a in list_: arr.append(int(a)) # arr = [12, 11, 13, 5, 6, 7] merge_sort(arr) print(arr)
Ruby
UTF-8
1,346
4.03125
4
[]
no_license
# --- Day 5: A Maze of Twisty Trampolines, All Alike --- # # An urgent interrupt arrives from the CPU: it's trapped in a maze of # jump instructions, and it would like assistance from any programs # with spare cycles to help find the exit. # # The message includes a list of the offsets for each jump. Jumps are # relative: -1 moves to the previous instruction, and 2 skips the next # one. Start at the first instruction in the list. The goal is to # follow the jumps until one leads outside the list. # # In addition, these instructions are a little strange; after each # jump, the offset of that instruction increases by 1. So, if you # come across an offset of 3, you would move three instructions # forward, but change it to a 4 for the next time it is encountered. # # How many steps does it take to reach the exit? def run(adjust) a = IO.read("05.in").split.map{|o|o.to_i} i = 0 n = 0 while true n += 1 j = i + a[i] a[i] = adjust.(a[i]) i = j return n if i < 0 or i >= a.length end end puts run(lambda {|o| o+1 }) # --- Part Two --- # # Now, the jumps are even stranger: after each jump, if the offset was # three or more, instead decrease it by 1. Otherwise, increase it by # 1 as before. # # How many steps does it now take to reach the exit? puts run(lambda {|o| if o >= 3 then o-1 else o+1 end })
Markdown
UTF-8
978
2.796875
3
[ "BSD-3-Clause" ]
permissive
# Font The Font object can be used to load and render TrueType fonts. Example use: ```Io // within a GLUT display callback... timesFont = Font clone open(\"times.ttf\") if (timesFont error, write(\"Error loading font: \", timesFont error, \"\n\"); return) timesFont setPointSize(16) glColor(0,0,0,1) timesFont draw(\"This is a test.\") ``` <b>Rendering fonts using OpenGL textures</b> Smaller fonts (those having a point size around 30 or smaller, depending on the font) will automatically be cached in and rendered from a texture. This technique is very fast and should support rendering speeds as fast (or faster than) those of typical desktop font rendering systems. Larger font sizes(due to texture memory constraints) will be rendered to a pixelmap when displayed. Thanks to Mike Austin for implementing the font texturing system. # Installation `freetype` should be install and foundable in your system. Then: ``` eerie install https://github.com/IoLanguage/Font.git ```
Java
UTF-8
3,917
2.1875
2
[]
no_license
package nanifarfalla.app.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import nanifarfalla.app.model.ClienteTienePedido; import nanifarfalla.app.model.Pedido; @Repository public interface ClienteTienePedidoRepository extends JpaRepository<ClienteTienePedido, Integer> { @Query(value = "select * " + "from cliente_tiene_pedido ctp " + "inner join usuario u on u.codigo_usuario=ctp.fkcodigo_usuario " + "inner join factura_c_tiene_pedido fc on fc.codigo_factura_cliente_tiene_pedido=ctp.fkcodigo_factura_cliente_tiene_pedido " + "inner join estado_cliente_tiene_pedido ec on ec.codigo_estado_cliente_tiene_pedido=ctp.fkcodigo_estado_cliente_tiene_pedido " + "inner join cliente c on c.codigo_cliente=ctp.fkcodigo_cliente " + "where u.codigo_usuario=:idCliente ", nativeQuery = true) List<ClienteTienePedido> findPedidos(@Param("idCliente") int idCliente); @Query(value = "select p.nombre_producto, p.foto_ruta, l.nombre_linea, p.stock_producto, pxp.cantidad_producto, pxp.valor_con_igv, pxp.valor_neto, ctp.cantidad_producto, u.nombre_usuario, u.apellido_usuario, u.email" + "from cliente_tiene_pedido ctp " + "inner join usuario u on u.codigo_usuario=ctp.fkcodigo_usuario " + "inner join producto_por_pedido pxp on ctp.codigo_pedido_web = pxp.fkcodigo_pedido_web " + "inner join producto p on p.codigo_producto = pxp.fkcodigo_producto " + "inner join linea l on l.codigo_linea = p.fkcodigo_linea " + "where u.codigo_usuario=:idCliente ", nativeQuery = true) List<ClienteTienePedido> findPedidosCart(@Param("idCliente") int idCliente); /*x * @Query(value =u * "select x.codigo_pedido_web, x.fkcodigo_suario, x.fkcodigo_cliente, x.fkcodigo_vendedor, x.fkcodigo_igv_venta, x.fkcodigo_promocion_venta, " * + * "x.fkcodigo_estado_cliente_tiene_pedido, x.fkcodigo_factura_cliente_tiene_pedido, x.descuento_web_pedido, x.precio_uni_desc_igv, x.precio_uni_desc_sin_igv, x.fecha_pedido, x.fecha_entrega, " * +"x.cantidad_producto, x.monto_por_descuento " + "from producto as x " + * "inner join usuario as u on x.fkcodigo_usuario = u.codigo_usuario " + * "inner join cliente as c on x.fkcodigo_cliente = c.codigo_cliente " + * "inner join vendedor as v on x.fkcodigo_vendedor = v.codigo_vendedor " + * "inner join igv_venta as i on x.fkcodigo_igv_venta = i.codigo_igv_venta " + * "inner join promocion_venta as p on x.fkcodigo_promocion_venta = p.codigo_promocion_venta " * + * "inner join estado_cliente_tiene_pedido as e on x.fkcodigo_estado_cliente_tiene_pedido = e.codigo_estado_cliente_tiene_pedido " * + * "inner join factura_c_tiene_pedido as f on x.fkcodigo_factura_cliente_tiene_pedido = f.codigo_factura_cliente_tiene_pedido " * + "where u.codigo_usuario = :idUsuario ", nativeQuery = true) * List<ClienteTienePedido> getPedidotieneProductos(@Param("idUsuario") int * idUsuario); * * * * @Query(value = * "select p.codigo_producto, p.fkcodigo_linea, p.nombre_producto from Producto p where p.fkcodigo_linea = ?1" * , nativeQuery = true) List<ClienteTienePedido> findByFkcodigo_linea(int * codigo_linea); * * * @Query("select new nanifarfalla.app.model.Producto(codigo_producto, nombre_producto) from Producto where mLinea.codigo_linea = :id" * ) List<ClienteTienePedido> findByLinea(@Param("id") int id); * * * @Query("select p from Producto p where p.mLinea.codigo_linea = ?1") * List<ClienteTienePedido> BuscaLineaporClase(int id); * * * @Query("select p from Producto p where p.mLinea.codigo_linea = :idLinea") * List<ClienteTienePedido> BuscarLineaClaseconParam(@Param("idLinea") int * codig_linea); */ }
Markdown
UTF-8
1,254
2.625
3
[]
no_license
# cf-and-s3-static-server-with-minio-proxy It provides a static server as a AWS Cloudfront and S3, and a proxy server as a local [minio](https://min.io/) server. ## Why? It is used in an environment where there is no direct access to s3. For example, if only one host in the corporate network can access s3, a minio server is launched on this host, allowing other hosts to access s3 through this minio server. ## Usage Deploy to AWS Cloudfront and S3. ``` # example, export TF_VAR_namespace=static-server export TF_VAR_stage=dev export TF_VAR_name=bucket-987349187 # s3 bucket name is static-server-dev-bucket-987349187-origin $ terraform apply ``` ## Environments ``` export AWS_ACCESS_KEY_ID=AKXXXXXXXXXXXXXXXX4S export AWS_SECRET_ACCESS_KEY=joxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxJd export AWS_DEFAULT_REGION=ap-northeast-1 export MINIO_ACCESS_KEY=minioproxy export MINIO_SECRET_KEY=minioproxy123 export SOURCE_BUCKET_NAME=study # You should create and use a bucket in minio with this name, # S3 bucket name to be synced. # It can be obtained from the output values after terraform apply. export TARGET_BUCKET_NAME=s3_bucket_name ``` ## Run minio After setting the environment variable, execute the minio and `handle-events.ts` with docker-compose. ``` $ docker-compose up -d ```
Java
UTF-8
744
3.25
3
[]
no_license
import java.util.ArrayDeque; import java.util.ArrayList; class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x){ val=x; } } public class BSTIterator { ArrayList<Integer> nodesSorted; int index; public BSTIterator(TreeNode root){ this.nodesSorted=new ArrayList<Integer>(); this.inorder(root); index=-1; } public void inorder(TreeNode node){ if(node==null) return; inorder(node.left); this.nodesSorted.add(node.val); inorder(node.right); } public int next(){ return this.nodesSorted.get(++index); } public boolean hasNext(){ return this.index+1<this.nodesSorted.size(); } }
Python
UTF-8
1,042
2.578125
3
[]
no_license
import csv import numpy as np import pandas as pd import matplotlib.pyplot as plt # seabornがあると、グラフがきれいにかける import seaborn as sns sns.set_style("darkgrid") from mpl_toolkits.mplot3d import Axes3D file = 'sample.csv' usecols = [1,133] skiprows = [0,1,2,3,4,5] names = ["Time","Between-the-hand"] df = pd.read_csv(file,usecols=usecols,skiprows=skiprows,names=names,header=None) # print(df) print(df["Between-the-hand"]) # print(df.query("Time <= 10")) # これより下で3次元プロットを試す。 # Top.head_Xだけ抽出する limit_time = 20 X = df.query("Time <= %i"%limit_time)[names[0]] Y = df.query("Time <= %i"%limit_time)[names[1]] # Z = df.query("Time <= %i"%limit_time)["Top.head_Z"] # print(len(X)) # fig = plt.figure() plt.figure() # ax = Axes3D(fig) l=0 t = len(X)-1 b=0 a=0 s=t-b while(l<=t): while(a<=s): plt.plot(X[l:t+1],Y[l:t+1], c=((a/s)*1.0,0.0,((s-a)/s)*1.0),lw=0.5) l=l+1 a=a+1 plt.xlabel(names[0]) plt.ylabel(names[1]) # ax.set_zlabel("Top.head_Z") plt.show()
Java
UTF-8
273
3.21875
3
[]
no_license
package array; public class printMultiDimArrays { public static void main(String args[]) { int arr[][]= { {2,7,9}, {3,6,1}, {7,4,2} }; for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
JavaScript
UTF-8
383
4.0625
4
[]
no_license
/* 给出 nums = [0, 1, 0, 3, 12], target = 0; 调用函数之后, 得到nums = [1, 3, 12, 0, 0].*/ var moveItems=(arr,target)=>{ var tmp= arr.filter(element=>element!=target); var tmpLength=tmp.length; for(let i=0;i<arr.length-tmpLength;i++){ tmp.push(target); } return tmp; } nums = [0, 1, 0, 3, 12]; target = 0; console.log(moveItems(nums,target));
JavaScript
UTF-8
3,935
2.671875
3
[ "MIT" ]
permissive
/** * js script **/ function loadUrl(url){ params['formURL'] = base_api_url+'films?page='+url; //alert( base_api_url+'films?page='+url); loadFilm(token, params); } function loadFilm(token, params){ var dat = {token:token,data:params["postData"]}; var objVal = ''; var htmlStr = ''; var i; if(params["postData"]){ $('#ajaxLoader').show(); } $.get(params["formURL"], dat, function(data, status){ //alert("Data: " + data + "\nStatus: " + status); //One Film objVal = data['data']['films']['data'][0]; strGenres = data['data']['films']['data']['genres']; Object.keys(objVal).forEach(function(k){ // console.log(k + ' - ' + objVal[k]); htmlStr = ''; htmlStr += '<img src="'+objVal['photo_url']+'" alt="'+objVal['name']+'" width="40%">'; htmlStr += '<div class="caption">'; htmlStr += '<h3>'+objVal['name']+'</h3>'; htmlStr += '<p>'+objVal['description']+' </p>'; htmlStr += '<p><b>Release Date:</b> '+objVal['release_date']+'</p>'; htmlStr += '<p><b>Rating:</b>'+objVal['rating']+'</p>'; htmlStr += '<p><b>Ticket Price:</b> '+objVal['ticket_price']+'</p>'; htmlStr += '<p><b>Country:</b> '+objVal['country']+'</p>'; htmlStr += '<p><b>Genres:</b> ' +strGenres+''; htmlStr += '</p>'; htmlStr += '<p>'; htmlStr += '<a href="'+base_url+'films/'+objVal['slug']+'" class="btn btn-primary" role="button">Show</a>'; htmlStr += '<a href="'+base_url+'films/'+objVal['id']+'/edit" class="btn btn-default" role="button">Edit</a>'; htmlStr += '</p><form method="POST" action="'+base_url+'films/'+objVal['id']+'" accept-charset="UTF-8" onsubmit="return confirm(&quot;Are you sure ?&quot;)"><input name="_method" type="hidden" value="DELETE"><input name="_token" type="hidden" value="Vt4Cvrb3e5R8DrmauN7YmPxC1SkYyuqqvWygNhf6">'; htmlStr += '<input class="btn btn-danger" type="submit" value="Delete">'; htmlStr += '</form>'; htmlStr += '<p></p>'; htmlStr += '</div>'; }); $('.filmData').html(htmlStr); // Film Pagination objVal = data['data']['films']; Object.keys(objVal).forEach(function(k){ htmlStr = ''; htmlStr += '<ul class="pagination" role="navigation">'; htmlStr += '<li class="page-item">'; htmlStr += ' <a class="page-link" onclick="loadUrl(1)" href="#" rel="next" aria-label="">« First</a>'; htmlStr += '</li>'; for (i = 1; i <= parseInt(objVal['total']); i++) { if(objVal['current_page']==i) htmlStr += '<li class="page-item active"><a class="page-link" onclick="loadUrl('+i+')" href="#" >'+i+'</a></li>'; else htmlStr += '<li class="page-item "><a class="page-link" onclick="loadUrl('+i+')" href="#" >'+i+'</a></li>'; } htmlStr += '<li class="page-item">'; htmlStr += ' <a class="page-link" onclick="loadUrl('+objVal['total']+')" rel="next" aria-label="Last »">Last »</a>'; htmlStr += '</li>'; htmlStr += '</ul>'; }); //Pagination Div $('#pages').html(htmlStr); }).done(function() { //alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { // After finish $('#ajaxLoader').hide(); }); } $("#logoutX").click(function () { localStorage.removeItem("token"); localStorage.removeItem("UserDataStr"); window.location = "."; }); function postForm(token, params){ var dat = {token:token,data:params["postData"]}; $.post(params["formURL"], dat, function(data, status){ alert("Data: " + data + "\nStatus: " + status); }).done(function() { alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); }); }
Java
UTF-8
3,466
2.65625
3
[]
no_license
package com.flytxt.atom.entity; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.apache.avro.Schema; //import org.apache.avro.Schema; import com.flytxt.atom.SerializationException; /** * @author athul * */ public class Complex { public Boolean[] boolArray = new Boolean[50]; public Long[] longArray = new Long[50]; private static final Map<Byte, Schema> schemas = new HashMap<>(); static { schemas.put((byte) 1, new Schema.Parser().parse( "{\"type\":\"record\",\"name\":\"Complex\",\"namespace\":\"com.flytxt.atom.entity\",\"fields\":[{\"name\":\"longArray\",\"type\":[{\"type\":\"array\",\"items\":[\"long\",\"null\"],\"java-class\":\"[Ljava.lang.Long;\"},\"null\"]},{\"name\":\"boolArray\",\"type\":[{\"type\":\"array\",\"items\":[\"boolean\",\"null\"],\"java-class\":\"[Ljava.lang.Boolean;\"},\"null\"]}]}")); } public Complex(boolean setValues) { Random random = new Random(); long randomLong = random.nextLong(); for (int i = 0; i < 50; i++) { this.longArray[i] = random.nextInt() % 2 == 0 ? randomLong += 20 : null; boolArray[i] = (i % (random.nextInt(50) + 1)) % 2 == 0 ? random.nextBoolean() : null; } } public Complex() { } public Compressed compress() { Compressed compressed = new Compressed(); for (int i = 0; i < 50; i++) { int theChosenOne = i / 4, position = i % 4; if (this.boolArray[i] == null) { compressed.boolArray[theChosenOne] |= (2 << (6 - (2 * position))); } else if (this.boolArray[i]) { compressed.boolArray[theChosenOne] |= (3 << (6 - (2 * position))); } } boolean isLongBaseSet = false; int valuesPresent = 0; for (int i = 0; i < 50; i++) { if (this.longArray[i] != null) { int theChosenOne = i / 8, position = i % 8; compressed.longArrayValuePresent[theChosenOne] |= (1 << (7 - position)); // setting the corresponding // bit if (isLongBaseSet) { long difference = this.longArray[i] - compressed.longBase; if (difference != (int) difference) { // difference is LONG compressed.diffValuesLong[valuesPresent] = difference; compressed.longArrayValueType[theChosenOne] |= (1 << (7 - position)); // setting the // corresponding bit } else { // difference is INT compressed.diffValuesInt[valuesPresent] = (int) difference; } } else { compressed.longBase = this.longArray[i]; isLongBaseSet = true; } valuesPresent += 1; } } return compressed; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 50; i++) sb.append(boolArray[i] + ","); sb.deleteCharAt(sb.length() - 1); sb.append("\n"); for (int i = 0; i < 50; i++) sb.append(longArray[i] + ","); sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public static void main(String[] args) throws IOException, SerializationException { Complex testObj = new Complex(true); System.out.println(testObj); long t1 = System.currentTimeMillis(); Compressed compressed = testObj.compress(); byte[] serialized = compressed.serialize(); Compressed deserialized = Compressed.deserialize(serialized); Complex expanded = deserialized.expand(); long t2 = System.currentTimeMillis() - t1; System.out.println(expanded); System.out.println("Time taken:" + t2); } }
Go
UTF-8
1,601
3.15625
3
[]
no_license
package database import ( "fmt" "log" "sync" ) var ( once sync.Once instance map[string]RuleConfiguration infoLog string = "INFO: [DB]:" errorLog string = "ERROR: [DB]:" ) // RuleConfiguration is used to store data in the node database type RuleConfiguration struct { SrcIP string `json:"SrcIP"` DstIP string `json:"DstIP"` Protocol string `json:"Protocol"` FlowID string `json:"FlowID"` Interface string `json:"Interface"` DstMAC string `json:"DstMAC"` Action string `json:"Action"` IsActive bool `json:"IsActive"` } // GetDatabase is used to get one instance of the db func GetDatabase() map[string]RuleConfiguration { log.Println(infoLog, "Invoke GetDatabase") once.Do(func() { instance = make(map[string]RuleConfiguration) }) return instance } // CreateRule is used to add a rule func CreateRule(key string, newRule RuleConfiguration) { log.Println(infoLog, "Invoke CreateRule") db := GetDatabase() db[key] = newRule } // ViewRules is used to print the database func ViewRules() { log.Println(infoLog, "Invoke ViewRules") db := GetDatabase() for key, value := range db { fmt.Println(key, value) } } // DeleteRule is used to delete a rule func DeleteRule(key string) { log.Println(infoLog, "Invoke DeleteRule") db := GetDatabase() delete(db, key) } // SetRuleState is used to set the state of a rule func SetRuleState(key string, isActive bool) bool { log.Println(infoLog, "Invoke SetRuleState") db := GetDatabase() if rule, found := db[key]; found { rule.IsActive = isActive db[key] = rule return true } return false }
JavaScript
UTF-8
2,694
2.671875
3
[]
no_license
module.exports = async function(client, message) { const resenhaList = require('../auxiliary/resenhaLoadList'); let first = [], second = [], third = []; let resenhistaCoin; let resenhistaName; for (let index = 0; index < resenhaList.length; index++) { resenhistaCoin = resenhaList[index].coin; resenhistaName = resenhaList[index].name; if ( index === 0 ) { first.push(resenhistaName); first.push(resenhistaCoin); } else if ( index === 1 ){ if ( resenhistaCoin > first[1] ) { second.push(first[0]); second.push(first[1]); first[0] = resenhistaName; first[1] = resenhistaCoin; } else { second.push(resenhistaName); second.push(resenhistaCoin); } } else if ( index === 2 ){ if ( resenhistaCoin > first[1] ) { third.push(second[0]); third.push(second[1]); second[0] = first[0]; second[1] = first[1]; first[0] = resenhistaName; first[1] = resenhistaCoin; } else if (resenhistaCoin > second[1]){ third.push(second[0]); third.push(second[1]); second[0] = resenhistaName; second[1] = resenhistaCoin; } else { third.push(resenhistaName); third.push(resenhistaCoin); } } else { if ( resenhistaCoin > first[1] ) { third[0] = second[0]; third[1] = second[1]; second[0] = first[0]; second[1] = first[1]; first[0] = resenhistaName; first[1] = resenhistaCoin; } else if ( resenhistaCoin > second[1] ){ third[0] = second[0]; third[1] = second[1]; second[0] = resenhistaName; second[1] = resenhistaCoin; } else if ( resenhistaCoin > third[1] ) { third[0] = resenhistaName; third[1] = resenhistaCoin; } } } first[1] = (first[1].toFixed(2)).replace('.', ','); second[1] = (second[1].toFixed(2)).replace('.', ','); third[1] = (third[1].toFixed(2)).replace('.', ','); await client.sendText(await message.chatId, `🏆🎖 *RANK DE COINS* 🎖🏆\n\n🥇 *${first[0]}* \t\t R₡ ${first[1]}\n🥈 *${second[0]}* \t\t R₡ ${second[1]}\n🥉 *${third[0]}* \t\t R₡ ${third[1]}`); }
Python
UTF-8
2,469
3.03125
3
[]
no_license
import tkinter as tk from tkinter.constants import END from tkinter.scrolledtext import * from tkinter.filedialog import * from tkinter.messagebox import * nuvarandefil = 'no file' def new_file(): """ Creates" a new file """ global nuvarandefil textruta.delete(1.0, tk.END) nuvarandefil = 'no file' def open_file(): global nuvarandefil filnamn = tk.filedialog.askopenfilename( filetype=( ('Textfile', '*.txt'), ('html-filer', '*.html'), ('Alla filer', '*.*') ) ) if filnamn: try: fil = open(filnamn, 'r', encoding='utf-8') rader = fil.read() nuvarandefil = filnamn except: tk.messagebox.showerror('Filfel', 'kunde inte öppna filen') else: textruta.delete(1.0, tk.END) textruta.insert(1.0, rader) finally: try: fil.close() except: pass def savefile(): global nuvarandefil filnamn = nuvarandefil rader = textruta.get(1.0, tk.END) if filnamn != 'no file': try: fil = open(filnamn, 'w', encoding='utf-8') fil.write(rader) except: tk.messagebox.showerror('Filefel', 'kunde inte öppna filen') else: file.close() else: saveas() def saveas(): global nuvarandefil filnamn = tk.filedialog.asksaveasfilename( filetypes=( ('Textfile', '*.txt'), ('html-filer', '*.html'), ('Alla filer', '*.*') ), defaultextension=".txt", ) if filnamn: nuvarandefil = filnamn savefile() root = tk.Tk() root.title('noootpad') root.geometry('800x400') root.resizable(False, False) textruta = ScrolledText( root, wrap=tk.interWORD, font=("Times New Roman", 15), undo=True ) textruta.pack() main_menu = tk.interMenu() root.config(menu=main_menu) file_menu = tk.interMenu(main_menu, tearoff=False) main_menu.add_cascade(label='File', menu=file_menu) file_menu.add_command(label='New', command=new_file) file_menu.add_command(label='Open', command=open_file) file_menu.add_command(label='Save', command=savefile) file_menu.add_command(label='Save As', command=saveas) file_menu.add_command(label='Exit', command=root.destroy) root.mainloop()
Java
UTF-8
2,176
2.53125
3
[]
no_license
package com.constpetrov.runstreets.model; import java.util.StringTokenizer; import android.os.Parcel; import android.os.Parcelable; public class Area implements Parcelable{ public static Parcelable.Creator<Area> CREATOR = new Parcelable.Creator<Area>() { @Override public Area createFromParcel(Parcel source) { return new Area(source); } @Override public Area[] newArray(int size) { return new Area[size]; } }; private int id; private String code; private int parentId; private int type; private String name; private String doc; public Area(){}; public Area(Parcel in){ id = in.readInt(); code = in.readString(); parentId = in.readInt(); type = in.readInt(); name = in.readString(); doc = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(code); dest.writeInt(parentId); dest.writeInt(type); dest.writeString(name); dest.writeString(doc); } @Override public String toString(){ return getAbbr(); } private String getAbbr() { if(getName().startsWith("Зелен")){ return "Зеленоград"; } StringTokenizer tokenizer = new StringTokenizer(getName(), " -"); StringBuilder b = new StringBuilder(); while (tokenizer.hasMoreTokens()){ b.append(tokenizer.nextToken().substring(0,1).toUpperCase()); } return b.toString(); } public String getDistrictName(){ return getName().replace("Район ", "").replace(" район", ""); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public int getParentId() { return parentId; } public void setParentId(int parentId) { this.parentId = parentId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDoc() { return doc; } public void setDoc(String doc) { this.doc = doc; } @Override public int describeContents() { return 0; } }
Shell
UTF-8
626
3.15625
3
[]
no_license
#!/bin/bash set -euo pipefail YEAR="$(date +%Y)" set +u source venv/bin/activate set -u echo "Downloading data for past week" ./hsotool.py --config hsotool_config.yaml echo "Converting xlsx data to csv" ./conversion.py $PWD/data_current.xlsx -o file_kwh_current.csv house_energy -t xlsx ./conversion.py $PWD/data_current.xlsx -o file_temp_current.csv outside_temperature -t xlsx echo "Inserting data to InfluxDB" sudo docker run --rm -v $PWD:/input telegraf --config /input/telegraf_file.conf --once echo "Generating aggregations" echo "Calculating aggregate statistics" ./aggregate_house_energy.sh echo "All done."
JavaScript
UTF-8
446
2.71875
3
[ "MIT" ]
permissive
window.onclick = function(event) { var modal = document.getElementById('modal-createsize'); if (event.target == modal) { modal.style.display = "none"; } } function create(){ $(document).click(function(){ $('#modal-createsize').css('display','block'); }); } function exit(){ $(document).click(function(){ $('#modal-createsize').css('display','none'); }); }
Java
UTF-8
3,458
2.984375
3
[]
no_license
package org.example; import ex41.nameSort; import ex42.Person; import ex42.parseData; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Optional; /* * UCF COP3330 Fall 2021 Assignment 3 Solution * Copyright 2021 ivan pavlov */ import static ex42.parseData.stringSort; import static java.lang.System.out; import static org.junit.Assert.assertEquals; public class parseTest { @Test @DisplayName("create array") void parse_test1() throws IOException { parseData tester = new parseData(); nameSort impor = new nameSort(); BufferedReader br = new BufferedReader(new FileReader("src/main/java/ex42/exercise42_input.txt")); String[] array = impor.storeString(br,8); String[] test = stringSort(array,7); Person[] testint = tester.createEmpArray(7,test); //counts number of lines in original file StringBuilder sb = new StringBuilder(); StringBuilder sb1 = new StringBuilder(); Optional<Person> p = Arrays.stream(testint).findFirst(); String sb1string = Arrays.stream(array).findFirst().toString(); String[] sb1Str = sb1string.split(","); sb.append(p.get().getFirst()); sb1.append(sb1Str[1]); // out.println(sb); // out.println(sb1); String actual = sb.toString(); String expected = sb1.toString(); assertEquals(expected,actual); } @Test @DisplayName("find longest")//since all find function work the same will not test each void parse_test2() throws IOException { parseData tester = new parseData(); nameSort impor = new nameSort(); BufferedReader br = new BufferedReader(new FileReader("src/main/java/ex42/exercise42_input.txt")); //i1 = num of lines-1,known String[] array = impor.storeString(br,8); String[] test = stringSort(array,7); Person[] testint = tester.createEmpArray(7,test); //person array int longestname = 0; longestname = tester.FindLongest(testint,7,1); // out.println(longestname); // out.println(); int actual = longestname; int expected = 8;//Geoffrey is the longest, known assertEquals(expected,actual); } @Test @DisplayName("createEmployee")//since all find function work the same will not test each void parse_test3() throws IOException { parseData tester = new parseData(); nameSort impor = new nameSort(); String p = "Pavlov,Ivan,40000"; Person ivan = parseData.createEmployee(p); String actual = ivan.getFirst(); String expected = "Ivan"; assertEquals(expected,actual); } @Test @DisplayName("sort test")//since all find function work the same will not test each void parse_test4() throws IOException { parseData tester = new parseData(); nameSort impor = new nameSort(); String[] testarr = {"acb","abc"}; String[] sorted = stringSort(testarr,1); String actual = Arrays.toString(sorted); String[] expect = {"abc","acb"}; String expected = Arrays.toString(expect); assertEquals(expected,actual); } }
PHP
UTF-8
3,927
2.765625
3
[]
no_license
<?php if (!DEBUG) die(); if (defined('IMPORT_MODELS') && IMPORT_MODELS) foreach (glob(ROOT_PATH . "/models/*.php") as $filename) include_once $filename; if (defined('AS_RAW_TEXT') && AS_RAW_TEXT) header("Content-Type: text/plain"); /* https://stackoverflow.com/questions/7153000/get-class-name-from-file */ function getClassFromFile($filename) { $fp = fopen($filename, 'r'); if (!$fp) return False; $class = $buffer = ''; $i = 0; while (!$class) { if (feof($fp)) return null; $buffer .= fread($fp, 512); if (preg_match('/class\s+(\w+)(.*)?\{/', $buffer, $matches)) { return $matches[1]; } } } /* https://gist.github.com/naholyr/1885879 */ function getNamespaceFromFile($filename) { $fp = fopen($filename, 'r'); if (!$fp) return False; $src = fread($fp, filesize($filename)); if (preg_match('#^namespace\s+(.+?);#sm', $src, $m)) { return $m[1]; } return null; } function getTableColumns($database, $table) { $statement = $database->prepare(" SELECT * from information_schema.columns WHERE TABLE_SCHEMA = :schema AND TABLE_NAME = :table "); $statement->execute([":schema" => DB_DATABASE, ":table" => $table]); if (!$statement) return False; return $statement->fetchAll(PDO::FETCH_ASSOC); } function out($txt="") { echo $txt . "\n"; } class DBModelTest { protected $namespace = "Model"; public function run($path) { $classname = getClassFromFile($path); $namespace = getNamespaceFromFile($path); if (is_null($classname)) return [False, 'No class declaration in the model file!']; if (is_null($namespace)) return [False, 'Namespace unspecified in the model file!']; if (!$classname || !$namespace) return [False, 'Unable to open the model file!']; if ($namespace !== $this->namespace) return [False, "Namespace must be '".$this->namespace."'!"]; if (!include($path)) return [False, 'Error during including the model file!']; $class = $namespace . "\\" . $classname; $model = new $class(); if (!is_subclass_of($model, "\\DBModel")) if (is_subclass_of($model, "\\Model")) return [True, "$classname isn't a database model - omitting"]; else return [False, "$classname isn't a \Model descendant!"]; $table = $model::getTableName(); $primary_key = $model::getPrimaryKey(); if (!$table) return [False, "$classname has unspecified table name!"]; if (!$primary_key) return [False, "$classname has unspecified primary key!"]; $db_class = new DBClass(); $db = $db_class->getConnection(); if (!$db) return [False, "Failure to establish database connection!"]; $columns = $model::getFields(); $db_columns = getTableColumns($db, $table); if (!$db_columns) return [False, "$classname - retrieving columns for table $table failed"]; $fully_correct = True; $message = ""; foreach ($db_columns as $column) { $column_name = $column["COLUMN_NAME"]; $column_key = $column["COLUMN_KEY"]; if (in_array($column_name, $columns)) { $columns = array_diff($columns, [$column_name]); // removes the column if ($column_key == "PRI" && $column_name != $primary_key) { $fully_correct = False; $message .= "\n[!] $classname - $column_name is set as the primary key in the database, but not in the model!"; } elseif ($column_key != "PRI" && $column_name == $primary_key) { $fully_correct = False; $message .= "\n[!] $classname - $column_name is set as the primary key in the model, but isn't one in the database!"; } } else { $fully_correct = False; $message .= "\n[!] $classname - $column_name not found in table $table!"; } } if ($fully_correct) $message = "OK. Every DB field found in model."; foreach ($columns as $column_name) { $fully_correct = False; $message .= "\n[*] $classname - extra public property found: \$$column_name"; } $message = trim($message); return [$fully_correct, $message]; } } ?>
Markdown
UTF-8
2,321
3.046875
3
[ "MIT" ]
permissive
# Material-UI confirm [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jonatanklosko/material-ui-confirm/blob/master/LICENSE) [![npm version](https://img.shields.io/npm/v/material-ui-confirm.svg)](https://www.npmjs.com/package/material-ui-confirm) [![Build Status](https://travis-ci.org/jonatanklosko/material-ui-confirm.svg?branch=master)](https://travis-ci.org/jonatanklosko/material-ui-confirm) [![Coverage Status](https://coveralls.io/repos/github/jonatanklosko/material-ui-confirm/badge.svg?branch=master)](https://coveralls.io/github/jonatanklosko/material-ui-confirm?branch=master) Higher order component for straightforward use of [@material-ui/core](https://material-ui.com/) confirmation dialogs. ## Installation ```sh npm install --save material-ui-confirm ``` ## Demo [![Edit material-ui-confirm demo](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/materialuiconfirm-demo-hzzdr?fontsize=14) ## Usage ```js import React from 'react'; import Button from '@material-ui/core/Button'; import withConfirm from 'material-ui-confirm'; const Item = ({ confirm }) => { const handleDelete = () => { /* ... */ }; return ( <Button onClick={confirm(handleDelete, { description: 'This action is permanent!' })}> Click </Button> ); }; export default withConfirm(Item); ``` ## API #### `withConfirm(Component)` Returns Component adding the `confirm` function to its props. #### `confirm(onConfirm, options)` Returns a function that opens the confirmation dialog once called. If the user confirms the action, the `onConfirm` callback is fired. ##### Options: | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | **`title`** | `string` | `'Are you sure?'` | Dialog title. | | **`description`** | `string` | `''` | Dialog content. | | **`confirmationText`** | `string` | `'Ok'` | Confirmation button caption. | | **`cancellationText`** | `string` | `'Cancel'` | Cancellation button caption. | | **`dialogProps`** | `object` | `{}` | Material-UI [Dialog](https://material-ui.com/api/dialog/#props) props. | | **`onClose`** | `function` | `() => {}` | Callback fired before the dialog closes. | | **`onCancel`** | `function` | `() => {}` | Callback fired when the user cancels the action. |
Python
UTF-8
598
4.5
4
[]
permissive
''' A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6. ''' # Python program to display all the prime numbers within an interval lower = 900 upper = 1000 print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): # all prime numbers are greater than 1 if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num)
C++
UTF-8
2,303
3.203125
3
[ "BSD-3-Clause" ]
permissive
#include <string> namespace TestNamespaceClasses { //! \brief first class inside of namespace class NamespacedClassTest { public: //! \brief namespaced class function virtual void function() const = 0; static void functionS(); explicit NamespacedClassTest() {} //! \brief namespaced class other function void anotherFunction() {} }; //! \brief second class inside of namespace class ClassTest { public: //! \brief second namespaced class function void function() {} //! \brief second namespaced class other function void anotherFunction() {} }; } // TestNamespaceClasses //! \brief class outside of namespace class OuterClass { public: //! \brief inner class class InnerClass {}; }; //! \brief class outside of namespace class ClassTest { public: /*! \brief non-namespaced class function More details in the header file. */ void function(int myParameter); //! \brief non-namespaced class other function void anotherFunction(); //! \brief namespaced class function virtual void publicFunction() const = 0; virtual void undocumentedPublicFunction() const = 0; //! A public class class PublicClass {}; class UndocumentedPublicClass {}; //! A public struct struct PublicStruct {}; struct UndocumentedPublicStruct {}; protected: //! A protected function void protectedFunction() {} void undocumentedProtectedFunction() {} //! A protected class class ProtectedClass {}; class UndocumentedProtectedClass {}; //! A protected struct struct ProtectedStruct {}; struct UndocumentedProtectedStruct {}; private: //! This is a private function virtual void privateFunction() const = 0; virtual void undocumentedPrivateFunction() const = 0; //! A private class class PrivateClass {}; class UndocumentedPrivateClass {}; //! A private struct struct PrivateStruct {}; struct UndocumentedPrivateStruct {}; }; template<typename T> void f0(); template<> void f0<std::string>(); namespace NS1 { template<typename T> void f1(); template<> void f1<std::string>(); namespace NS2 { template<typename T> void f2(); template<> void f2<std::string>(); } // namespace NS2 } // namespace NS1
Markdown
UTF-8
4,998
3.109375
3
[ "MIT" ]
permissive
# Running the KQ Scene Scoring server on a local computer If you want to run KQ Scene Scoring on your computer, or do development on it, follow the instructions in this section. Instructions for installing it on Heroku are provided later on. Clone the repo and set up gems and the initial database: ```sh $ git clone https://github.com/acidhelm/kq_scene_scoring_server.git $ cd kq_scene_scoring_server $ bundle install --path vendor/bundle $ bin/rails db:schema:load ``` If you don't want to set up a GitHub account, you can also [download the source code](https://github.com/acidhelm/kq_scene_scoring_server/archive/master.zip) and unzip it. There is one configuration key that you need to set, but you'll only have to do this once. In the `kq_scene_scoring_server` directory, run: ```sh $ ruby -e 'require "securerandom"; puts "ATTR_ENCRYPTED_KEY=#{SecureRandom.hex 16}"' > .env ``` That creates an encryption key that only works on your computer. You should not copy that key to any other computer; generate a new key if you start using KQ Scene Scoring on another computer. Then run the Rails server: ```sh $ bin/rails server ``` ## Create your KQ Scene Scoring account KQ Scene Scoring accounts are used to hold the list of tournaments that you are scoring and your Challonge API key. You can find your API key in [your account settings](https://challonge.com/settings/developer). There is no UI for creating accounts, but you can make an account in the Rails console. Run the console: ```sh $ bin/rails console ``` Then run this command to make an account: ```ruby > User.create user_name: "A user name", api_key: "Your API key", password: "A password" ``` The user name and password that you set here are used to log in to KQ Scene Scoring. They do not have to be the same as your Challonge user name and password. # Running KQ Scene Scoring on Heroku KQ Scene Scoring is ready to deploy to a Heroku app, so that tournament scores can be viewed by anyone. These instructions assume that you have created accounts on Heroku and GitHub. KQ Scene Scoring doesn't require any paid components, so you can use a free Heroku account. ## Deploying to Heroku using the command line To use command-line tools, you must install the [Heroku CLI app](https://devcenter.heroku.com/articles/heroku-cli). After you clone the repo, run: ```sh $ heroku create <heroku app name> ``` For example, run this command: ```sh $ heroku create my-kq-scene-scoring ``` to create <tt>my-kq-scene-scoring.herokuapp.com</tt>. `heroku create` also creates a git remote with the default name of "heroku". Then, push the app to that remote: ```sh $ git push heroku master ``` You'll see a bunch of output as the app is compiled and installed. Next, create the environment variable `ATTR_ENCRYPTED_KEY`. Instead of creating an `.env` file, you add the variable to your Heroku app's configuration: ```sh $ key=`ruby -e 'require "securerandom"; puts SecureRandom.hex(16)'` $ heroku config:set ATTR_ENCRYPTED_KEY=$key ``` Next, set up the database: ```sh $ heroku run rails db:migrate ``` Run the Rails console: ```sh $ heroku console ``` and create a KQ Scene Scoring account as described earlier. You can then access KQ Scene Scoring at https://your-app-name.herokuapp.com. ## Deploying to Heroku using a Web browser On GitHub, fork the KQ Scene Scoring repo to make a copy of it in your GitHub account. On your Heroku dashboard, click _New_&rarr;_Create new app_, and give it a name. Click that app in the dashboard, then click _Deploy_. In the _Deployment method_ section, click _GitHub_, then _Connect to GitHub_. That will show a popup window from GitHub asking you to allow Heroku to access your GitHub account. Click the _Authorize_ button. The _Connect to GitHub_ page will now show your GitHub account and a search field. Enter the name of your forked repo and click _Search_. Click _Connect_ next to your repo in the search results. The page will have a new _Manual deploy_ section at the bottom. Click _Deploy branch_ to deploy the <tt>master</tt> branch to your Heroku app. Once the deployment is done, the page will say "Your app was successfully deployed." <tt>\o/</tt> Click _Settings_, then in the top-right corner, click _More_&rarr;_Run console_. Type "bash", then click _Run_. Run the Ruby command to generate an encryption key as described earlier, and copy the key. Close the console. Click _Reveal config vars_ and create an <tt>ATTR_ENCRYPTED_KEY</tt> variable. Use the encryption key that you just created as the value for that variable. Create <tt>SLACK_TOKEN</tt> too if you want to send Slack notifications. Click _More_&rarr;_Run console_ again, and enter "rails db:migrate". When that finishes, click _Run another command_ at the bottom of the window, and enter "console". Create a KQ Scene Scoring account as described earlier. You can then access KQ Scene Scoring at https://your-app-name.herokuapp.com.
Java
UTF-8
1,685
2.625
3
[]
no_license
package org.openchat.domain.users; import java.util.List; public class UserService { private final IdGenerator idGenerator; private final UserRepository userRepository; public UserService(IdGenerator idGenerator, UserRepository userRepository) { this.idGenerator = idGenerator; this.userRepository = userRepository; } public User createUser(RegistrationData registrationData) throws UsernameAlreadyInUseException { validateUsername(registrationData.username()); User user = createUserFrom(registrationData); userRepository.add(user); return user; } public List<User> allUsers() { return userRepository.all(); } public void addFollowing(Following following) throws FollowingAlreadyExistsException{ if (userRepository.hasFollowing(following)) { throw new FollowingAlreadyExistsException(); } userRepository.add(following); } public List<User> followeesFor(String followerId) { return userRepository.followeesBy(followerId); } private void validateUsername(String username) throws UsernameAlreadyInUseException { if (userRepository.isUsernameTaken(username)) { throw new UsernameAlreadyInUseException(); } } private User createUserFrom(RegistrationData registrationData) { String userId = idGenerator.next(); return new User(userId, registrationData.username(), registrationData.password(), registrationData.about(), registrationData.homePage()); } }
TypeScript
UTF-8
726
3.09375
3
[]
no_license
import { Person } from './Person'; import { Gender } from './Gender'; import { isAllLetter, isAllNumber, isAlphaNumeric } from './Utils'; export class Student extends Person { private studentID: string; constructor(firstName: string, lastName: string, gender: Gender, username: string, password: string, studentID: string) { super(firstName, lastName, gender, username, password); this.studentID = studentID; } getStudentID(): string { return this.studentID; } setStudentID(studentID: string): boolean { if (isAllNumber(studentID) && studentID.length === 9) { this.studentID = studentID; return true; } return false; } }
Java
UTF-8
2,908
1.882813
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.09.18 at 11:48:27 AM IST // package com.iexceed.esoko.jaxb.ns; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for createSMSCodesReq complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="createSMSCodesReq"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Header" type="{http://www.iexceed.com/Header}Header"/> * &lt;element name="CRSMSCDDTLS" type="{http://www.iexceed.com/createSMSCodes}CRSMSCDDTLS" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "createSMSCodesReq", propOrder = { "header", "crsmscddtls" }) public class CreateSMSCodesReq { @XmlElement(name = "Header", required = true) protected Header header; @XmlElement(name = "CRSMSCDDTLS", required = true) protected List<CRSMSCDDTLS> crsmscddtls; /** * Gets the value of the header property. * * @return * possible object is * {@link Header } * */ public Header getHeader() { return header; } /** * Sets the value of the header property. * * @param value * allowed object is * {@link Header } * */ public void setHeader(Header value) { this.header = value; } /** * Gets the value of the crsmscddtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the crsmscddtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCRSMSCDDTLS().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CRSMSCDDTLS } * * */ public List<CRSMSCDDTLS> getCRSMSCDDTLS() { if (crsmscddtls == null) { crsmscddtls = new ArrayList<CRSMSCDDTLS>(); } return this.crsmscddtls; } }
Python
UTF-8
8,039
2.84375
3
[ "MIT" ]
permissive
#coding=utf-8 #代码中包含中文,就需要在头部指定编码。 from sklearn import datasets #from keras.datasets import boston_housing from keras import models from keras import layers from keras.models import Sequential from keras.layers import Dense,BatchNormalization,Dropout,Reshape,Flatten from keras.layers.convolutional import Conv2D,MaxPooling2D,Conv1D,MaxPooling1D import numpy as np import matplotlib.pyplot as plt from matplotlib import pyplot from sklearn.model_selection import train_test_split import os #1.导入数据集 print("1.导入数据集") diabetes = datasets.load_diabetes() train_data = diabetes.data # 获得其特征向量 train_targets = diabetes.target # 获得样本label #这是一个糖尿病的数据集,主要包括442行数据,10个属性值,分别是:Age(年龄)、性别(Sex)、Body mass index(体质指数)、 #Average Blood Pressure(平均血压)、S1~S6一年后疾病级数指标。Target为一年后患疾病的定量指标。 print(train_data.shape) print(train_targets.shape) print(train_data[:1]) print(train_targets[:1]) #2.将数据集划分为 训练集和测试集 # test_size:  float-获得多大比重的测试样本 (默认:0.25)  int - 获得多少个测试样本 # random_state:  int - 随机种子(种子固定,实验可复现) #shuffle - 是否在分割之前对数据进行洗牌(默认True) print("\n2.将数据集划分为 训练集和测试集") train_data, test_data, train_targets, test_targets = train_test_split(train_data, train_targets, test_size=0.3, random_state=42) print(train_data.shape) print(train_targets.shape) print(train_data[:1]) print(train_targets[:1]) #3.建立模型 print("\n3.建立模型") def build0(): model=Sequential(name='diabetes') model.add(BatchNormalization(input_shape=(10,))) model.add(Dropout(0.5)) model.add(Dense(1)) return model def build1(): model=Sequential(name='diabetes') model.add(BatchNormalization(input_shape=(10,))) model.add(Dense(10)) model.add(Dropout(0.5)) model.add(Dense(1)) return model def build2(): model=Sequential(name='diabetes') model.add(BatchNormalization(input_shape=(10,))) model.add(Dense(10,activation='tanh')) model.add(Dropout(0.5)) model.add(Dense(1)) return model def build3(): model=Sequential(name='diabetes') model.add(BatchNormalization(input_shape=(10,))) model.add(Dense(10,activation='sigmoid')) model.add(Dropout(0.5)) model.add(Dense(1)) return model def build4(): model=Sequential(name='diabetes') model.add(BatchNormalization(input_shape=(10,))) model.add(Reshape((10,1))) model.add(Conv1D(filters=10,strides=1,padding='same',kernel_size=2,activation='sigmoid')) model.add(Conv1D(filters=20, strides=1, padding='same', kernel_size=2, activation='sigmoid')) model.add(MaxPooling1D(pool_size=2,strides=1,padding='same')) model.add(Conv1D(filters=40, strides=1, padding='same', kernel_size=2, activation='sigmoid')) model.add(Conv1D(filters=80, strides=1, padding='same', kernel_size=2, activation='sigmoid')) model.add(MaxPooling1D(pool_size=2, strides=1, padding='same')) model.add(Flatten()) model.add(Dropout(0.5)) model.add(Dense(1)) return model def build5(): model = Sequential(name='diabetes') model.add(BatchNormalization(input_shape=(10,))) model.add(Reshape((10,1))) model.add(Conv2D(filters=10, strides=1, padding='same', kernel_size=1, activation='sigmoid')) model.add(Conv2D(filters=20, strides=2, padding='same', kernel_size=2, activation='sigmoid')) model.add(MaxPooling2D(pool_size=2, strides=1, padding='same')) model.add(Conv2D(filters=40, strides=1, padding='same', kernel_size=1, activation='sigmoid')) model.add(Conv2D(filters=80, strides=2, padding='same', kernel_size=2, activation='sigmoid')) model.add(MaxPooling2D(pool_size=2, strides=1, padding='same')) model.add(Flatten()) model.add(Dropout(0.5)) model.add(Dense(1)) return model #3.训练模型 print("\n3.训练模型") for i in range(4,5): print(("build and train diabetes"+str(i)+" model...")) model=eval("build"+str(i)+"()") #均方误差(mean-square error, MSE)是反映估计量与被估计量之间差异程度的一种度量。 #监测的指标为mean absolute error(MAE)平均绝对误差---两个结果之间差的绝对值。 #model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])adam model.compile('adam','mae') history=model.fit(train_data,train_targets,batch_size=16,epochs=80,verbose=0,validation_data=(test_data,test_targets)) #print(len(history.history)) #print(history.history) #print(history.history['loss']) #print(history.history['acc']) # plot train and validation loss pyplot.plot(history.history['loss']) pyplot.title("model train vs validation loss - build"+str(i)+"()") #pyplot.title('model train vs validation loss') pyplot.xlabel('epoch') pyplot.ylabel('loss') pyplot.legend(['train','validation'],loc='upper right') pyplot.show() ''' f=open("result.txt",'a') f.write(str(history.history['val_loss'][-1])+"\n") f.close() ''' #查看第一列年龄的数据 #print(diabetes.data[1]) ''' def build_model(): model = models.Sequential() model.add(layers.Dense(64, activation='relu',input_shape=(train_data.shape[1],))) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1)) #均方误差(mean-square error, MSE)是反映估计量与被估计量之间差异程度的一种度量。 #监测的指标为mean absolute error(MAE)平均绝对误差---两个结果之间差的绝对值。 model.compile(optimizer='rmsprop', loss='mse', metrics=['mae']) return model (train_data,train_targets),(test_data,test_targets) = boston_housing.load_data() mean = train_data.mean(axis=0) print(mean) train_data -= mean # 减去均值 std = train_data.std(axis=0) # 特征标准差 print(std) train_data /= std #print(train_data) test_data -= mean #测试集处理:使用训练集的均值和标准差;不用重新计算 test_data /= std #print(test_data) print(train_data.shape) print(test_data.shape) print("\n") print(train_data[10:11]) print(train_targets[10:11]) print("\n") print("train_targets.mean:") print(train_targets.mean(axis=0)) ''' ''' 因为数据各个特征取值范围各不相同,不能直接送到神经网络模型中进行处理。 尽管网络模型能适应数据的多样性,但是相应的学习过程变得非常困难。 一种常见的数据处理方法是特征归一化normalization---减均值除以标准差;数据0中心化,方差为1. ''' ''' k = 4 num_val_samples = len(train_data) // k num_epochs = 100 all_scores = [] for i in range(k): print('processing fold #',i) val_data = train_data[i*num_val_samples : (i+1)*num_val_samples] # 划分出验证集部分 val_targets = train_targets[i*num_val_samples : (i+1)*num_val_samples] partial_train_data = np.concatenate([train_data[:i*num_val_samples],train_data[(i+1)* num_val_samples:] ],axis=0) # 将训练集拼接到一起 partial_train_targets = np.concatenate([train_targets[:i*num_val_samples],train_targets[(i+1)* num_val_samples:] ],axis=0) model = build_model() model.fit(partial_train_data,partial_train_targets,epochs=num_epochs,batch_size=16,verbose=0)#模型训练silent模型 val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0) # 验证集上评估 all_scores.append(val_mae) #模型训练 model = build_model() model.fit(train_data, train_targets,epochs=80, batch_size=16, verbose=0) test_mse_score, test_mae_score = model.evaluate(test_data, test_targets)# score 2.5532484335057877 print("test_mse_score") print(test_mse_score) print("test_mae_score") print(test_mae_score) classes=model.predict(test_data[10:11],batch_size=128) print(classes) print(test_targets[10:11]) '''
Python
UTF-8
587
4.4375
4
[]
no_license
""" Write a method retrieve_values that takes in two dictionaries and a key. The method should return an array containing the values from the two hashes that correspond with the given key. """ def retrieve_values(hash1, hash2, key): list1 = [] if key in hash1 and hash2: list1.append(hash1[key]) list1.append(hash2[key]) return list1 dog1 = {"name": "Fido", "color": "brown"} dog2 = {"name": "Spot", "color": "white"} print(retrieve_values(dog1, dog2, "name")) # => ["Fido", "Spot"] print(retrieve_values(dog1, dog2, "color")) # => ["brown", "white"]
Python
UTF-8
2,071
3.8125
4
[]
no_license
import math import random # Python Sample : Assignment # Version : Python 2.x ''' This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' print 'Python Assignment' print # Numbers a = 2 b = 3 c = a + b print 'c = ', c d = 10 e = 3.0 f = d / e print 'f = ', f # Bitwise operation g = 1 h = g << 2 print 'h = ', h # Complex Numbers k = 1 + 2j l = 5 + 10j m = k + l print 'm = ', m # Hex numbers o = 0x0f p = 0xef q = o + p print 'q = ', q # Maths functions (need import math) r = math.sin(100) + math.pi s = abs(-100) t = math.sqrt(4) u = int(12.345) v = round(10.123) w = round(10.123, 2) print 'r = ', r print 's = ', s print 't = ', t print 'u = ', u print 'v = ', v print 'w = ', w # random number (need import random) x = random.random() y = random.randint(1, 1000) print 'x = ', x print 'y = ', y # String z = 'This is a string.' strlen = len(z) print 'strlen = ', strlen # String concatenation s1 = 'abc' s2 = 'def' s3 = s1 + s2 print 's3 = ', s3 print '-'*40 # Swap string s4 = 'Peter' print 'swap s4 = ', s4[::-1] # Strig conversion s5 = "123" n1 = int(s5) + 1 print "n1 = ", n1 # Character code s6 = 'a' print 'Character code of s6 = ', ord(s6) print 'Character of 97 = ', chr(97) # Formating string print "String formating %s, %d" % ("123", 456) # String functions s7 = "this is a test string." print "capitalize : ", s7.capitalize() print "center : ", s7.center(10) print "isdigit : ", s7.isdigit() print "substring = ", s7[5:7]
Java
UTF-8
829
3.890625
4
[]
no_license
import java.io.IOException; import java.util.Scanner; /* Leia 2 valores inteiros X e Y. A seguir, calcule e mostre a soma dos números impares entre eles. Entrada O arquivo de entrada contém dois valores inteiros. Saída O programa deve imprimir um valor inteiro. Este valor é a soma dos valores ímpares que estão entre os valores fornecidos na entrada que deverá caber em um inteiro. */ public class ex1071_soma_de_impares_consecutivos { public static void main(String[] args) { Scanner input = new Scanner(System.in); int i, X, Y, soma=0; X = input.nextInt(); Y = input.nextInt(); if (X < Y) { for (i=X+1; i<Y; i++) { if (i % 2 != 0) { soma+=i; } } } else { for (i=Y+1; i<X; i++) { if (i % 2 != 0) { soma+=i; } } } System.out.println(soma); } }
Python
UTF-8
853
3.171875
3
[]
no_license
hp_ryu = int(input()) hp_ken = int(input()) g_ryu = 0 g_ken = 0 while hp_ken > 0 and hp_ryu > 0: golpe = int(input()) if golpe > 0: hp_ken = hp_ken - golpe g_ryu += 1 print("RYU APLICOU UM GOLPE:", golpe) print("HP RYU =", hp_ryu) if hp_ken > 0: print("HP KEN =", hp_ken) else: print("HP KEN = 0") elif golpe < 0: hp_ryu = hp_ryu + golpe g_ken += 1 print("KEN APLICOU UM GOLPE:", abs(golpe)) if hp_ryu > 0: print("HP RYU =", hp_ryu) else: print("HP RYU = 0") print("HP KEN =", hp_ken) else: if hp_ken <= 0: print("LUTADOR VENCEDOR: RYU") print("GOLPES RYU =", g_ryu) print("GOLPES KEN =", g_ken) if hp_ryu <= 0: print("LUTADOR VENCEDOR: KEN") print("GOLPES RYU =", g_ryu) print("GOLPES KEN =", g_ken)
Java
UTF-8
216
1.796875
2
[]
no_license
package dao; import java.util.List; import dto.User; public interface HelloDao { public int insertinto(String userid,String password); public List<User> finduser(String userid,String password); }
Python
UTF-8
2,755
2.59375
3
[ "Apache-2.0" ]
permissive
from flask import session, request from flask_restful import Resource, reqparse, inputs, abort from api.common.database import database from api.common.utils import checkTag, checkTime, checkTel import json import requests ''' ### sendOfflineCapsule Use this method to send offline capsule. HTTP Request Method: **POST** | Field | Type | Required | Description | |---------------|---------|----------|----------------------------------------------------------------| | sender_name | String | Yes | Sender's name. | | sender_tel | String | Yes | Sender's telephone number. | | receiver_name | String | Yes | Receiver's name. | | receiver_tel | String | Yes | Receiver's telephone number. | | receiver_addr | String | Yes | Receiver's address. | | capsule_tag | String | Yes | The tag ID attached on the envelope. | | period | String | Yes | The period of time capsule. Must be `half-year` or `one-year`. | | seal | Boolean | Yes | Whether the seal is required. | ''' parser = reqparse.RequestParser() parser.add_argument('sender_name', type = str, required = True) parser.add_argument('sender_tel', type = str, required = True) parser.add_argument('receiver_name', type = str, required = True) parser.add_argument('receiver_tel', type = str, required = True) parser.add_argument('receiver_addr', type = str, required = True) parser.add_argument('capsule_tag', type = str, required = True) parser.add_argument('period', type = str, required = True, choices = ('half-year', 'one-year')) parser.add_argument('seal', type = inputs.boolean, required = True) class sendOfflineCapsule(Resource): def post(self): if checkTime() != 0: abort(416, message = "Event is not ongoing.") args = parser.parse_args() if not checkTel(args["sender_tel"]) or not checkTel(args["receiver_tel"]): abort(400, message = "Invalid telephone number.") if checkTag(args["capsule_tag"]) == False: abort(400, message = "Invalid capsule tag.") if not database.getTagStatus(args["capsule_tag"]): abort(409, message = "The capsule tag already exists.") database.addOfflineCapsule(args["sender_name"], args["sender_tel"], args["receiver_name"], args["receiver_tel"], args["receiver_addr"], args["capsule_tag"], args["period"], args["seal"]) return { "receiver_name": args["receiver_name"], "count": database.getStatisticsByTel(args["receiver_tel"]) }
Java
UTF-8
336
2.296875
2
[ "Apache-2.0" ]
permissive
package com.tvd12.test.testing.util; import org.testng.annotations.Test; import com.tvd12.test.base.BaseTest; import com.tvd12.test.util.Pair; public class PairTest extends BaseTest { @Test public void test() { Pair<String, String> pair = new Pair<>("1", "a"); assert pair.setValue("b").equals("a"); } }
Java
UTF-8
2,651
2.375
2
[]
no_license
package com.pmp.business; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import com.pmp.bean.CentroDeCustoBean; import com.pmp.bean.CompCodeBean; import com.pmp.bean.UsuarioBean; import com.pmp.entity.PmpCompCodePartner; import com.pmp.util.JpaUtil; public class CompCodeBusiness { private UsuarioBean usuarioBean; public CompCodeBusiness(UsuarioBean bean) { this.usuarioBean = bean; } public List<CompCodeBean> findAllCompCode(){ List<CompCodeBean> cc = new ArrayList<CompCodeBean>(); EntityManager manager = null; try { manager = JpaUtil.getInstance(); Query query = manager.createQuery("From PmpCompCodePartner"); List<PmpCompCodePartner> result = query.getResultList(); for (PmpCompCodePartner compcode : result) { CompCodeBean bean = new CompCodeBean(); bean.setId(Long.valueOf(compcode.getId())); bean.setDescricao(compcode.getDescricao()); cc.add(bean); } } catch (Exception e) { e.printStackTrace(); }finally{ if(manager != null && manager.isOpen()){ manager.close(); } } return cc; } public CompCodeBean saveOrUpdateCompCode(CompCodeBean bean){ EntityManager manager = null; try { manager = JpaUtil.getInstance(); manager.getTransaction().begin(); PmpCompCodePartner comp = null; if(bean.getId() == null || bean.getId() == 0){ comp = new PmpCompCodePartner(); bean.toBean(comp); manager.persist(comp); }else{ comp = manager.find(PmpCompCodePartner.class, bean.getId()); bean.toBean(comp); manager.merge(comp); } manager.getTransaction().commit(); bean.setId(comp.getId()); return bean; } catch (Exception e) { if(manager != null && manager.getTransaction().isActive()){ manager.getTransaction().rollback(); } e.printStackTrace(); }finally { if(manager != null && manager.isOpen()){ manager.close(); } } return null; } public Boolean removerCompCode(CompCodeBean bean){ EntityManager manager = null; try { manager = JpaUtil.getInstance(); manager.getTransaction().begin(); manager.remove(manager.find(PmpCompCodePartner.class, bean.getId())); manager.getTransaction().commit(); return true; } catch (Exception e) { if(manager != null && manager.getTransaction().isActive()){ manager.getTransaction().rollback(); } e.printStackTrace(); }finally { if(manager != null && manager.isOpen()){ manager.close(); } } return false; } }
Python
UTF-8
1,186
3.765625
4
[]
no_license
class Dog: role = 'dog' def __init__(self,name,breed,attack_val): self.name = name self.breed = breed self.attack_val = attack_val self.life_val = 100 def bite(self,person): person.life_val -= self.attack_val print('dog [%s] attack human [%s], human [%s] lose [%s] HP, remaining HP is [%s]...' % (self.name,person.name,person.name,self.attack_val,person.life_val)) class Person: role = 'person' def __init__(self,name,gender,attack_val): self.name = name self.gender = gender self.attack_val = attack_val self.life_val = 100 def attack(self,dog): dog.life_val -= self.attack_val print('human [%s] attack dog [%s], dog [%s] lose [%s] HP, remaining HP is [%s]...' % (self.name,dog.name,dog.name,self.attack_val,dog.life_val)) d1 = Dog('Mjj','jin mao',30) d2 = Dog('HH','er ha',40) p1 = Person('Synfer','M',50) p1.attack(d1) """return: human [Synfer] attack dog [Mjj], dog [Mjj] lose [50] HP, remaining HP is [50]...""" d1.bite(p1) """dog [Mjj] attack human [Synfer], human [Synfer] lose [30] HP, remaining HP is [70]..."""
Java
UTF-8
4,650
2.453125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.project.views; import com.company.project.model.Group; import com.mycompany.project.MyVaadinUI; import com.mycompany.project.business.BusinessLogic; import com.mycompany.project.components.GroupDetails; import com.mycompany.project.components.NewGroupForm; import com.vaadin.data.Property; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.BeanContainer; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.Table; import com.vaadin.ui.Table.RowHeaderMode; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import java.util.ArrayList; /** * * @author vikrant.thakur */ public class GroupsView extends Panel implements View { public static final String NAME = "Groups"; // used by navigator for switching private final NewGroupForm newGroupForm = new NewGroupForm(); private final Window window = new Window(); private final BeanContainer<String, Group> beanContainer = new BeanContainer<String, Group>(Group.class); private final Table table = new Table(); private final GroupDetails groupDetails = new GroupDetails(); public GroupsView() { VerticalLayout mainVLayout = new VerticalLayout(); mainVLayout.setMargin(true); mainVLayout.setSpacing(true); setContent(mainVLayout); // view header Label header = new Label("<div align=\"center\" style=\"font-size:12pt;\">Grupos</div>"); header.setContentMode(ContentMode.HTML); mainVLayout.addComponent(header); // set window properties window.setWidth("400px"); window.setCaption("New Group"); window.setModal(true); window.setContent(newGroupForm); // add new cotact button Button btnNew = new Button("Add New Group"); mainVLayout.addComponent(btnNew); // clicking the button should display the NewContactForm btnNew.addClickListener(new ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { if (window.getParent() == null) { getUI().addWindow(window); } } }); //add a horozontal layout - left has a table, right has a ContactDetail component HorizontalLayout hLayout = new HorizontalLayout(); hLayout.setSizeFull(); hLayout.setSpacing(true); mainVLayout.addComponent(hLayout); //add a table table.setWidth("600px"); table.setImmediate(true); hLayout.addComponent(table); // how does table get its data beanContainer.setBeanIdProperty("id"); table.setContainerDataSource(beanContainer); //set columns final Object[] NATURAL_COL_ORDER = new Object[]{"name"}; final String[] COL_HEADERS_ENGLISH = new String[]{"Name"}; table.setSelectable(true); table.setColumnCollapsingAllowed(true); table.setRowHeaderMode(RowHeaderMode.INDEX); table.setVisibleColumns(NATURAL_COL_ORDER); table.setColumnHeaders(COL_HEADERS_ENGLISH); // selecting a table row should enable/disale the ContactDetails component table.addValueChangeListener(new ValueChangeListener(){ @Override public void valueChange(Property.ValueChangeEvent event) { String groupId = (String)table.getValue(); groupDetails.setGroupId(groupId); } }); //add a ContactDetails component // contactDetails.setWidth("500px"); hLayout.addComponent(groupDetails); // let the table fill the entire remaining width hLayout.setExpandRatio(groupDetails, 1); } @Override public void enter(ViewChangeListener.ViewChangeEvent event) { load(); } public void load() { beanContainer.removeAllItems(); // get hold of the business logic BusinessLogic bl = ((MyVaadinUI) getUI()).getBusinessLogic(); ArrayList<Group> groups = bl.getAllGroups(); for (int i = 0; i < groups.size(); i++) { beanContainer.addAll(groups); } } }
Markdown
UTF-8
2,306
3.46875
3
[]
no_license
## Project Instructions :pencil2: **Review the Article to Mockup Project [Rubric](https://review.udacity.com/#!/rubrics/145/view)** 1. Download and unzip `mockup-to-article.zip` in the Supporting Materials section, below. You'll find `index.html`, the article mockup image (`blog-mockup.pdf`) and a file called `reflections.txt` inside. 2. Use what you've learned about web development so far to edit index.html so that it looks exactly like the mockup image. You will need to use new elements, which means that you'll need to research and experiment! (Hint: look up "superscript," "horizontal rule," and "strikethrough."). :point_right: Note: You can recreate the mockup without using a single \<br\> tag! You don't need to worry about line breaks. The text should naturally wrap depending on how wide the window is. 3. When you've finished building the article, open up `reflections.txt`. You've learned a lot about web development so far. I want you to take a moment to write down your thoughts about web development in `reflections.txt`. Answer the following questions: > _What new skills have you learned?_\ > _What has been easy?_\ > _What has been difficult?_\ > _How have you used the problem solving strategies from the first project to overcome challenges so far?_ ****** :point_right: [Project Specifications/Rubric](https://review.udacity.com/#!/rubrics/145/view) :point_right: [View Online](https://jtrfs.github.io/mockup-to-article/) *** ### :red_circle: My tweaks to the project: * I used not only HTML but also some internal CSS plus media query along with and jQuery. :exclamation: **To see the effect you must resize the viewport**. * I tried to follow the mockup precisely - its look/design. **some media query** ``` @media screen and (min-width: 1300px) { .tooltip1{ display: none; } .tooltip2 { display: inline-block} ``` **some jQuery** ``` <script> $(function() { $( document ).on( "mousemove", function( event ) { $( ".tooltip1" ).css({ "left" : event.pageX, "top" : event.pageY }); }); }); </script> ``` ******** ### To do list - [x] remember to try out the markdown (I tried to get the hang of the markdown in this README file) - [ ] keep coding ... :smirk:
JavaScript
UTF-8
1,068
2.6875
3
[]
no_license
(function () { "use strict"; angular .module("movie") .controller("MainController", MainController); MainController.$inject = ["movieService"]; function MainController(movieService) { var mainVm = this; mainVm.addMovie = addMovie; mainVm.deleteMovie = deleteMovie; init(); function init() { mainVm.title = "MovieFlix"; mainVm.sorter = { sortBy:"Title", sortOrder:false }; movieService.getMovies() .then(function (data) { mainVm.movies = data; }) .catch(function (error) { console.log(error); }) } function addMovie() { mainVm.movies.unshift(mainVm.newMovie); mainVm.newMovie = null; }; function deleteMovie(Title) { _.remove(mainVm.movies,function (movie) { return movie.Title === Title; }); } } })();
Java
UTF-8
25,247
2.90625
3
[]
no_license
import java.awt.event.ActionEvent; import java.util.*; import com.google.gson.Gson; import javafx.scene.control.TextArea; import java.time.Instant; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; enum RaceType { IND, PARIND, GRP, PARGRP } /** * The main class. This represents the inner workings of the Chronotimer. * * @author LLM * */ public class ChronoTimer implements Runnable { public Channel[] channels; public boolean powerOn = false; ArrayList<Race> raceList = new ArrayList<Race>(); Race currentRace; RaceType raceType; TextArea raceDisplay; public Queue<Command> cmdQueue; public ChronoTimer() { channels = new Channel[8]; cmdQueue = new LinkedList<Command>(); } /** * The entry point for the chronotimer when its thread begins. */ public void run() { // Create new channels for (int i = 0; i <= 7; i++) { channels[i] = new Channel(this); } Main.dbg.printDebug(1, "Welcome to Chronotimer. Use the GUI or type 'HELP' in the console."); /* * EVENT LOOP When the application starts, we start at Main which * creates and runs a Simulator thread, which creates a Chronotimer * thread. The chronotimer thread will go execute this while loop every * GRANULARITY miliseconds. */ while (true) { while (powerOn) { // Handles the scrolling on the gui if (raceDisplay != null && currentRace != null) { double scroll = raceDisplay.getScrollTop(); raceDisplay.setText(currentRace.toString()); // current race // output raceDisplay.setScrollTop(scroll); } // Goes through all pending commands until the queue is empty. while (cmdQueue.isEmpty() == false) { // Simulator runs the command cmdQueue.poll().execute(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(Main.GRANULAITY); } catch (InterruptedException e) { e.printStackTrace(); } } // Runs the commands in the command queue. while (cmdQueue.isEmpty() == false) { // Simulator runs the command cmdQueue.poll().execute(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Handles scoring by race type. */ public void score(ActionEvent e) { if (currentRace == null || currentRace.currentRaceType == null) { Main.dbg.printDebug(0, "[ERR] score was called while currentRace or its racetype is null."); return; } switch (currentRace.currentRaceType) { case IND: // if start is tripped if (e.getSource().equals(channels[0])) { try { Racer popped = currentRace.toRace.pollFirst(); popped.t.startTime(); currentRace.inRace.addLast(popped); } catch (NoSuchElementException err) { Main.dbg.printDebug(0, "[WARN] No racers are ready to start!"); } catch (NullPointerException ex) { Main.dbg.printDebug(0, "[WARN] Noone to start! Add more racers or start finishing."); } // if finish is tripped } else if (e.getSource().equals(channels[1])) { try { Racer popped = currentRace.inRace.pollFirst(); popped.t.stopTime(); currentRace.finishRace.add(popped); } catch (NoSuchElementException err) { Main.dbg.printDebug(0, "[WARN] No racers are ready to finish!"); } catch (NullPointerException err) { Main.dbg.printDebug(0, "[WARN] No racers are ready to finish!"); } } break; case PARIND: // if start is tripped if (e.getSource().equals(channels[0]) || e.getSource().equals(channels[2])) { try { Racer popped = currentRace.toRace.pollFirst(); popped.t.startTime(); currentRace.inRace.addLast(popped); } catch (NoSuchElementException err) { Main.dbg.printDebug(0, "[WARN] No racers are ready to start!"); } catch (NullPointerException ex) { Main.dbg.printDebug(0, "[WARN] Noone to start! Add more racers or start finishing."); } // if finish is tripped } else if (e.getSource().equals(channels[1]) || e.getSource().equals(channels[3])) { try { Racer popped = currentRace.inRace.pollFirst(); popped.t.stopTime(); currentRace.finishRace.add(popped); } catch (NoSuchElementException err) { Main.dbg.printDebug(0, "[ERR] No racers are ready to finish!"); } catch (NullPointerException err) { Main.dbg.printDebug(0, "[ERR] No racers are ready to finish!"); } } break; case GRP: if (e.getSource().equals(channels[0])) { // if start is tripped currentRace.startTime = Instant.now().toEpochMilli() + Time.currentMs; } else if (e.getSource().equals(channels[1])) { // if finish is tripped int i = 1; if (!(currentRace.finishRace.isEmpty())) { int s = currentRace.finishRace.size(); i = currentRace.finishRace.get(s - 1).bib + 1; } Racer r = new Racer(i); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } break; case PARGRP: if (currentRace.startTime == 0 && e.getSource().equals(channels[0])) { currentRace.startTime = Instant.now().toEpochMilli() + Time.currentMs; currentRace.inRace.addAll(currentRace.toRace); currentRace.toRace.removeAll(currentRace.inRace); } else { if (!(currentRace.inRace.isEmpty())) { if (e.getSource().equals(channels[0]) && channels[0].getState()) { Racer r = currentRace.removeBib(1); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } else if (e.getSource().equals(channels[1]) && channels[1].getState()) { Racer r = currentRace.removeBib(2); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } else if (e.getSource().equals(channels[2]) && channels[2].getState()) { Racer r = currentRace.removeBib(3); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } else if (e.getSource().equals(channels[3]) && channels[3].getState()) { Racer r = currentRace.removeBib(4); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } else if (e.getSource().equals(channels[4]) && channels[4].getState()) { Racer r = currentRace.removeBib(5); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } else if (e.getSource().equals(channels[5]) && channels[5].getState()) { Racer r = currentRace.removeBib(6); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } else if (e.getSource().equals(channels[6]) && channels[6].getState()) { Racer r = currentRace.removeBib(7); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } else if (e.getSource().equals(channels[7]) && channels[7].getState()) { Racer r = currentRace.removeBib(8); r.t.start = currentRace.startTime; r.finish(); currentRace.finishRace.add(r); } } } break; default: Main.dbg.printDebug(0, "[ERR] score called while racetype is invalid."); break; } } /** * A quick command to create a command. */ public Command toCommand(String cmd) { return new Command(cmd); } /** * A "command" object. * args[0] is the command itself (PRINT, NEWRUN, etc), while * args[1] and args[2] are the arguments. * The constructor takes a single string, which parses according to the format "COMMAND ARG1 ARG2" * * IMPORTANT: When a Command is constructed, the Command adds itself to the command queue. */ public class Command { String command = "", arg1 = "", arg2 = ""; // Takes string of format "COMMAND ARG1 ARG2" public Command(String cmd) { // If the power is off, don't process anything besides POWER commands. if (powerOn == false && cmd.equalsIgnoreCase("POWER") == false) { return; } Main.dbg.printDebug(3, "Command Constructor in: " + cmd); String[] args = cmd.split(" "); command = args[0]; if (args.length > 1) arg1 = args[1]; if (args.length > 2) arg2 = args[2]; Main.dbg.printDebug(3, "Command Constructor stored: " + Arrays.toString(cmd.split(" "))); Main.dbg.printDebug(0, Time.printTime() + "\t" + this.command + " " + arg1 + " " + arg2); // Every created command is added to the command queue. cmdQueue.add(this); } /** * Calling execute on a command will run the function associated with it. * For a description of the function, see the "HELP" function's output. * @return true if the command is a valid command, false otherwise. */ public boolean execute() { Main.dbg.printDebug(3, "EXECUTING " + command + " " + arg1 + " " + arg2); switch (command.toUpperCase()) { case "POWER": // Should toggle the power. powerOn = powerOn ? false : true; if (powerOn) Main.dbg.printDebug(1, "ChronoTimer switched on!"); else Main.dbg.printDebug(1, "ChronoTimer switched off!"); break; case "EXIT": // cleanup? System.exit(0); break; case "RESET": currentRace = null; Race.maxRaceNum = 1; raceList.clear(); raceDisplay.clear(); raceDisplay.setText("ChronoTimer powered on\nSelect a race type and hit New Run"); Main.dbg.printDebug(1, "ChronoTimer reset!"); powerOn = false; try { Thread.sleep(1100); } // Stops just long enough for Chronotimer to loop catch (InterruptedException e) { e.printStackTrace(); } powerOn = true; break; case "TIME": Main.dbg.printDebug(3, "INPUT TO TIME COMMAND: " + arg1); int hour, min; double sec; String[] input = arg1.split(":"); try { if (input.length != 3) { System.out.println("Inproper formatting! Proper Usage is HOUR:MIN:SEC, ie 3:00:00.1"); break; } if (input.length == 2) { min = Integer.valueOf(input[0]); sec = Double.valueOf(input[1]); Time.setTime(0, min, sec); Main.dbg.printDebug(3, "MIN: " + min + " SEC: " + sec); } else if (input.length == 3) { hour = Integer.valueOf(input[0]); min = Integer.valueOf(input[1]); sec = Double.valueOf(input[2]); Main.dbg.printDebug(3, "HOUR: " + hour + " MIN: " + min + " SEC: " + sec); Time.setTime(hour, min, sec); } else { System.out.println("Inproper formatting! Proper Usage is HOUR:MIN:SEC, ie 3:00:00.1"); } } catch (NumberFormatException e) { System.out.println("Inproper formatting! Proper Usage is HOUR:MIN:SEC, ie 3:00:00.1"); break; } break; case "TOG": // command arg1 arg2 int c = Integer.parseInt(arg1); // Handles channels as starting at 1 vs. arrays starting at 0. if (channels[c - 1] != null) { channels[c - 1].toggle(); String state = channels[c - 1].getState() ? "on" : "off"; if (currentRace.currentRaceType == RaceType.PARGRP && channels[c - 1].getState()) { currentRace.toRace.add(new Racer(c)); } Main.dbg.printDebug(1, "Channel " + Integer.toString(c) + " is now toggled " + state); } else { Main.dbg.printDebug(0, "You need to initialize channnels"); } break; // arg1 is sensortype, arg2 is number of sensor case "CONN": int sensorNum = Integer.parseInt(arg2); Sensor s; if (arg1.equals("GateSensor")) { s = new PadSensor(channels[sensorNum - 1]); } else if (arg1.equalsIgnoreCase("EyeSensor")) { s = new EyeSensor(channels[sensorNum - 1]); } else if (arg1.equalsIgnoreCase("PadSensor")) { s = new PadSensor(channels[sensorNum - 1]); } else { Main.dbg.printDebug(0, "[ERR] Invalid sensor type."); break; } channels[sensorNum - 1].setSensor(s); Main.dbg.printDebug(3, arg1 + " " + sensorNum + " connected."); break; // arg1 is sensor number case "DISC": int sensorNumm = Integer.parseInt(arg1); channels[sensorNumm - 1].s.disconnect(); Main.dbg.printDebug(3, "Sensor " + sensorNumm + " disconnected."); break; case "EVENT": if (arg1 == null || arg1 == "") { Main.dbg.printDebug(0, "[ERR] Please specify a race type. See 'HELP'."); break; } switch (arg1.toUpperCase()) { case "IND": raceType = RaceType.IND; Main.dbg.printDebug(1, "Event set to IND"); channels[0] = new Channel(ChronoTimer.this); channels[1] = new Channel(ChronoTimer.this); if (currentRace != null) { currentRace.currentRaceType = RaceType.IND; } break; case "PARIND": raceType = RaceType.PARIND; Main.dbg.printDebug(1, "Event set to PARIND"); for (int i = 0; i < 4; i++) channels[i] = new Channel(ChronoTimer.this); if (currentRace != null) { currentRace.currentRaceType = RaceType.PARIND; } break; case "GRP": raceType = RaceType.GRP; Main.dbg.printDebug(1, "Event set to GRP"); channels[0] = new Channel(ChronoTimer.this); channels[1] = new Channel(ChronoTimer.this); if (currentRace != null) { currentRace.currentRaceType = RaceType.GRP; } break; case "PARGRP": raceType = RaceType.PARGRP; Main.dbg.printDebug(1, "Event set to PARGRP"); for (int i = 0; i < 8; i++) channels[i] = new Channel(ChronoTimer.this); if (currentRace != null) { currentRace.currentRaceType = RaceType.PARGRP; } break; default: Main.dbg.printDebug(0, "[ERR] Unsupported race type '" + arg1 + "'. Use the HELP command."); break; } break; case "NEWRUN": DirectoryServer.md.clear(); if (raceType == null) { Main.dbg.printDebug(0, "[WARN] No racetype selected. Use EVENT or HELP for more info."); break; } else if (currentRace != null && currentRace.raceEnded == false) { Main.dbg.printDebug(0, "Race is not ended. Use ENDRUN to end the race."); break; } else if (currentRace != null) { raceList.add(currentRace); // Saves the current race into an array. } if (raceType == RaceType.IND) { currentRace = new Race(raceType); Main.dbg.printDebug(1, "New IND race created: " + currentRace.hashCode() + ", race #" + currentRace.raceNum); } else if (raceType == RaceType.PARIND) { currentRace = new Race(raceType); Main.dbg.printDebug(1, "New PARIND race created"); } else if (raceType == RaceType.GRP) { currentRace = new Race(raceType); Main.dbg.printDebug(1, "New GRP race created"); } else if (raceType == RaceType.PARGRP) { currentRace = new Race(raceType); Main.dbg.printDebug(1, "NEW PARGRP race created"); } break; case "ENDRUN": DirectoryServer.md.clear(); if (currentRace == null) { Main.dbg.printDebug(0, "[ERR] no race to end."); break; } currentRace.raceEnded = true; if (raceType == RaceType.GRP || raceType == RaceType.PARGRP) currentRace.finishTime = Instant.now().toEpochMilli() + Time.currentMs; // This is what will be displayed in the webserver as the time. for (Racer r : currentRace.finishRace) { r.prettyTime = Time.convert(r.t.runTime()); } if (raceType == RaceType.GRP) currentRace.finishTime = Instant.now().toEpochMilli() + Time.currentMs; Main.dbg.printDebug(1, String.format("Race %d was set to finished.", currentRace.raceNum)); Gson gson = new Gson(); String json = gson.toJson(currentRace.finishRace); // Client will connect to this location URL site; try { site = new URL("http://localhost:8000/sendresults"); HttpURLConnection conn = (HttpURLConnection) site.openConnection(); // now create a POST request conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(json); out.flush(); out.close(); InputStreamReader inputStr = new InputStreamReader(conn.getInputStream()); // string to hold the result of reading in the response StringBuilder sb = new StringBuilder(); // read the characters from the request byte by byte and build up // the Response int nextChar; while ((nextChar = inputStr.read()) > -1) { sb = sb.append((char) nextChar); } Main.dbg.printDebug(3, "JSON Return String: " + sb); Main.dbg.printDebug(0, "Results Sent to Server"); } catch (Exception ex){ //Main.dbg.printDebug(0, "[ERR] HTTP/JSON Problems. Is the server connected?"); //ex.printStackTrace(); } break; case "PRINT": try { if (currentRace.finishRace.isEmpty()) { Main.dbg.printDebug(0, "[WARN] No racers found in finishing queue."); } else { for (Racer r : currentRace.finishRace) { long time = r.t.runTime(); if (time == Long.MAX_VALUE) { Main.dbg.printDebug(0, "Racer " + r.bib + " DNF"); } else { Main.dbg.printDebug(0, "Racer " + r.bib + " " + (r.t.runTime()) / 1000.0 + " seconds"); } } } } catch (NullPointerException ex) { Main.dbg.printDebug(0, "[WARN] Could not print. Did you initialize the race or racers?"); } break; case "NUM": boolean duplicate = false; try { if (arg1 == null || arg1.equals("")) { Main.dbg.printDebug(0, "[ERR] Please enter a bib number."); break; } if (currentRace == null || currentRace.currentRaceType == null) { Main.dbg.printDebug(0, "[ERR] No race type selected. Define events with 'EVENT' first, or see 'HELP'"); } else if (currentRace.currentRaceType == RaceType.IND || currentRace.currentRaceType == RaceType.PARIND) { int bib = Integer.parseInt(arg1); try { for (Racer r : currentRace.toRace) { if (r.bib == bib) { Main.dbg.printDebug(0, "[ERR] A racer already has bib " + bib + "."); duplicate = true; break; } } if (duplicate) break; currentRace.toRace.add(new Racer(bib)); Main.dbg.printDebug(1, "Racer " + bib + " added"); } catch (Exception ex) { Main.dbg.printDebug(0, "[ERR] Not a valid number, or race was incorrectly created."); } } else if (currentRace.currentRaceType == RaceType.GRP || currentRace.currentRaceType == RaceType.PARGRP) { if (currentRace.raceEnded == false) { Main.dbg.printDebug(0, "[ERR] End run before numbering contestants. in GRP races."); } else { currentRace.giveBib(Integer.parseInt(arg1)); } } } catch (NumberFormatException e) { Main.dbg.printDebug(0, "[ERR] Please enter a valid bib number."); } break; case "CLR": try { if (currentRace != null) { if (currentRace.removeBib(Integer.parseInt(arg1)) != null) { Main.dbg.printDebug(3, "Racer removed."); } else { Main.dbg.printDebug(0, "[WARN] No racer removed. Could not find racer."); } } } catch (NumberFormatException e) { Main.dbg.printDebug(0, "[ERR] Please enter a valid bib number."); } break; case "SWAP": // Only functions during IND & PARIND races (according to spec) if (currentRace == null) { Main.dbg.printDebug(0, "[ERR] Cannot SWAP when there's no race!"); break; } if ((currentRace.currentRaceType == RaceType.IND || currentRace.currentRaceType == RaceType.PARIND) && currentRace.inRace.size() >=1) { ArrayList<Racer> list = new ArrayList<Racer>(currentRace.inRace); Collections.swap(list, 0, 1); Deque<Racer> newQ = new ArrayDeque<Racer>(); for (Racer r : list) { newQ.addLast(r); } currentRace.inRace = newQ; } else { Main.dbg.printDebug(0, "[ERR] Only works during IND or PARIND races."); } break; case "DNF": if (currentRace == null || currentRace.currentRaceType == null) { Main.dbg.printDebug(0, "[ERR] Cannot DNF when there's no race or race type!!"); break; } if (currentRace.currentRaceType != RaceType.GRP || currentRace.currentRaceType != RaceType.PARGRP) { if (!(currentRace.inRace.isEmpty() || currentRace.inRace == null)) { Racer r = currentRace.inRace.pollFirst(); r.runTime = Long.MAX_VALUE; r.dnf = true; currentRace.finishRace.add(r); } } break; case "CANCEL": if (currentRace == null) { Main.dbg.printDebug(0, "[ERR] Cannot CANCEL when there's no race!"); break; } if (currentRace.currentRaceType != RaceType.GRP && currentRace.currentRaceType != RaceType.PARGRP){ Racer r = currentRace.inRace.pollLast(); r.t.start = 0; currentRace.toRace.push(r); } break; case "TRIG": // Find the sensor object associated with arg1 // Send a trigger command to it try { int chan = Integer.parseInt(arg1); channels[(chan - 1)].trigger(); Main.dbg.printDebug(2, "Channel " + (chan) + " tripped!"); } catch (NumberFormatException e) { Main.dbg.printDebug(0, "[ERR] Please enter a valid number."); } break; case "START": if (currentRace.currentRaceType == RaceType.IND) { channels[0].trigger(); } else if (currentRace.currentRaceType == RaceType.PARIND) { if (channels[0] != null && channels[0].getState()) channels[0].trigger(); if (channels[2] != null && channels[2].getState()) channels[2].trigger(); } break; case "FINISH": if (currentRace.currentRaceType == RaceType.IND || currentRace.currentRaceType == RaceType.GRP) { channels[1].trigger(); } else if (currentRace.currentRaceType == RaceType.PARIND) { if (channels[1] != null && channels[1].getState()) channels[1].trigger(); if (channels[3] != null && channels[3].getState()) channels[3].trigger(); } break; case "DEBUG": Main.MAX_VERBOSITY = Integer.parseInt(arg1); for (int i = 0; i <= 3; i++) Main.dbg.printDebug(i, "MAX_VERBOSITY CHANGED -- Debug level [" + i + "] messages active"); break; case "LIST": if (currentRace != null) { Main.dbg.printDebug(0, currentRace.toString()); } else { // handles null pointer exception Main.dbg.printDebug(0, "Race hasn't started yet."); } break; case "SERVER": Main.dbg.printDebug(0, "Server now on!"); DirectoryServer ds = new DirectoryServer(); ds.run(); break; case "HELP": System.out.println(">>> COMMANDS:\n" + "POWER Turn on and enter idle state or turn system off but stay in simulator\n" + "EXIT Exit the simulaton\n" + "RESET Resets the System to initial state\n" + "TIME Set the current time FORMAT: <hour>:<min>:<sec>\n" + "TOG toggle state of channel FORMAT: <channel>\n" + "CONN connect a type of sensor to channel <num> FORMAT: <sensor> <num>\n" + "DISC disconnect sensor from channel <num> FORMAT: <num>\n" + "EVENT type of event (IND, PARIND, GRP, PARGRP) FORMAT: <eventcode>\n" + "NEWRUN creates a new run\n" + "ENDRUN done with a run\n" + "PRINT Prints the run on stdout\n" + "NUM Set <num> as the next competitor to start FORMAT: <num>\n" + "LR Clear competitor number <num> FORMAT: <num>\n" + "SWAP Exchange next to compentitors to finish in IND\n" + "DNF Next competitor to finish will not finish\n" + "TRIG Trigger channel <num> FORMAT: <num>\n" + "CONN Attaches channel <num> to a style of sensor <sensortype> FORMAT: <sensortype> <num>\n" + "DISC Disconnects sensor <num> connected with CONN. FORMAT: <num>\n" + "START Start trigger channel 1 -- macro for TRIG 1\n" + "FINISH Finish trigger channel 2 -- macro for TRIG 2\n" + "DEBUG Change the debug output's verbosity. FORMAT: <0...3>\n" + "LIST Show the current race, their queues, and racers.\n" + "SERVER Start the server.\n" + "CANCEL A competitor started but their start is invalid. Send them back to start queue"); break; default: Main.dbg.printDebug(0, "UNSUPPORTED COMMAND: " + this); return false; } return true; } } }
Java
UTF-8
346
1.914063
2
[]
no_license
package com.ninvit.framework.repository; import java.util.Optional; import com.ninvit.framework.models.BlogPost; import org.springframework.data.jpa.repository.JpaRepository; public interface BlogPostRepository extends JpaRepository<BlogPost, Long> { void deleteBlogPostById(Long id); Optional<BlogPost> findBlogPostById(Long id); }