language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
2,988
2.6875
3
[]
no_license
import React, { Component } from 'react'; import Header from '../header'; import SearchPanel from '../search-panel'; import TodoList from '../todo-list'; import AddItemPanel from '../add-item-panel'; import './App.css'; export default class App extends Component { state = { filter: '', text: '', todos: [ { action: 'Learn ReactJS', important: false, done: false }, { action: 'Drink coffee', important: false, done: false }, { action: 'Read a Book', important: false, done: false }, { action: 'Make Todo App', important: true, done: false }, ], }; onDelete = (action) => { const { todos } = this.state; this.setState({ todos: todos.filter((todo) => { return todo.action !== action; }), }); }; handleSubmit = (todo) => { this.setState({ todos: [...this.state.todos, todo] }); }; toggleProperty = (action, property) => { return this.state.todos.map((todo) => todo.action === action ? { ...todo, [property]: !todo[property] } : todo ); }; onToggleDone = (action) => { this.setState({ todos: this.toggleProperty(action, 'done'), }); }; onToggleImportant = (action) => { this.setState({ todos: this.toggleProperty(action, 'important'), }); }; onChangeSearch = (text) => { this.setState({ text }); }; onChangeFilter = (filter) => { this.setState({ filter }); }; search = (text, todos) => { if (text.length === 0) { return todos; } else { return todos.filter((todo) => { return todo.action.toLowerCase().indexOf(text.toLowerCase()) > -1; }); } }; filter = (todos, filter) => { switch (filter) { case 'active': return todos.filter((todo) => !todo.done); case 'done': return todos.filter((todo) => todo.done); default: return todos.filter((todo) => !todo.done); } }; render() { const { filter, text, todos } = this.state; const visibleTodos = this.filter(this.search(text, todos), filter); const doneTodosCounter = todos.filter((todo) => todo.done).length; const todosCounter = todos.length - doneTodosCounter; return ( <div className="container"> <Header todos={todosCounter} done={doneTodosCounter} /> <SearchPanel filter={filter} onChangeSearch={this.onChangeSearch} onChangeFilter={this.onChangeFilter} /> <TodoList todos={visibleTodos} onDelete={this.onDelete} onToggleDone={this.onToggleDone} onToggleImportant={this.onToggleImportant} /> <AddItemPanel handleSubmit={this.handleSubmit} /> <p className="text-center"> <a className="source text-secondary" href="https://github.com/hyypia/todo-app" > Source Code <i className="fa fa-github pl-1" /> </a> </p> </div> ); } }
Java
UTF-8
1,402
3.03125
3
[]
no_license
package be.ac.umons.stratego.pawn; import be.ac.umons.stratego.board.BaseBoard; import java.io.*; /** * Created by marco on 13/05/15. */ /** * this class contains methods for save the game or load the game */ public class SaveLoad implements Serializable{ /** * Save the board contains in BaseBoard * @param plateau represents the game board to save * @throws IOException @see ObjectOutputStream */ public static void SaveGame(BaseBoard plateau) throws IOException { Cell[][] gameBoard = plateau.board; OutputStream file = new FileOutputStream("Sauvegarde"); ObjectOutputStream oursave = new ObjectOutputStream(file); //effectue la sérialistation oursave.writeObject(gameBoard); oursave.close(); } /** *Load the game saved by SaveGame() * @return the board saved * @throws IOException @see FileInputStream * @throws ClassNotFoundException @see ObjectInputStream */ public static BaseBoard LoadGame() throws IOException,ClassNotFoundException{ InputStream file = new FileInputStream("Sauvegarde"); ObjectInputStream ourload= new ObjectInputStream(file); // effectue la désérialistation Cell [][] gameBoard = (Cell[][])ourload.readObject(); BaseBoard x = new BaseBoard(); x.board = gameBoard; ourload.close(); return x; } }
C#
UTF-8
2,015
2.5625
3
[]
no_license
using System; using ForkusHotel.Api.Solution.Persistence; using System.Linq; // ReSharper disable ClassNeverInstantiated.Global namespace ForkusHotel.Api.Solution.ReadModels { internal class BookingQueries : IBookingQueries { private readonly BookingStore _bookingStore; public BookingQueries(BookingStore bookingStore) { _bookingStore = bookingStore; } public BookingListDto RetrieveAllBookings() { return new BookingListDto { bookings = (from booking in _bookingStore.Bookings select new BookingListItemDto { bookingId = booking.BookingId, roomType = booking.RoomType, startDate = booking.StartDate, numberOfNights = booking.NumberOfNights, guestName = booking.GuestName, }).ToArray() }; } public BookingDetailsDto RetrieveBookingDetails(Guid bookingId) { var dto = (from booking in _bookingStore.Bookings where booking.BookingId == bookingId select new BookingDetailsDto { bookingId = booking.BookingId, roomType = booking.RoomType, startDate = booking.StartDate, numberOfNights = booking.NumberOfNights, guestName = booking.GuestName, paymentConfirmed = booking.PaymentConfirmed, checkedIn = booking.CheckedIn, checkedOut = booking.CheckedOut }).SingleOrDefault(); return dto; } public string[] RetrieveAllRoomTypes() { return (from roomType in RoomType.AllRoomTypes select roomType.Name).ToArray(); } } }
Java
UTF-8
720
1.921875
2
[]
no_license
package com.kh.myapp; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.kh.myapp.member.vo.MemberVO; @ExtendWith(SpringExtension.class) @ContextConfiguration(locations= {"file:src/main/webapp/WEB-INF/spring/test.xml"}) class blahblah { private static final Logger logger = LoggerFactory.getLogger(blahblah.class); @Autowired MemberVO logintest; @Test void test() { logger.info(logintest.toString()); } }
Java
UTF-8
2,530
3.375
3
[]
no_license
import java.util.Scanner; public class Saque { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Digite seu saldo atual: "); Float saldoAtual = sc.nextFloat(); sc.close(); if (saldoAtual <= 500) { Ali aliquota = new Ali(); aliquota.valor = 0.5; ParAd parcelaAdicional = new ParAd(); parcelaAdicional.valor = 0; Double saldoSaque = (saldoAtual * aliquota) + parcelaAdicional; System.out.println("O saldo para o saque de aniversário é" + saldoSaque); } else if (saldoAtual >= 500.01 & saldoAtual >= 1000) { Double aliquota = 0.4; int parcelaAdicional = 50; Double saldoSaque = (saldoAtual * aliquota) + parcelaAdicional; System.out.println("O saldo para o saque de aniversário é" + saldoSaque); } else if (saldoAtual >= 1000.01 & saldoAtual >= 5000) { Double aliquota = 0.3; int parcelaAdicional = 150; Double saldoSaque = (saldoAtual * aliquota) + parcelaAdicional; System.out.println("O saldo para o saque de aniversário é" + saldoSaque); } else if (saldoAtual >= 5000.01 & saldoAtual >= 10000) { Double aliquota = 0.2; int parcelaAdicional = 650; Double saldoSaque = (saldoAtual * aliquota) + parcelaAdicional; System.out.println("O saldo para o saque de aniversário é" + saldoSaque); } else if (saldoAtual >= 10000.01 & saldoAtual >= 15000) { Double aliquota = 0.15; int parcelaAdicional = 1150; Double saldoSaque = (saldoAtual * aliquota) + parcelaAdicional; System.out.println("O saldo para o saque de aniversário é" + saldoSaque); } else if (saldoAtual >= 15000.01 & saldoAtual >= 20000) { Double aliquota = 0.1; int parcelaAdicional = 1900; Double saldoSaque = (saldoAtual * aliquota) + parcelaAdicional; System.out.println("O saldo para o saque de aniversário é" + saldoSaque); } else if (saldoAtual >= 20000) { Double aliquota = 0.05; int parcelaAdicional = 2900; Double saldoSaque = (saldoAtual * aliquota) + parcelaAdicional; System.out.println("O saldo para o saque de aniversário é" + saldoSaque); } else { System.out.println("O valor não é válido."); } } }
C#
UTF-8
1,853
3.5625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _6.Forum_Topics { class Program { static void Main(string[] args) { var dict = new Dictionary<string, List<string>>(); string input = Console.ReadLine(); while (true) { if (input == "filter") { break; } string[] tokens = input.Split(", ->".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string topic = tokens[0]; if (!dict.ContainsKey(topic)) { dict[topic] = new List<string>(); } for (int i = 1; i < tokens.Length; i++) { if (!dict[topic].Contains(tokens[i])) { dict[topic].Add(tokens[i]); } } input = Console.ReadLine(); } var filterBy = Console.ReadLine().Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToArray(); foreach (var pair in dict) { bool toPrint = false; for (int i = 0; i < filterBy.Length; i++) { if (pair.Value.Contains(filterBy[i])) { toPrint = true; } else { toPrint = false; break; } } if (toPrint) { Console.WriteLine($"{pair.Key} | #{string.Join(", #", pair.Value)}"); } } } } }
Python
UTF-8
469
2.84375
3
[]
no_license
import numpy as np sigmoid = lambda z : 1/(1+np.exp(-z)) sigmoid_grad = lambda z : z*(1-z) relu = lambda z: (z>0)*z relu_grad = lambda z : (z>0)*1 softmax = lambda z: np.exp(z)/np.sum(np.exp(z)) softmax_grad = lambda z: z*(1-z) tanh = lambda z : np.tanh(z) tanh_grad = lambda z : 1-z*z activation_dict = {"sigmoid":[sigmoid, sigmoid_grad], "relu":[relu, relu_grad], "softmax":[softmax, softmax_grad], "tanh":[tanh, tanh_grad]}
Go
UTF-8
2,069
3.15625
3
[]
no_license
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "sort" "strings" "github.com/julienschmidt/httprouter" "github.com/rs/cors" ) var create = func(addr string, handler http.Handler) listener { return &http.Server{Addr: addr, Handler: handler} } type listener interface { ListenAndServe() error } func main() { s, err := createServer(":3141") if err != nil { log.Fatal(err) } s.ListenAndServe() } func createServer(addr string) (listener, error) { words, err := ioutil.ReadFile("words.txt") // https://github.com/dwyl/english-words/blob/master/words_alpha.txt if err != nil { return nil, err } anagrams := createDictionary(string(words)) router := httprouter.New() router.GET("/anagrams/:letters", anagramFinder(anagrams)) router.NotFound = http.FileServer(http.Dir("../client")) handler := cors.Default().Handler(router) return create(addr, handler), nil } func anagramFinder(anagrams map[string][]string) func(http.ResponseWriter, *http.Request, httprouter.Params) { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { json, err := findWords(anagrams, p.ByName("letters")) httpOut(w, json, err) } } func httpOut(w http.ResponseWriter, message string, err error) { if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Fprintf(w, message) } func findWords(anagrams map[string][]string, letters string) (string, error) { sorted := sortAlpha(strings.ToLower(letters)) if value, ok := anagrams[sorted]; ok { data, err := json.Marshal(value) return string(data), err } return "[]", nil } func createDictionary(words string) map[string][]string { anagrams := make(map[string][]string) for _, word := range strings.Split(words, ",") { sorted := sortAlpha(word) if value, ok := anagrams[sorted]; ok { anagrams[sorted] = append(value, word) } else { anagrams[sorted] = []string{word} } } return anagrams } func sortAlpha(word string) string { s := strings.Split(word, "") sort.Strings(s) return strings.Join(s, "") }
Python
UTF-8
1,714
3.296875
3
[]
no_license
from typing import List class Solution: def largestRectangleArea(self, heights: List[int]) -> int: maxarea = 0 hlen = len(heights) height_stack = [0] * hlen index_stack = [0] * hlen stack_index = -1 if hlen == 0: return 0 for i in range(hlen): h = heights[i] area = h area_index = i density = h # print("\ni", i) # print(height_stack) # print(index_stack) current_stack_index = stack_index index = current_stack_index while index > -1: if height_stack[index] > h: height_stack[index] = h if height_stack[index] * (i - index_stack[index] + 1) > area: area = height_stack[index] * (i - index_stack[index] + 1) area_index = index_stack[index] # print("new", height_stack[index], index_stack[index], area) stack_index = index index -= 1 stack_index += 1 height_stack[stack_index] = h index_stack[stack_index] = i maxarea = max(maxarea, area) # print(i, h, area) # print(height_stack) # print(index_stack) return maxarea s = Solution() # print(s.largestRectangleArea([2,1,5,6,2,3])) # print(s.largestRectangleArea([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) a = [] for i in range(20000): a.append(i+1) print(s.largestRectangleArea(a)) # a = [] # for i in range(20000): # a.append(20000-i) # print(s.largestRectangleArea(a))
Markdown
UTF-8
3,096
3.1875
3
[ "Apache-2.0" ]
permissive
# `kustomization_resource` Resource Resource to provision JSON encoded Kubernetes manifests as produced by the `kustomization_build` or `kustomization_overlay` data sources on a Kubernetes cluster. Uses client-go dynamic client and uses server side dry runs to determine the Terraform plan for changing a resource. ### Terraform Limitation Terraform providers can not control the Terraform dependency graph. But namespaced Kubernetes resources require the namespace to be created first. And there are other examples, like CRDs. To work around Terraform's limitation, this provider retries creating Kubernetes resources that depend on another Kubernetes resource. This works well in many cases but has a potential race condition. It is possible, for various reasons, that the resource's dependency does not get created within the number of retries. Terraform will continue with other resources, but not retry the already failed ones. Applying the failed resources, requires a second Terraform run. One possible workaround is to increase the number of parallel resource operations, using Terraform's `-parallelism=n` parameter. This increases the chance, that the resource the provider is waiting for gets created in time. But increased parallelism is not always an option. A better approach is to instruct Terraform to handle the resources in the correct order, using an explicit `depends_on`. For this reason, both data sources additionally return `ids_prio`, three sets of IDs grouped by the order they should be applied in. Below two examples show both the simplified usage with `for_each` and `ids`. As well as the example with an explicit `depends_on` and `for_each` based on what priority bracket the ID is in. ## Example Usage ### Simple Example ```hcl data "kustomization_build" "test" { path = "test_kustomizations/basic/initial" } resource "kustomization_resource" "test" { for_each = data.kustomization_build.test.ids manifest = data.kustomization_build.test.manifests[each.value] } ``` ### Explicit `depends_on` Example ```hcl data "kustomization_build" "test" { path = "kustomize/test_kustomizations/basic/initial" } # first loop through resources in ids_prio[0] resource "kustomization_resource" "p0" { for_each = data.kustomization_build.test.ids_prio[0] manifest = data.kustomization_build.test.manifests[each.value] } # then loop through resources in ids_prio[1] # and set an explicit depends_on on kustomization_resource.p0 resource "kustomization_resource" "p1" { for_each = data.kustomization_build.test.ids_prio[1] manifest = data.kustomization_build.test.manifests[each.value] depends_on = [kustomization_resource.p0] } # finally, loop through resources in ids_prio[2] # and set an explicit depends_on on kustomization_resource.p1 resource "kustomization_resource" "p2" { for_each = data.kustomization_build.test.ids_prio[2] manifest = data.kustomization_build.test.manifests[each.value] depends_on = [kustomization_resource.p1] } ``` ## Argument Reference - `manifest` - (Required) JSON encoded Kubernetes resource manifest.
Python
UTF-8
625
3.15625
3
[]
no_license
import threading cv = threading.Condition() alist = [] def product(): global alist cv.acquire() print('producer acquire lock') for i in range(10): alist.append(i) cv.release() print('producer release lock') def consumer(): cv.acquire() print('consumer acquire lock') while not alist: print('consumer wait and release lock') cv.wait() print('wait threading acquire lock') print(alist) if __name__ == '__main__': tproducer = threading.Thread(target=product) tconsumer = threading.Thread(target=consumer) tproducer.start() tconsumer.start()
JavaScript
UTF-8
786
2.546875
3
[]
no_license
const { GeneralError } = require("../error/errors"); const handleErrors = (err, req, res, next) => { if (err instanceof GeneralError) { const errCode = err.getCode(); return res.status(errCode).json({ status: errCode, errorCode: nameToErrorCode(err) }); } return res.status(500).json({ status: 500, errorCode: "INTERNAL_SERVER_ERROR", errorCode: err.message }); }; const nameToErrorCode = (err) => { if (err.name.includes("NameTaken")){ return "RESOURCE_ALREADY_EXISTS"; } else if(err.name.includes("Invalid")){ return "BAD_REQUEST"; } else if(err.name.includes("Nonexistent")){ return (err.operation.includes(err.resource))?"RESOURCE_NOT_FOUND":"RELATED_RESOURCE_NOT_FOUND"; } }; module.exports = handleErrors;
C#
UTF-8
1,747
3.953125
4
[]
no_license
/* Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Leetcode { public partial class Solution { public Tuple<int, int> TwoSum(int[] numbers, int target) { int length = numbers.Length; var numList = numbers.ToList(); numList.Sort(); int startIndex = 0; int endIndex = length - 1; for (int i = 0; i < length - 1; i++) { if (numList[startIndex] + numList[endIndex] > target) endIndex--; else if (numList[startIndex] + numList[endIndex] < target) startIndex++; else { break; } } int returnStartIndex = Array.IndexOf(numbers, numList[startIndex]); int returnEndIndex = Array.LastIndexOf(numbers, numList[endIndex]); if (returnStartIndex > returnEndIndex) { var tmp = returnStartIndex; returnStartIndex = returnEndIndex; returnEndIndex = tmp; } return new Tuple<int, int>(returnStartIndex + 1, returnEndIndex + 1); } } }
Python
UTF-8
155
2.828125
3
[]
no_license
#ugugdsun toog palendrom esehiig shalga a = input("vvedite chislo: ") c = a[::-1] if a==c: print("palendrome") else: print("palendrome bish")
Python
UTF-8
2,301
2.984375
3
[]
no_license
from Ports.abstractPort import abstractPort import random # Ein Dummy Port, der random Analog Inputs generiert. class DummyAnalogInputPort(abstractPort): description = "Ein Analoger Dummy Port, der zufällig Integer zwischen den beiden angegebenen Zahlen generiert." options = { "randomSeed": { "name": "Random Seed", "type": "text", "description": "Ein Seed für den Zufallsgenerator.", "standard": "abc", "tab": 1, "final": True }, "min": { "name": "minimaler Wert", "type": "number", "description": "Der minimale Wert als Integer den der Dummyport ausgeben soll.", "standard": 0, "tab": 2, "min": -2000, "max": 2000, "step": 1, "final": False }, "max": { "name": "maximaler Wert", "type": "number", "description": "Der maximale Wert als Integer den der Dummyport ausgeben soll.", "standard": 1000, "tab": 3, "min": -2000, "max": 2000, "step": 1, "final": False } } lastNumber = 0 def __init__(self, externalPort, settings): super().__init__(externalPort, settings) random.seed(self.settings["randomSeed"]) self.lastNumber = int((settings["max"] - settings["min"]) / 2) def getState(self): settings = self.getSettings() # generate a realistic value, near the old value. shortRangeValue = (settings["max"] - settings["min"]) / 100 randomNumber = random.randint(-shortRangeValue, shortRangeValue) while self.lastNumber + randomNumber > settings["max"] or self.lastNumber + randomNumber < settings["min"]: if randomNumber > 0: randomNumber = randomNumber - 1 else: randomNumber = randomNumber + 1 self.lastNumber = self.lastNumber + randomNumber return self.lastNumber def getValueRange(self): settings = self.getSettings() interval = [settings["min"], settings["max"], 1] return interval def getOptions(self): return {**super().superOptions, **self.options}
C++
UTF-8
2,555
2.78125
3
[]
no_license
#include <pigpio.h> #ifndef __cplusplus extern "C++" { #endif //#ifdef __cplusplus #include "SG90.h" #include <cmath> const double minAngle = -90.0; const double maxAngle = 90.0; const double angleRange = 180.0; // Degrees the servo is able to move const unsigned int operatingFreq = 50; const double realMaxDuty = PI_HW_PWM_RANGE; const double signalPeriodMs = 1000.0 / operatingFreq; const double angleTolerance = 0.5; // Constructor sg90ctl::sg90ctl(int iGPIOidx, double iMaxDutyCycleFactor, double iMinDutyCycleFactor) { _GPIOidx = iGPIOidx; _MaxDutyCycleFactor = iMaxDutyCycleFactor; _MinDutyCycleFactor = iMinDutyCycleFactor; } // Destructor sg90ctl::~sg90ctl() { } void sg90ctl::CleanUp() { gpioHardwarePWM(getGPIOIdx(), 0, 0); } int sg90ctl::initialise() { return gpioHardwarePWM(getGPIOIdx(), operatingFreq, toDutyCycle(0)); } int sg90ctl::setTargetLocation(double iAngle) { int rc = 1; double currentLocation = getCurrentLocation(); double deltaangle = std::abs(iAngle - currentLocation); double delaytime = deltaangle / 60 * 0.1 * 2; unsigned int dutyCycle = toDutyCycle(iAngle); while ((currentLocation > (iAngle + angleTolerance)) || (currentLocation < (iAngle - angleTolerance))) { rc = gpioHardwarePWM(getGPIOIdx(), operatingFreq, dutyCycle); //rc = gpioPWM(getGPIOIdx(), dutyCycle); if (rc) break; gpioSleep(PI_TIME_RELATIVE, delaytime, 0); // sleep for 0.1 seconds currentLocation = getCurrentLocation(); } return rc; } int sg90ctl::moveToLocation(double iAngle) { if ((iAngle < minAngle) || (iAngle > maxAngle)) return 1; return setTargetLocation(iAngle); } double sg90ctl::getCurrentLocation() { if (!getGPIOIdx()) return 0; int curWidth = gpioGetPWMdutycycle(getGPIOIdx()); if (curWidth == PI_BAD_USER_GPIO || curWidth == PI_NOT_SERVO_GPIO) throw "bad configuration"; return toAngle(curWidth); } int sg90ctl::move(bool iMovePlus) //Increment one degree { double deltaAngle = (iMovePlus) ? 1.0 : -1.0; deltaAngle += getCurrentLocation(); if ((deltaAngle < minAngle) || (deltaAngle > maxAngle)) return 1; return setTargetLocation(deltaAngle); } double sg90ctl::toAngle(unsigned int iValue) const { return (iValue - realMaxDuty * _MinDutyCycleFactor) * angleRange / ((_MaxDutyCycleFactor - _MinDutyCycleFactor) * realMaxDuty) + minAngle; } unsigned int sg90ctl::toDutyCycle(double iAngle) const { return realMaxDuty * _MinDutyCycleFactor + (iAngle - minAngle) * ((_MaxDutyCycleFactor -_MinDutyCycleFactor) * realMaxDuty) / angleRange; } #ifndef __cplusplus } #endif //ifndef __cplusplus
Java
UTF-8
320
2.8125
3
[]
no_license
package PracaDomowa2701; public class NajwiekszyWspolnyDzielnik { public static void main(String[] args) { int n = 21; int k = 7; while (n != k){ if (n > k) n -= k; else k -= n; } System.out.println("NWD "+n); } }
Java
UTF-8
1,175
2
2
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license" ]
permissive
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.auth; import android.net.Uri; /** Fake UserInfo */ public class UserInfo { protected String email = "fake email"; String getUid() { return "fake uid"; } String getProviderId() { return "fake provider id"; } String getDisplayName() { return "fake display name"; } String getPhoneNumber() { return "fake phone number"; } Uri getPhotoUrl() { return null; } String getEmail() { return email; } boolean isEmailVerified() { // This is false to match the desktop stub. return false; } }
Java
UTF-8
8,629
1.9375
2
[]
no_license
package network; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Properties; import network.Protocols; import network.Config; import network.TcpSender; import network.TcpListener; import util.Log; import constants.MySqlStatement; public class Node { public static final int commonPort = 3001; public static final String IP_EUROPE_AMERICA = "192.168.0.27"; //tim public static final String IP_ASIA_AFRICA = "192.168.0.28"; //gab public static final String IP_BOTH = "192.168.0.29"; //luigi public static final int BOTH_NODE_NUMBER = 1; public static final int EUROPE_AMERICA_NODE_NUMBER = 2; public static final int ASIA_AFRICA_NODE_NUMBER = 3; int nodeNumber; //TcpSender myClient; TcpSender allClient = new TcpSender(IP_BOTH, IP_ASIA_AFRICA); TcpSender europeAmericaClient = new TcpSender(IP_EUROPE_AMERICA, IP_BOTH); TcpSender asiaAfricaClient = new TcpSender(IP_ASIA_AFRICA, IP_EUROPE_AMERICA); Connection mainConn; // set auto commit false Connection replicaConn; TcpListener myServer = new TcpListener(this); public Node (int nodeNumber) { // set this different from each other this.nodeNumber = nodeNumber; Properties connectionProps = new Properties(); connectionProps.put("user", Config.user); connectionProps.put("password", Config.password); switch(nodeNumber) { case BOTH_NODE_NUMBER: try { this.mainConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wdi_all_regions", connectionProps); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { this.replicaConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wdi_asia_africa", connectionProps); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case EUROPE_AMERICA_NODE_NUMBER: try { this.mainConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wdi_europe_and_america", connectionProps); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { this.replicaConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wdi_all_regions", connectionProps); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case ASIA_AFRICA_NODE_NUMBER: try { this.mainConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wdi_asia_africa", connectionProps); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { this.replicaConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/wdi_europe_and_america", connectionProps); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } Log.getInstance().initializeLogFiles(nodeNumber, "log.txt", "transactions.txt"); myServer.start(); try { this.mainConn.setAutoCommit(false); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { this.replicaConn.setAutoCommit(false); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public boolean executeQueryAt(int targetNode, String SQLQuery, String countrycode) { // for inserting, updating, deleting switch (targetNode) { case EUROPE_AMERICA_NODE_NUMBER: // europe return sendData( allClient, europeAmericaClient, europeAmericaClient, asiaAfricaClient, SQLQuery); case ASIA_AFRICA_NODE_NUMBER: // asia return sendData( allClient, asiaAfricaClient, allClient, europeAmericaClient, SQLQuery ); case BOTH_NODE_NUMBER: String region = getRegionFromCountryCode(countrycode); if (region.contains("Europe") || region.contains("America")) return sendData( allClient, europeAmericaClient, europeAmericaClient, asiaAfricaClient, SQLQuery); else return sendData( allClient, asiaAfricaClient, allClient, europeAmericaClient, SQLQuery ); } return false; } public ArrayList<String[]> retrieveData (ArrayList <Integer> targetNodes, ArrayList <String> queries) { ArrayList<String[]> out = new ArrayList<>(); for (int i = 0; i < targetNodes.size(); i++) { if (targetNodes.get(i) == this.nodeNumber) { // if local read PreparedStatement pst; try { pst = mainConn.prepareStatement(queries.get(i)); ResultSet rs = pst.executeQuery(); ResultSetMetaData metadata = rs.getMetaData(); int numberOfColumns = metadata.getColumnCount(); while (rs.next()) { System.out.println("Result set is not empty"); String[] toPlace = new String[numberOfColumns]; for(int j = 0; j < numberOfColumns; j++){ toPlace[j] = rs.getObject(j+1) + ""; } out.add(toPlace); } return out; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // for global read String statement = queries.get(i) + Protocols.QUERY_FOR_SELECT; switch (targetNodes.get(i)) { case EUROPE_AMERICA_NODE_NUMBER: out.addAll(europeAmericaClient.requestData(statement)); break; case ASIA_AFRICA_NODE_NUMBER: out.addAll(asiaAfricaClient.requestData(statement)); break; case BOTH_NODE_NUMBER: out.addAll(allClient.requestData(statement)); break; } } } return out; } public boolean sendData(TcpSender clientForMain1, TcpSender clientForMain2, TcpSender clientForRep1, TcpSender clientForRep2, String SQLQuery) { String queryForMain = SQLQuery + Protocols.QUERY_FOR_MAIN; String queryForReplica = SQLQuery + Protocols.QUERY_FOR_REPLICA; String reply1 = clientForMain1.forwardData(queryForMain); String reply2 = clientForMain2.forwardData(queryForMain); String reply3 = clientForRep1.forwardData(queryForReplica); String reply4 = clientForRep2.forwardData(queryForReplica); System.out.println("Reply1: " + reply1 + " Reply2: " + reply2 + " Reply3: " + reply3 + " Reply4: " + reply4); if (reply1.contains(Protocols.READY) && reply2.contains(Protocols.READY) && reply3.contains(Protocols.READY) && reply4.contains(Protocols.READY)) { clientForMain1.forwardData(Protocols.COMMIT_FOR_MAIN); clientForMain2.forwardData(Protocols.COMMIT_FOR_MAIN); clientForRep1.forwardData(Protocols.COMMIT_FOR_REPLICA); clientForRep2.forwardData(Protocols.COMMIT_FOR_REPLICA); return true; } else { clientForMain1.forwardData(Protocols.ABORT); clientForMain2.forwardData(Protocols.ABORT); clientForRep1.forwardData(Protocols.ABORT); clientForRep2.forwardData(Protocols.ABORT); } return false; } public Connection getMainConnection() { return mainConn; } public Connection getReplicaConnection() { return replicaConn; } public void startServerThread() { this.myServer.start(); } public String getRegionFromCountryCode (String countrycode) { String region = ""; String sql = MySqlStatement.getRegionOfCountryCode + countrycode + "'"; try { PreparedStatement pstmt = getMainConnection().prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); if (rs.next()) region = rs.getString(1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return region; } }
Java
UTF-8
4,758
2.09375
2
[]
no_license
package com.gxz.sys.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.gxz.sys.constast.SysConstast; import com.gxz.sys.domain.Menu; import com.gxz.sys.domain.User; import com.gxz.sys.service.MenuService; import com.gxz.sys.utils.BuilderEasyuiComboTree; import com.gxz.sys.utils.WebUtils; import com.gxz.sys.utils.jsondata.DataGridView; import com.gxz.sys.utils.jsondata.MenuTreeNode; import com.gxz.sys.utils.jsondata.ResultObj; import com.gxz.sys.vo.MenuVo; @Controller @RequestMapping("menu") public class MenuController { @Autowired private MenuService menuService; @RequestMapping("treeNode") @ResponseBody public List<MenuTreeNode> loadLeftMenu(MenuVo menuVo){ List<MenuTreeNode> menuList = new ArrayList<>(); User user = (User) WebUtils.getCurrentHttpServletRequest().getSession().getAttribute("user"); List<Menu> menus = null; menuVo.setAvailable(SysConstast.AVAILABLE_TRUE); //根据用户的type属性判断数的显示 if(user.getType()==SysConstast.USER_SYSTEM_SUPER){ menus = menuService.queryAllMenus(menuVo); }else{ menus = menuService.queryAllMenusByUserId(user.getUserid()); } for (Menu menu : menus) { Integer id = menu.getId(); Integer pid = menu.getPid(); String name = menu.getName(); Boolean isParent = menu.getParent()==SysConstast.PARENT_TRUE?true:false; Boolean open = menu.getOpen()==SysConstast.OPEN_TRUE?true:false; String href = menu.getHref(); String icon = menu.getIcon(); String tabIcon = menu.getTabicon(); MenuTreeNode menuTree = new MenuTreeNode(id, pid, name, isParent, open, href, icon, tabIcon); menuList.add(menuTree); } return menuList; } /****************菜单管理开始*****************/ @RequestMapping("toMenuManager") public String toMenuManager(){ return "forward:/WEB-INF/view/system/menuManager.jsp"; } @RequestMapping("loadMenuManagerTree") @ResponseBody public List<MenuTreeNode> loadMenuManagerTree(MenuVo menuVo){ List<Menu> menus = menuService.queryAllMenus(menuVo); List<MenuTreeNode> menuList = new ArrayList<>(); for (Menu menu : menus) { Integer id = menu.getId(); Integer pid = menu.getPid(); String name = menu.getName(); Boolean isParent = menu.getParent()==SysConstast.PARENT_TRUE?true:false; Boolean open = menu.getOpen()==SysConstast.OPEN_TRUE?true:false; String href = menu.getHref(); String icon = menu.getIcon(); String tabIcon = menu.getTabicon(); menuList.add(new MenuTreeNode(id, pid, name, isParent,open, href, icon, tabIcon)); } return menuList; } @RequestMapping("loadAllMenuData") @ResponseBody public DataGridView loadAllMenuData(MenuVo menuVo){ return menuService.loadAllMenuData(menuVo); } //添加 //加载esayui中的ComboTree @RequestMapping("loadComboTreeJson") @ResponseBody public List<MenuTreeNode> loadComboTreeJson(MenuVo menuVo){ List<Menu> menus = menuService.queryAllMenus(menuVo); List<MenuTreeNode> treeNodes = new ArrayList<>(); for (Menu menu : menus) { Integer id = menu.getId(); Integer pid = menu.getPid(); String name = menu.getName(); treeNodes.add(new MenuTreeNode(id,pid,name)); } Integer topId = 0; return BuilderEasyuiComboTree.builderCombTree(treeNodes, topId); } @RequestMapping("addMenu") @ResponseBody public ResultObj addMenu(MenuVo menuVo){ ResultObj obj = null; try { menuService.addMenu(menuVo); obj = new ResultObj(SysConstast.CODE_SUCCESS,SysConstast.OPERATION_ADD_SUCCESS); } catch (Exception e) { e.printStackTrace(); obj = new ResultObj(SysConstast.CODE_ERROR,SysConstast.OPERATION_ADD_ERROR); } return obj; } @RequestMapping("updateMenu") @ResponseBody public ResultObj updateMenu(MenuVo menuVo){ ResultObj obj = null; try { menuService.updateMenu(menuVo); obj = new ResultObj(SysConstast.CODE_SUCCESS,SysConstast.OPERATION_ADD_SUCCESS); } catch (Exception e) { e.printStackTrace(); obj = new ResultObj(SysConstast.CODE_ERROR,SysConstast.OPERATION_ADD_ERROR); } return obj; } @RequestMapping("deleteMenu") @ResponseBody public ResultObj deleteMenu(MenuVo menuVo){ ResultObj obj = null; try { menuService.deleteMenu(menuVo); obj = new ResultObj(SysConstast.CODE_SUCCESS,SysConstast.OPERATION_ADD_SUCCESS); } catch (Exception e) { e.printStackTrace(); obj = new ResultObj(SysConstast.CODE_ERROR,SysConstast.OPERATION_ADD_ERROR); } return obj; } /****************菜单管理结束*****************/ }
TypeScript
UTF-8
689
2.640625
3
[ "MIT" ]
permissive
import { expect, should } from 'chai'; should(); import { unescape } from '../unescape'; describe('unescape()', () => { it('should replace `&colon;` with `:` in given string', () => { unescape('hellow &colon; world').should.equal('hellow : world'); }); it('should replace `&#number;` with the respective character.', () => { unescape('hellow &#39; world').should.equal('hellow \' world'); }); it('should replace `&#xnumber;` with the respective character.', () => { unescape('hellow &#x49; world').should.equal('hellow I world'); }); it('should remove other `&...;` stuff.', () => { unescape('hellow &lt; world').should.equal('hellow world'); }); });
Java
UTF-8
1,809
3.03125
3
[]
no_license
package model; import org.joda.time.IllegalFieldValueException; import org.joda.time.LocalDate; import org.joda.time.Years; import exceptions.BadAgumentsException; import pattern.Person; public class Employee extends Person { private String job; private Integer salary; private LocalDate start; private LocalDate end; private Integer contract_time; public Employee() { super(); } public Employee(final String name, final String surname, final Integer year, final Integer month, final Integer day, final char sex, final String country, final Integer start_year, final Integer start_month, final Integer start_day, final Integer end_year, final Integer end_month, final Integer end_day, final String job, final Integer salary) throws IllegalFieldValueException, BadAgumentsException { super(name, surname, year, month, day, sex, country); start = new LocalDate(new Integer(start_year), new Integer(start_month), new Integer(start_day)); end = new LocalDate(new Integer(end_year), new Integer(end_month), new Integer(end_day)); contract_time = time(start, end); this.job = job; this.salary = salary; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public Integer getContract_time() { return contract_time; } public Integer time(final LocalDate start, final LocalDate end) { return new Integer(Years.yearsBetween(start, end).getYears()); } @Override public String toString() { return "Employee [job=" + job + ", salary=" + salary + ", start=" + start + ", end=" + end + ", contract_time=" + contract_time + Person.class.toString() +"]"; } }
Java
UTF-8
554
2.65625
3
[ "Apache-2.0" ]
permissive
package org.ovirt.engine.core.utils; import java.util.function.Supplier; /** * This is similar to Google's Suppliers#MemoizingSupplier but is not thread-safe */ public class MemoizingSupplier<T> implements Supplier<T> { private final Supplier<T> delegate; private boolean initialized; private T value; public MemoizingSupplier(Supplier<T> delegate) { this.delegate = delegate; } public T get() { if (!initialized) { value = delegate.get(); initialized = true; } return value; } }
C++
UTF-8
127
2.625
3
[]
no_license
#include <iostream> int main() { int a=1; int db=0; while (a!=0) { a<<=1; ++db; } std::cout<<db<<std::endl; }
Java
UTF-8
259
1.78125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package joliex.java; /** * * @author balint */ public class formatExeption extends Exception { public formatExeption() { super("Error"); } }
Markdown
UTF-8
378
2.671875
3
[]
no_license
# Frame A simple loader that is able to load in-memory dlls. # Usage ```C #include "frame.h" // Loading a dll from memory. pvDll being the in-memory dll. HMODULE hDll = FRAME_LoadLibrary(pvDll); // Getting the address of an exported function from the loaded dll. FARPROC pfnProc = FRAME_GetProcAddress(hDll, "FunctionName"); // Freeing the dll FRAME_FreeLibrary(hDll); ```
C
UTF-8
2,088
3.265625
3
[]
no_license
#include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/times.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> void handler(int sig) { printf("Odebralem sygnal %d\tPID: %d\n", sig, getpid()); } int main(int argc, char* argv[]) { if (argc < 2) { printf("Nie podano argumentu...\n"); exit(1); } struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (strcmp(argv[1], "ignore") == 0) { act.sa_handler = SIG_IGN; sigaction(SIGUSR1, &act, NULL); raise(SIGUSR1); printf("Rodzic zignorowal sygnal\n"); if (fork() == 0) { raise(SIGUSR1); printf("Dziecko zignorowalo sygnal\n"); } } else if (strcmp(argv[1], "handler") == 0) { act.sa_handler = handler; sigaction(SIGUSR1, &act, NULL); raise(SIGUSR1); if (fork() == 0) { raise(SIGUSR1); } } else if (strcmp(argv[1], "mask") == 0) { sigaddset(&act.sa_mask, SIGUSR1); sigprocmask(SIG_SETMASK, &act.sa_mask, NULL); raise(SIGUSR1); printf("Rodzic zablokowal sygnal\n"); if (fork() == 0) { raise(SIGUSR1); printf("Dziecko zablokowalo sygnal\n"); } } else if (strcmp(argv[1], "pending") == 0) { sigaddset(&act.sa_mask, SIGUSR1); sigprocmask(SIG_SETMASK, &act.sa_mask, NULL); raise(SIGUSR1); sigset_t set; sigpending(&set); if (sigismember(&set, SIGUSR1)) { printf("SIGUSR1 oczekuje w procesie rodzica\n"); } else { printf("SIGUSR1 nie oczekuje w procesie rodzica\n"); } if (fork() == 0) { sigpending(&set); if (sigismember(&set, SIGUSR1)) { printf("SIGUSR1 oczekuje w procesie dziecka\n"); } else { printf("SIGUSR1 nie oczekuje w procesie dziecka\n"); } } } while (wait(NULL) > 0) ; return 0; }
Java
UTF-8
2,634
2.515625
3
[]
no_license
package com.makarenko.sqlcmd.commands; import com.makarenko.sqlcmd.model.DatabaseManager; import com.makarenko.sqlcmd.view.Message; import com.makarenko.sqlcmd.view.MessageColor; import org.junit.Before; import org.junit.Test; import static junit.framework.TestCase.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ClearTest { private Message message; private DatabaseManager databaseManager; private Command command; private MessageColor messageColor; @Before public void setUp() { message = mock(Message.class); databaseManager = mock(DatabaseManager.class); command = new Clear(message, databaseManager); messageColor = new MessageColor(); } @Test public void testClearTableSuccessful() { when(message.read()).thenReturn("car"); command.executionCommand("clear|car"); verify(message).write("You want to clear the table 'car'? Enter the name of the table to confirm"); verify(databaseManager).clearTable("car"); verify(message).write("Table 'car' successfully cleared"); } @Test public void testClearTableNotSuccessful() { when(message.read()).thenReturn("d"); command.executionCommand("clear|car"); verify(message).write("You want to clear the table 'car'? Enter the name of the table to confirm"); verify(message).write("cleaning canceled"); } @Test public void testBeginCommand() { boolean beginCommand = command.beginCommand("clear|"); assertTrue(beginCommand); } @Test public void testBeginCommandError() { boolean beginCommandError = command.beginCommand("clqear|"); assertFalse(beginCommandError); } @Test public void testWithoutParameterCommand() { boolean commandWithout = command.beginCommand("clear"); assertFalse(commandWithout); } @Test public void testWithParameterCommandError() { try { command.executionCommand("clear|"); fail(); } catch (IllegalArgumentException e) { assertEquals(messageColor.getErrorMessage("clear|") + "clear|tableName", e.getMessage()); } } @Test public void testFormatCommand() { String formatCommand = command.formatCommand(); assertEquals(formatCommand, "clear|tableName"); } @Test public void testDepictionCommand() { String formatCommand = command.depictionCommand(); assertEquals(formatCommand, "Table cleaning"); } }
Python
UTF-8
1,009
3.125
3
[]
no_license
def areaforn(r, n): return (n)*(4*r+4*(n-1)+2)/2 def solve(fIn, testNum): line = fIn.readline() (r,t) = (int(x) for x in line.split()) n = 32 ans = False low = 1 high = n mid = (low+high)/2 a = areaforn(r, n) if a<t : print "error" a = areaforn(r, mid) while not ans: if a < t: if areaforn(r, mid+1) > t: ans = True break low = mid mid = (low+high)/2 a = areaforn(r, mid) else: if a > t: if areaforn(r, mid-1) < t: mid -= 1 ans = True break high = mid mid = (low+high)/2 a = areaforn(r, mid) else: ans = True break return str(mid) def main(file): fIn = open(file) fOut = open(file+'.out', "w") line = fIn.readline() numTest = int(line) for i in range(numTest): print "test", i+1 fOut.write('Case #' + str(i+1) + ': ' + str(solve(fIn, i+1)) + '\n') fIn.close() fOut.close() return main("A-small-attempt0.in")
Markdown
UTF-8
1,620
3.046875
3
[ "MIT" ]
permissive
> Note: Future updates will be committed in a private repository but the live site will stay up-to-date ## Live site :rocket: The live site can be found [here](https://www.shanemaglangit.com/) ## Rebuild locally :hammer: 1. **Install Gatsby CLI** Use the following command to install gatsby-cli. This requires you to have Node.js pre-installed on your device. ```bash npm install -g gatsby-cli ``` 2. **Clone the project** Run the following command to create a clone of the project ```bash git clone https://github.com/ShaneMaglangit/shanemaglangit-gatsby.git cd shanemaglangit-gatsby ``` 3. **Set up the project** Once you have a working clone of the project, you may use the following command install the necessary dependencies. ```bash npm install ``` 4. **Set up the Strapi Headless CMS** This site uses Strapi as its CMS. Read the [getting started with gatsby](https://strapi.io/documentation/v3.x/getting-started/gatsby.html) as your guide on setting it up. Here are the structure of the collections **Projects** ``` featured: Boolean priority: Number title: Text description: Text source: Text ref: Text category: Enum(software, website) preview: Media ``` **Testimonials** ``` name: Text company: Text message: Text ``` 5. **Add Google Analytics ID** To have the project running, it is necessary to put your own GA trackig ID under gatsby-config.js. Otherwise, you can remove it completely. 6. **Start the project** To wrap things up, run the following command to start the project. ```bash gatsby develop ``` Now you'll be all set to go. You may access the site through http://localhost:8000/.
C#
UTF-8
1,323
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using Projeto.Entity.Entities; using System.ComponentModel.DataAnnotations.Schema; namespace Projeto.DAL.Configuration { public class UsuarioConfiguration : EntityTypeConfiguration<Usuario> { public UsuarioConfiguration() { ToTable("TB_USUARIO"); HasKey(u => u.Id); Property(u => u.Id) .HasColumnName("IDUSUARIO") .IsRequired(); Property(u => u.Nome) .HasColumnName("NOME") .HasMaxLength(50) .IsRequired(); Property(u => u.Sobrenome) .HasColumnName("SOBRENOME") .HasMaxLength(50) .IsRequired(); Property(u => u.Sexo) .HasColumnName("SEXO") .HasMaxLength(15) .IsRequired(); Property(u => u.DataNascimento) .HasColumnName("DATANASCIMENTO") .IsRequired(); Property(u => u.Foto) .HasColumnName("FOTO") .HasMaxLength(50) .IsRequired(); } } }
Java
UTF-8
520
2.875
3
[]
no_license
package Practice; import java.util.Collections; import java.util.Comparator; import java.util.PriorityQueue; /** * Created by intelliswift on 12/16/18. */ public class HeapSortUse { public static void main (String[]args){ PriorityQueue<Integer>p = new PriorityQueue<>(new PriorityQueue<Integer>(Collections.reverseOrder())); p.add(16); p.add(30); p.add(50); p.add(60); p.add(15); System.out.println(p.poll()); System.out.println(p.peek()); } }
PHP
UTF-8
432
3.9375
4
[]
no_license
<?php //Code to calculate a number of days between any two dates function calcDays($sdate, $edate) { $diff = abs($edate-$sdate); $days = $diff/(60*60*24); return $days; } $sdate = '1997-09-24'; $edate = '2021-01-01'; $sdate = strtotime($sdate); $edate = strtotime($edate); $days = calcDays($sdate, $edate); echo "Number of days between given dates is $days \n"; ?>
Python
UTF-8
572
2.9375
3
[]
no_license
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("Position_Salaries.csv") X = data.iloc[:, 1:2].values Y = data.iloc[:, 2].values from sklearn.tree import DecisionTreeRegressor reg = DecisionTreeRegressor(random_state=0) reg.fit(X,Y) ypred= reg.predict(X) #print(ypred) #plt.plot(X, ypred,color='g') x_grid = np.arange(min(X), max(X), 0.01) x_grid = x_grid.reshape((len(x_grid),1)) plt.scatter(X,Y, color='r') plt.plot(x_grid, reg.predict(x_grid), color='b') r2 = reg.score(x_grid, reg.predict(x_grid)) print(r2) plt.show()
JavaScript
UTF-8
4,236
3.0625
3
[]
no_license
var toDoList = angular.module("toDoList", []); toDoList.controller('mainController', ['$scope', function ($scope) { $scope.item = { id: "", value: "", isComplete: false, editing: false }; // Initializing a empty object /* * Setting the default value of the item-container * If localStorage already consist the array then use that else * make a new one. */ if (window.localStorage.getItem('itemContainer') === null) { localStorage.setItem('itemContainer', JSON.stringify([])); } $scope.itemContainer = JSON.parse(localStorage.getItem('itemContainer')) ; $scope.counter = $scope.itemContainer.length + 1; // Adding the counter to assign the Id's to items /* * This function will add the item to the item-container in localStorage * This function will accept a new Object as parameter */ $scope.addItem = function (newItem) { $scope.itemContainer.push(newItem); localStorage.setItem('itemContainer', JSON.stringify($scope.itemContainer)); $scope.item = ""; return $scope.item; }; /* This function will update the localstorage with the changes */ $scope.updateItem = function (itemContainer) { localStorage.setItem('itemContainer', JSON.stringify($scope.itemContainer)); }; /* * This constructor function will create the new list-item objects */ $scope.itemObject = function (id, value) { this.id = id; this.value = value; this.isComplete = false; this.editing = false; }; /* * This function will get called whenever any entry will be updated in the list */ $scope.createItemObject = function () { var newItem = new $scope.itemObject($scope.counter, $scope.item.value); $scope.addItem(newItem); $scope.counter++; }; /* This function will look if the item is checked or not. based on that it will * change the css-class in the 'li' element */ $scope.addItemCheckedClass = function (obj) { if (obj.isComplete === false) { obj.isComplete = true; $scope.updateItem($scope.itemContainer); }else { obj.isComplete = false; $scope.updateItem($scope.itemContainer); } }; /* This function will add the 'line-through' class on the 'li' if the item is checked */ $scope.changeClass = function (obj) { if (obj.isComplete) { return true; } }; /* This function will retrun the count of the pending items */ $scope.checkPendingItem = function () { var len = $scope.itemContainer.length; var count = 0; for (var i = 0; i < len; i++) { var obj = $scope.itemContainer[i]; if (obj.isComplete) { count++; } } return (len - count); }; /* This function will remove the element from the list on clicking the close button*/ $scope.removeItem = function (obj) { var index = $scope.itemContainer.indexOf(obj); $scope.itemContainer.splice(index, 1); $scope.updateItem(); }; /* Funtion will work whever the item is double-clicked */ $scope.editItem = function (obj) { if (!obj.isComplete) { obj.editing = true; $scope.updateItem(obj); } }; $scope.doneEdit = function (obj) { obj.editing = false; $scope.updateItem(obj); }; /* Function to display the pending items */ $scope.showPendingStatus = false; $scope.showCompletedStatus = false; $scope.showAllStatus = true; $scope.showPending = function () { $scope.showAllStatus = false; $scope.showPendingStatus = true; $scope.showCompletedStatus = false; }; $scope.showCompleted = function () { $scope.showAllStatus = false; $scope.showPendingStatus = false; $scope.showCompletedStatus = true; }; $scope.showAll = function () { $scope.showAllStatus = true; $scope.showPendingStatus = false; $scope.showCompletedStatus = false; }; }]);
Java
UTF-8
13,444
1.984375
2
[]
no_license
package com.liftindia.app.caldroid; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.liftindia.app.R; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.TimeZone; import hirondelle.date4j.DateTime; /** * The CaldroidGridAdapter provides customized view for the dates gridview * * @author thomasdao */ public class CaldroidGridAdapter extends BaseAdapter { protected ArrayList<DateTime> datetimeList; protected int month; protected int year; protected Context context; protected ArrayList<DateTime> disableDates; protected ArrayList<DateTime> selectedDates; // Use internally, to make the search for date faster instead of using // indexOf methods on ArrayList protected HashMap<DateTime, Integer> disableDatesMap = new HashMap<DateTime, Integer>(); protected HashMap<DateTime, Integer> selectedDatesMap = new HashMap<DateTime, Integer>(); protected DateTime minDateTime; protected DateTime maxDateTime; protected DateTime today; protected int startDayOfWeek; protected boolean sixWeeksInCalendar; protected Resources resources; private int disableTextColr; private int notAvailbleTextColr; private boolean isSelectionEnable = true; /** * caldroidData belongs to Caldroid */ protected HashMap<String, Object> caldroidData; /** * extraData belongs to client */ protected HashMap<String, Object> extraData; public void setAdapterDateTime(DateTime dateTime) { this.month = dateTime.getMonth(); this.year = dateTime.getYear(); this.datetimeList = CalendarHelper.getFullWeeks(this.month, this.year, startDayOfWeek, sixWeeksInCalendar); } // GETTERS AND SETTERS public ArrayList<DateTime> getDatetimeList() { return datetimeList; } public DateTime getMinDateTime() { return minDateTime; } public void setMinDateTime(DateTime minDateTime) { this.minDateTime = minDateTime; } public DateTime getMaxDateTime() { return maxDateTime; } public void setMaxDateTime(DateTime maxDateTime) { this.maxDateTime = maxDateTime; } public ArrayList<DateTime> getDisableDates() { return disableDates; } public void setDisableDates(ArrayList<DateTime> disableDates) { this.disableDates = disableDates; } public ArrayList<DateTime> getSelectedDates() { return selectedDates; } public void setSelectedDates(ArrayList<DateTime> selectedDates) { this.selectedDates = selectedDates; } public HashMap<String, Object> getCaldroidData() { return caldroidData; } public void setCaldroidData(HashMap<String, Object> caldroidData, DataMap datamap) { this.caldroidData = caldroidData; // Reset parameters populateFromCaldroidData(); populateHashMap(datamap); } public HashMap<String, Object> getExtraData() { return extraData; } public void setExtraData(HashMap<String, Object> extraData) { this.extraData = extraData; } /** * Constructor * * @param context * @param month * @param year * @param caldroidData * @paramfget extraData */ public CaldroidGridAdapter(Context context, int month, int year, HashMap<String, Object> caldroidData, HashMap<String, Object> extraData, DataMap datamap, boolean isSelectionEnable) { super(); this.month = month; this.year = year; this.context = context; this.caldroidData = caldroidData; this.extraData = extraData; this.resources = context.getResources(); this.isSelectionEnable = isSelectionEnable; // Get data from caldroidData disableTextColr = Color.parseColor("#ababab"); notAvailbleTextColr = Color.parseColor("#000000"); selected_color = context.getResources().getColor(R.color.white); populateFromCaldroidData(); populateHashMap(datamap); } /* @Override public boolean areAllItemsEnabled() { return isSelectionEnable; }*/ HashMap<Integer, Integer> currentMonthMap; private int selected_color; private boolean calender_not_null = false; private void populateHashMap(DataMap data) { if (data != null) if (data.getYearMap() != null) if (data.getYearMap().get(year) != null) if (data.getYearMap().get(year).getMonthMap() != null) if (data.getYearMap().get(year).getMonthMap().get(month) != null) if (data.getYearMap().get(year).getMonthMap().get(month).getDateMap() != null) { currentMonthMap = data.getYearMap().get(year).getMonthMap().get(month).getDateMap(); calender_not_null = true; } } /** * Retrieve internal parameters from caldroid data */ @SuppressWarnings("unchecked") private void populateFromCaldroidData() { disableDates = (ArrayList<DateTime>) caldroidData .get(CaldroidFragment.DISABLE_DATES); if (disableDates != null) { disableDatesMap.clear(); for (DateTime dateTime : disableDates) { disableDatesMap.put(dateTime, 1); } } selectedDates = (ArrayList<DateTime>) caldroidData .get(CaldroidFragment.SELECTED_DATES); if (selectedDates != null) { selectedDatesMap.clear(); for (DateTime dateTime : selectedDates) { selectedDatesMap.put(dateTime, 1); } } minDateTime = (DateTime) caldroidData .get(CaldroidFragment._MIN_DATE_TIME); maxDateTime = (DateTime) caldroidData .get(CaldroidFragment._MAX_DATE_TIME); startDayOfWeek = (Integer) caldroidData .get(CaldroidFragment.START_DAY_OF_WEEK); sixWeeksInCalendar = (Boolean) caldroidData .get(CaldroidFragment.SIX_WEEKS_IN_CALENDAR); this.datetimeList = CalendarHelper.getFullWeeks(this.month, this.year, startDayOfWeek, sixWeeksInCalendar); } public void updateToday() { today = CalendarHelper.convertDateToDateTime(new Date()); } protected DateTime getToday() { if (today == null) { today = CalendarHelper.convertDateToDateTime(new Date()); } return today; } @SuppressWarnings("unchecked") protected void setCustomResources(DateTime dateTime, View backgroundView, TextView textView) { // Set custom background resource HashMap<DateTime, Integer> backgroundForDateTimeMap = (HashMap<DateTime, Integer>) caldroidData .get(CaldroidFragment._BACKGROUND_FOR_DATETIME_MAP); if (backgroundForDateTimeMap != null) { // Get background resource for the dateTime Integer backgroundResource = backgroundForDateTimeMap.get(dateTime); // Set it if (backgroundResource != null) { backgroundView.setBackgroundResource(backgroundResource .intValue()); } } // Set custom text color HashMap<DateTime, Integer> textColorForDateTimeMap = (HashMap<DateTime, Integer>) caldroidData .get(CaldroidFragment._TEXT_COLOR_FOR_DATETIME_MAP); if (textColorForDateTimeMap != null) { // Get textColor for the dateTime Integer textColorResource = textColorForDateTimeMap.get(dateTime); // Set it if (textColorResource != null) { textView.setTextColor(resources.getColor(textColorResource .intValue())); } } } /** * Customize colors of text and background based on states of the cell * (disabled, active, selected, etc) * <p/> * To be used only in getView method * * @param position * @param cellView */ protected void customizeTextView(int position, TextView cellView) { // Get dateTime of this cell DateTime dateTime = this.datetimeList.get(position); Calendar calendar = Calendar.getInstance(); // Set color of the dates in previous / next month if (dateTime.getMonth() != month) { cellView.setTextColor(resources .getColor(R.color.caldroid_darker_gray)); cellView.setVisibility(View.GONE); return; } if (calendar.get(Calendar.YEAR) == dateTime.getYear() && dateTime.getMonth() == calendar.get(Calendar.MONTH) + 1) { if (dateTime.getDay() < calendar.get(Calendar.DAY_OF_MONTH)) { cellView.setTextColor(resources .getColor(R.color.caldroid_darker_gray)); } } else if (calendar.get(Calendar.YEAR) == dateTime.getYear() && dateTime.getMonth() + 1 == calendar.get(Calendar.MONTH) + 1 + 4) { if (dateTime.getDay() > calendar.get(Calendar.DAY_OF_MONTH)) { Log.e("not selectable", "not 2"); cellView.setTextColor(resources .getColor(R.color.caldroid_darker_gray)); } else { Log.e("good selectable", "good 2"); } } boolean shouldResetDiabledView = false; boolean shouldResetSelectedView = false; // Customize for disabled dates and date outside min/max dates if ((minDateTime != null && dateTime.lt(minDateTime)) || (maxDateTime != null && dateTime.gt(maxDateTime)) || (disableDates != null && disableDatesMap.get(dateTime) != null )) { cellView.setTextColor(disableTextColr); /*if (CaldroidFragment.disabledBackgroundDrawable == -1) { cellView.setTextColor(disableTextColr); } else { // cellView.setBackgroundResource(CaldroidFragment.disabledBackgroundDrawable); }*/ ///udated by sagar // if (dateTime.equals(getToday())) { // cellView.setTextColor(Color.parseColor("#ffffff")); // //cellView.setBackgroundResource(R.drawable.red_border_gray_bg); // } else { // // // } } else { shouldResetDiabledView = true; } // Customize for selected dates if (selectedDates != null && selectedDatesMap.get(dateTime) != null) { cellView.setTextColor(selected_color); } else { shouldResetSelectedView = true; cellView.setTextColor(notAvailbleTextColr); } ///udated by sagar // if (dateTime.equals(getToday())) { // cellView.setBackgroundResource(R.drawable.today_circle_bg); // cellView.setTextColor(selected_color); // } cellView.setText("" + dateTime.getDay()); // // Set custom color if required // setCustomResources(dateTime, cellView, cellView); if (calender_not_null) { if (currentMonthMap.get(dateTime.getDay()) != null) { cellView.setTextColor(selected_color); cellView.setBackgroundResource(R.drawable.selected_circle_bg); } } if (!isEnabled(position)) cellView.setTextColor(disableTextColr); } private long nintyDaysMillis = 1000l * 60l * 60l * 24l * 90l; @Override public boolean isEnabled(int position) { boolean isEnable = true; DateTime dateTime = this.datetimeList.get(position); long currentmillis = dateTime.getMilliseconds(TimeZone.getDefault()); long todaymillis = today.getMilliseconds(TimeZone.getDefault()); //disable dates if (currentmillis < todaymillis) { isEnable = false; } else if (dateTime.getMonth() - today.getMonth() == 3) { if (dateTime.getDay() > today.getDay()) { isEnable = false; } } return isEnable; } @Override public int getCount() { // TODO Auto-generated method stub return this.datetimeList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); TextView cellView = (TextView) convertView; // For reuse if (convertView == null) { cellView = (TextView) inflater.inflate(R.layout.date_cell, null); } customizeTextView(position, cellView); return cellView; } }
Python
UTF-8
2,689
3.171875
3
[]
no_license
get_ipython().magic('matplotlib notebook') import matplotlib.pyplot as plt import pandas as pd import numpy as np from calendar import month_abbr def get_data(): df = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv') df['Data_Value'] = df['Data_Value'].apply(lambda x: x/10) df['Date'] = pd.to_datetime(df['Date']) return df def clear_data(): df = get_data() #cut off the extra day in February df['Year'], df['Month_Day'] = df['Date'].dt.year, df['Date'].dt.strftime('%m-%d') df = df[df['Month_Day'] != '02-29'] #selecting TMAX and TMIN data temp_max = (df[(df['Element'] == 'TMAX') & (df['Year'] >=2005) & (df['Year']<2015)] .groupby(['Month_Day'])['Data_Value'].max()) temp_min = (df[(df['Element'] == 'TMIN') & (df['Year'] >=2005) & (df['Year']<2015)] .groupby(['Month_Day'])['Data_Value'].min()) df = df.merge(temp_max.reset_index(drop=False).rename(columns={'Data_Value':'Max_Temp'}), on='Month_Day', how='left') df = df.merge(temp_min.reset_index(drop=False).rename(columns={'Data_Value':'Min_Temp'}), on='Month_Day', how='left') #selecting TMAX and TMIN for 2015 df_2015MAX = df[(df['Year'] == 2015) & (df['Data_Value'] > df['Max_Temp'])] df_2015MIN = df[(df['Year'] == 2015) & (df['Data_Value'] < df['Min_Temp'])] return temp_max, temp_min, df_2015MAX, df_2015MIN #reading cleaner data TMAX, TMIN, TMAX_2015, TMIN_2015 = clear_data() #plotting data (lines and scatter) dates = np.arange('2015-01-01','2016-01-01', dtype='datetime64[D]') plt.figure() plt.plot(dates, TMAX, color='tomato',linewidth=1) plt.plot(dates, TMIN, color='royalblue',linewidth=1) plt.scatter(TMAX_2015['Date'].values, TMAX_2015['Data_Value'], c='darkred', s=10) plt.scatter(TMIN_2015['Date'].values, TMIN_2015['Data_Value'], c='darkblue', s=10) #formatting the graphic plt.xlabel(' ') plt.ylabel('Temperature [°C]', fontsize=12) plt.title('Temperatures variation in Ann Arbor, Michigan, USA, from 2005 \n to 2014, and special marks of 2015') plt.legend(['Highest temperatures (2005-2014)', 'Lower temperatures (2005-2014)', 'Day in 2015 above historical series', 'Day in 2015 below historical series'], loc=0, frameon=False, fontsize=8) #fill between lines plt.fill_between(dates, TMAX, TMIN, facecolor='gray', alpha=0.5) #artistic vision ax = plt.gca() ax.axis(['2015/01/01','2015/12/31',-50,50]) ax.set_xticklabels([' %s'%s for s in month_abbr if s!='']) # adding 9 spaces before month name ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.show() # In[ ]:
Java
UTF-8
967
1.929688
2
[]
no_license
package com.example.leaderboard; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; public class SubmitActivity extends AppCompatActivity { private Toolbar toolbar2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_submit); Toolbar toolbar2 = findViewById(R.id.toolbar2); setSupportActionBar(toolbar2); toolbar2.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_black_24dp)); toolbar2.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setContentView(R.layout.activity_main); } }); } @Override public boolean onSupportNavigateUp(){ onBackPressed(); return true; } }
Python
UTF-8
197
3.40625
3
[]
no_license
jari_jari = input("Masukkan nilai: ") jari_jari = int(jari_jari) rumus = (jari_jari*jari_jari*22/7) print("Luas lingkaran dengan jari-jari ",jari_jari, "cm adalah {0:.2f} cm\u00b2.".format(rumus))
Markdown
UTF-8
2,061
2.59375
3
[]
no_license
# Qt4.8.6-my-modified-version 自用修改版Qt4.8.6 #QtCore 主要对QObject::connect进行修改 enum ConnectionType { AutoConnection, DirectConnection, QueuedConnection, AutoCompatConnection, BlockingQueuedConnection, ParallelBlockingQueuedConnection, //like BlockingQueuedConnection, but the receivers will begin together UniqueConnection = 0x80 }; enum ConnectionPosition { ConnectAtEnd = 0, ConnectAtBegin }; 原版Qt没有ConnectionPosition,信号触发时槽函数的调用顺序由QObject::connect的连接顺序决定。 现在可以在连接时指定ConnectAtBegin,让该槽函数获得优先调用。 ParallelBlockingQueuedConnection是一种新的连接类型,类似于BlockingQueuedConnection,但不同的是,槽函数会同时被调用。 #QtGui 由于Qt4对高dpi支持得不好,所以我删除了Windows系统下SetProcessDPIAware的调用,修改版的QtGui被视为不支持高dpi的旧程序,在高dpi环境下,界面被放大,会模糊,比例不会失调。 #版本兼容性 ####修改版的Qt模块,仅QtCore与原版不同(多了几个导出符号),其他模块(QtGui、QtWidgets等)理论上与原版完全相同,可以随意混用。 ####修改版在代码级、二进制级向下兼容原版。 ####反过来,如果代码中没有用到修改版的新特性,就可以在原版上编译(必须的);`但是,无论是否用到新特性,使用修改版编译的程序都无法在原版上运行`。 编译所用的版本 程序可以在原版上运行 程序可以在修改版上运行 原版 √ √ 修改版                  × √ 如果试图用原版dll/so上运行使用修改版编译的程序,会因为找不到专有的导出符号而出错。 Windows会弹出错误提示框,而Linux会在第一次运行到QObject::connect时崩溃。
PHP
UTF-8
822
2.5625
3
[ "Apache-2.0" ]
permissive
<?php namespace Craft; /** * The class name is the UTC timestamp in the format of mYYMMDD_HHMMSS_migrationName */ class m141126_000001_user_week_start_day extends BaseMigration { /** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { Craft::log('Adding weekStartDay column to users table...', LogLevel::Info, true); $column = array(ColumnType::TinyInt, 'unsigned', 'required' => true, 'default' => '0'); if (craft()->db->columnExists('users', 'weekStartDay')) { $this->update( 'users', array('weekStartDay' => '0'), 'weekStartDay is null' ); $this->alterColumn('users', 'weekStartDay', $column); } else { $this->addColumnAfter('users', 'weekStartDay', $column, 'preferredLocale'); } return true; } }
Python
UTF-8
1,491
2.9375
3
[]
no_license
import face_recognition from PIL import Image, ImageDraw image_of_me = face_recognition.load_image_file('img/known/Dimitris_Pallas.jpg') dimitris_face_encoding = face_recognition.face_encodings(image_of_me)[0] # Create and array of encodings and names known_face_encoding = [ dimitris_face_encoding ] known_face_name = [ "Dimitris Pallas" ] # Load test image test_image = face_recognition.load_image_file('img/unknown/we_will_see.jpg') # Find faces test image face_locations = face_recognition.face_locations(test_image) face_encoding = face_recognition.face_encodings(test_image, face_locations) # Convert to PIL format pil_image = Image.fromarray(test_image) # Create an ImageDraw instance draw = ImageDraw.Draw(pil_image) # Loop through faces in test image for (top, right, bottom, left), face_encoding in zip(face_locations, face_encoding): matches = face_recognition.compare_faces(known_face_encoding, face_encoding) name = "Unknown person" # if match if True in matches: first_match_index = matches.index(True) name = known_face_name[first_match_index] # Draw box draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 0)) # Draw label text_width, text_height = draw.textsize(name) draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 0), outline=(0, 0, 0)) draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 255, 255, 255)) del draw pil_image.show()
Java
UTF-8
1,176
2.0625
2
[]
no_license
/** * */ package com.zappos.rest; import java.util.List; import com.google.gson.Gson; import com.zappos.domain.ProductResponse; import com.zappos.domain.SearchResponse; import com.zappos.restconnector.WebServiceConnector; import com.zappos.util.PropertiesHandler; /** * @author satyaswaroop * */ public class RestClient { private PropertiesHandler properties = PropertiesHandler.getProperties("src\\rest.properties"); public SearchResponse search(String term,int page) { String url = properties.getValue("searchurl")+properties.getValue("parameter_term")+term+properties.getValue("parameter_page")+(page); String response = WebServiceConnector.getResponse(url); Gson gson = new Gson(); SearchResponse p = gson.fromJson(response, SearchResponse.class); return p; } public ProductResponse getProduct(List<String> styleId) { String url = properties.getValue("producturl")+properties.getValue("parameter_style")+styleId.toString()+properties.getValue("parameter_includes"); String response = WebServiceConnector.getResponse(url); Gson gson = new Gson(); ProductResponse p = gson.fromJson(response, ProductResponse.class); return p; } }
Python
UTF-8
919
3.015625
3
[]
no_license
import numpy as np from utils import SkillType, BaseAttr, DynamicAttr class Skill: def __init__(self): self.type = SkillType.getRandomType() self.attr = DynamicAttr.getRandomType(4) self.target = DynamicAttr.getRandomType(3) self.ratio = np.random.randint(2,10) / 100.0 class Person: def __init__(self): self.attrs = {attr.name: np.random.randint(10,100) for attr in BaseAttr} @property def level(self): return 1 @property def attack(self): return self.attrs['base_attack'] + self.attrs['mat_attack'] * (self.level - 1) @property def defence(self): return self.attrs['base_defence'] + self.attrs['mat_defence'] * (self.level - 1) @property def life(self): return self.attrs['base_life'] + self.attrs['mat_life'] * (self.level - 1) if __name__ == '__main__': a = Person() print(a.attrs)
Python
UTF-8
1,435
3.328125
3
[]
no_license
import sys sys.stdin = open("1208.txt", "r") # 버블 정렬 # 카운팅 정렬 def my_max(): max_height = box_height[0] max_index = 0 # 초기값 index 0인 첫번째 값, 인덱스는 0 설정 for i in range(len(box_height)): if box_height[i] > max_height: max_height = box_height[i] max_index = i return max_index # 최소 높이의 위치 인덱스 def my_min(): min_height = box_height[0] min_index = 0 # 초기값 index 0인 첫번째 값, 인덱스는 0 설정 for j in range(len(box_height)): if box_height[j] < min_height: min_height = box_height[j] min_index = j return min_index # 최대 높이의 위치 인덱스 for tc in range(1, 11): # 총 10개의 테스트 케이스 반복 dump = int(input()) # 덤프 횟수 box_height = list(map(int, input().split())) # 박스 높이 for k in range(dump): # 덤프횟수 반복 box_height[my_max()] -= 1 # 최대 높이 위치의 인덱스(my_max())에 접근하여 높이(box_height[my_max()])를 1개 감소 box_height[my_min()] += 1 # 최소 높이 위치의 인덱스(my_min())에 접근하여 높이(box_height[my_min()])를 1개 감소 result = box_height[my_max()] - box_height[my_min()] # 최고점과 최저점의 높이 차 print('#{} {}'.format(tc, result)) # 출력
JavaScript
UTF-8
1,595
2.765625
3
[]
no_license
function assertCSTTZ() { // NOTE: Verify that we are not sproofing Time Zone, as the rest call depends // on locale. UTC doesn't make sense here as we need local time var timeZoneOffset = - ( (new Date()).getTimezoneOffset() / 60 ); if ( timeZoneOffset !== 8 ) { console.error(`* Error: Time zone is incorrect: UTC + (${timeZoneOffset})`); console.error('* Abort: environment is tempered.'); process.exit(0); } } function isCheckInHour (curTime) { const HOURS = [5]; // Only Early morning console.log(`** Checkin time is ${HOURS[0]}-${HOURS[HOURS.length -1 ] + 1} with *CST, GMT+8*.`); var curDay = curTime.getDay(); var curHour = curTime.getHours(); return (HOURS.indexOf(curHour) > -1); } function isValidServerComm(res) { if (res.statusCode !== 200) { console.error(`* Network error: ${res.statusCode}`); return false; } // NOTE is `authorized` field alone enough? if ( !res.socket.authorized ) { console.error(`* ERROR: The Server is NOT authorized. Something weird happened.`); return false; } return true; } // FIX: the following DNS check is basically useless, with HTTPS we might not // need DNS checking anymore. function isSuspiciousDNSRes(addrs) { const wrongAddrs = ["127.0.0.1", "108.61.162.93"]; return addrs.some( addr => (wrongAddrs.indexOf(addr) > -1) ); } module.exports = { assertCSTTZ: assertCSTTZ, isCheckInHour: isCheckInHour, isValidServerComm: isValidServerComm, isSuspiciousDNSRes: isSuspiciousDNSRes, };
Ruby
UTF-8
279
3.265625
3
[]
no_license
unsorted_array = [5, 3, 42, 398, 28, 2, 20, 5, 2, 0, -20, 4] class Array def quicksort return self if size <= 1 pivot = self.sample left_array select{|x| x < pivot}.quicksort + [pivot] + select{|x| x > pivot}.quicksort end end puts unsorted_array.quicksort
Python
UTF-8
2,138
2.703125
3
[ "MIT" ]
permissive
from discord import Embed, ChannelType from discord.ext import commands config_file = 'extensions/inquisition_channel_id.txt' class Inquisition(commands.Cog): """Runs the Inquisition channel.""" def __init__(self, bot, channel_id): self.bot = bot self.channel = bot.get_channel(channel_id) self.info_suffix = "Use the '!inquisition question' (!inq q <question>) command to ask a question." @commands.command(aliases=["q"]) @commands.guild_only() async def question(self, ctx, *, question_text): """Ask a question in the Inquisition Channel.""" if ctx.channel != self.channel: await ctx.channel.send("This is not the Inquisition channel.") return message = await ctx.channel.send(embed=Embed( title="{} asked a question:".format(ctx.author.display_name), description=question_text, color=ctx.bot.colors['default'])) await message.pin() await ctx.channel.edit(topic="{} - {}".format(question_text, self.info_suffix)) @commands.command(hidden=True) @commands.guild_only() @commands.check_any( commands.is_owner(), commands.has_role('Operator')) # TODO: Check for any role in config.json async def inqsetup(self, ctx): """Set the Inquisition Channel""" if ctx.channel.type != ChannelType.text: await ctx.channel.send(embed=ctx.bot.error_embed("Not available here.")) return self.channel = ctx.channel with open(config_file, 'w') as file: file.write(str(self.channel.id)) await ctx.channel.send(embed=Embed( title="Inquisition", description="Let the Inquisition begin! {}".format(self.info_suffix), color=ctx.bot.colors['confirm'])) def setup(bot): channel_id = None try: with open(config_file, 'r') as file: channel_id = int(file.read()) except Exception as exc: print("Failed to load inquisition_channel_id.txt") print(repr(exc)) bot.add_cog(Inquisition(bot, channel_id))
Java
UTF-8
2,473
2.375
2
[]
no_license
package connectEchoNest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; public class dbHandler { static String URL = "jdbc:mysql://" + "127.0.0.1:8889/exercise_myp?useUnicode=true&characterEncoding=euckr"; static String ID = "root"; static String PW = "root"; static Connection conn = null; dbHandler() { try { Class.forName("com.mysql.jdbc.Driver"); conn = (Connection) DriverManager.getConnection(URL, ID, PW); System.out.println("Mysql Connect Success!"); } catch (Exception e) { e.printStackTrace(); return; } } public static GomLog getSeqSongDeatil(int startIndex, int size) { GomLog gomlog = new GomLog(); try{ Statement stmt = null; System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT * FROM gomlog LIMIT " + startIndex + ", " + size; ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name gomlog.addIp(rs.getString("ip")); gomlog.addDate(rs.getString("date")); gomlog.addTime(rs.getString("time")); gomlog.addTitle(rs.getString("title")); gomlog.addArtist(rs.getString("artist")); gomlog.addSize(rs.getInt("size")); gomlog.addUtc(rs.getInt("utc")); gomlog.addVersion(rs.getString("version")); } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return gomlog; } public static void InsertSongId(String ip, String date, String time, String songid, List<String> genre, int size, int utc, String version) { Statement st = null; String genres = ""; for(int i=0; i<genre.size(); i++) genres += genre.get(i) + ","; String query = "INSERT INTO gom_echo " + " (ip, date, time, song_id, genre, size, utc, version) " + " values ('" + ip + "', '" + date + "', '" + time + "', '" + songid + "'," + " '"+genres+"', " + size+", " + utc + ", '" + version + "')"; try { st = conn.createStatement(); st.executeUpdate(query); st.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
SQL
UTF-8
10,040
3.09375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1:3306 -- Généré le : mer. 24 juil. 2019 à 18:06 -- Version du serveur : 5.7.23 -- Version de PHP : 7.2.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `brehat` -- -- -------------------------------------------------------- -- -- Structure de la table `admin` -- DROP TABLE IF EXISTS `admin`; CREATE TABLE IF NOT EXISTS `admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `prename` varchar(255) NOT NULL, `login` varchar(255) NOT NULL, `pass` varchar(255) NOT NULL, `mail` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `admin` -- INSERT INTO `admin` (`id`, `name`, `prename`, `login`, `pass`, `mail`) VALUES (1, 'morillon', 'guillaume', 'pseudo', '$2y$10$YeFPkvb/j/93.arZ/LxgheyNNglsC2dmG50d5MTKiZQTXc9vIOJ8i', 'guillaume.morillon@gmx.fr'); -- -------------------------------------------------------- -- -- Structure de la table `avis` -- DROP TABLE IF EXISTS `avis`; CREATE TABLE IF NOT EXISTS `avis` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(256) NOT NULL, `prenom` varchar(256) NOT NULL, `avis` text NOT NULL, `mail` varchar(256) NOT NULL, `datejour` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `avis` -- INSERT INTO `avis` (`id`, `nom`, `prenom`, `avis`, `mail`, `datejour`) VALUES (14, 'Morillon', 'Guillaume', 'Location très agréable dans une maison typique de Bretagne. Nous avons eu beau temps durant tout le séjour, les températures étaient même très agréables! nous reviendrons l\'année prochaine', 'guill@free.fr', '2019-07-08'), (19, 'Dubois', 'Jean-Luc', 'La maison est agréable et pratique, je recommande !', 'guillaume.morillon@gmx.fr', '2019-07-24'); -- -------------------------------------------------------- -- -- Structure de la table `avis_buffer` -- DROP TABLE IF EXISTS `avis_buffer`; CREATE TABLE IF NOT EXISTS `avis_buffer` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(256) NOT NULL, `prenom` varchar(256) NOT NULL, `avis` text NOT NULL, `mail` varchar(256) NOT NULL, `datejour` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Structure de la table `citations_brehat` -- DROP TABLE IF EXISTS `citations_brehat`; CREATE TABLE IF NOT EXISTS `citations_brehat` ( `id` int(11) NOT NULL AUTO_INCREMENT, `auteur` varchar(256) NOT NULL, `citation` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `citations_brehat` -- INSERT INTO `citations_brehat` (`id`, `auteur`, `citation`) VALUES (1, 'Erik Orsenna de l’Académie Française ', ' Bréhat n’est pas qu’une île : un archipel, c’est-à-dire une grande famille d’univers minuscules. Chacun d’entre eux résume le monde. Prenez le temps d’y aborder. Un voyage à Bréhat c’est mille voyages, ouvrez l’œil et freinez l’allure. La récompense est au bout de la lenteur.'), (2, 'Victor Hugo', 'L’espace est un océan ; les univers sont des îles. Mais il faut des communications entre ces îles. Ces communications se font par les âmes. La mort fait des envois d’esprits d’un monde à l’autre.'), (4, 'Albert Camus', 'D\'une manière générale, j\'aime toutes les îles. Il est plus facile d\'y régner.'), (5, 'Tant qu\'il y aura des îles - Jacques Chancel', 'Chacun de nous porte en lui ces propres îles, refuges.'), (6, 'Patrick Weber', 'J’aime bien les îles. Il n’y a pas moyen de fuir. Quand on est face à un problème.'), (7, 'Coluche', 'C\'est joli la Bretagne, et puis c\'est pas loin de la France.'), (8, 'L\'Adieu aux îles (1986) de Hervé Jaouen', 'C\'était la Bretagne et seule cette province leur semblait capable de rivaliser avec la beauté sauvage de leurs îles.'), (9, 'Lettre, à Emile Schuffenecker, 1888 de Paul Gauguin', 'J\'aime la Bretagne, j\'y trouve le sauvage, le primitif. Quand mes sabots résonnent sur ce sol de granit, j\'entends le son sourd, mat et puissant que je cherche en peinture.'), (10, 'Ce qui reste du jour (1966-1972), Journal IX (1972) de Julien Green', 'Visite d\'un ami breton, il me parle du grand nombre d\'autonomistes bretons, me dit que ce qui a le plus indigné la Bretagne, c\'est le geste d\'Herriot supprimant à Paris la chaire de breton. L\'âme de la Bretagne, c\'est sa langue.'), (11, 'Mémoires d\'outre-tombe (1848), Partie 3, Livre 31, Chapitre 1 de François René, vicomte de Chateaubriand', 'Les pieds me brûlaient à Paris, je ne pouvais m\'habituer au ciel gris et triste de la France, ma patrie; qu\'aurais-je donc pensé du ciel de la Bretagne, ma matrie, pour parler grec?'), (12, 'Extraits historiques de Jules Michelet', 'La pauvre et dure Bretagne, l\'élément résistant de la France, étend ses champs de quartz et de schiste depuis les ardoisières de Châteaulin près Brest jusqu\'aux ardoisières d\'Angers.'), (13, 'Proverbes Bretons', 'Comme la grêle dans la mer, les Anglais fondent en Bretagne.'), (14, 'Proverbes Bretons', 'Ô Bretagne ! ô très beau pays ! Bois au milieu, mer à l’entour !'), (15, 'De Ronan Le Coadic / L\'identité bretonne ', 'Les eaux bretonnes ne sont pas les plus chaudes, mais de là à vouloir les chauffer au fuel régulièrement !'); -- -------------------------------------------------------- -- -- Structure de la table `contact` -- DROP TABLE IF EXISTS `contact`; CREATE TABLE IF NOT EXISTS `contact` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(256) NOT NULL, `prenom` varchar(256) NOT NULL, `message` text NOT NULL, `mail` varchar(256) NOT NULL, `dateJour` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `contact` -- INSERT INTO `contact` (`id`, `nom`, `prenom`, `message`, `mail`, `dateJour`) VALUES (15, 'Morillon', 'Chloé', 'Pouvez-vous nous contacter ? nous aimeroins louer la maison pour Noël ? merci', 'guillaume.morillon@gmx.fr', '2019-07-24'), (14, 'Morillon', 'Guillaume', 'Est-il possible de venir avec un chat ?', 'guillaume.morillon@gmx.fr', '2019-07-24'); -- -------------------------------------------------------- -- -- Structure de la table `fichier_client` -- DROP TABLE IF EXISTS `fichier_client`; CREATE TABLE IF NOT EXISTS `fichier_client` ( `id` int(11) NOT NULL AUTO_INCREMENT, `nom` varchar(256) NOT NULL, `prenom` varchar(256) NOT NULL, `adresse` varchar(256) NOT NULL, `code_postal` int(11) NOT NULL, `ville` varchar(256) NOT NULL, `telephone` int(11) NOT NULL, `mail` varchar(256) NOT NULL, `semaine_resa` int(11) NOT NULL, `info_particuliere` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `fichier_client` -- INSERT INTO `fichier_client` (`id`, `nom`, `prenom`, `adresse`, `code_postal`, `ville`, `telephone`, `mail`, `semaine_resa`, `info_particuliere`) VALUES (1, 'Morillon', 'Guillaume', 'L\'ancienne Gare', 35310, 'Saint-thurial', 611153406, 'guillaumemorillon@free.fr', 45, 'J\'aime les chats'), (6, 'Dubois', 'Jean-Luc', 'Ricourtel', 56800, 'Ploërmel', 611153406, 'jldubois@free.fr', 46, '2 personnes dans la maison'); -- -------------------------------------------------------- -- -- Structure de la table `reponse_avis` -- DROP TABLE IF EXISTS `reponse_avis`; CREATE TABLE IF NOT EXISTS `reponse_avis` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_avis` int(11) NOT NULL, `auteur` varchar(256) NOT NULL, `reponse` text NOT NULL, `date_reponse` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `reponse_avis` -- INSERT INTO `reponse_avis` (`id`, `id_avis`, `auteur`, `reponse`, `date_reponse`) VALUES (1, 3, 'Guillaume', 'ceci est une réponse à un avis', '2019-07-08'), (2, 3, 'ooooooooooooooo', 'ooooooooooooooooooo', '2019-07-08'), (3, 3, 'jjjjjjj', 'jjjjjjj', '2019-07-08'), (4, 3, 'kkkkkkkkkk', 'kkkkkkkkkkk', '2019-07-08'), (5, 14, 'Violaine Quéré ', 'merci pour ces remarques', '2019-07-08'), (13, 19, 'Violaine Quéré', 'Merci pour ces remarques ! ', '2019-07-24'), (7, 3, 'violaine', 'commentaire de violaine', '2019-07-09'); -- -------------------------------------------------------- -- -- Structure de la table `reponse_contact` -- DROP TABLE IF EXISTS `reponse_contact`; CREATE TABLE IF NOT EXISTS `reponse_contact` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_contact` int(11) NOT NULL, `nom` varchar(256) NOT NULL, `prenom` varchar(256) NOT NULL, `reponse` text NOT NULL, `email_demandeur` varchar(256) NOT NULL, `date_reponse` date NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; -- -- Déchargement des données de la table `reponse_contact` -- INSERT INTO `reponse_contact` (`id`, `id_contact`, `nom`, `prenom`, `reponse`, `email_demandeur`, `date_reponse`) VALUES (1, 1, 'Quéré', 'Violaine', 'Voici la réponse du message de Guillaume Morillon', 'guillaume.morillon@gmx.fr', '2019-07-18'), (5, 14, 'Quéré ', 'Violaine', 'Bonjour, Malheureusement pour des questions d\'hygiène, nous n\'acceptons pas les animaux.cordialement', 'guillaume.morillon@gmx.fr', '2019-07-24'), (6, 15, 'Quéré Violaine', 'Violaine', 'Bonjour,\r\nVous pouvez sans problème louer la maison cette semaine.\r\n Je vous recontacte la semaine prochaine pour finaliser la réservation.\r\ncordialement,', 'guillaume.morillon@gmx.fr', '2019-07-24'); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C
UTF-8
1,157
3.75
4
[]
no_license
/** * generate.c * * Generates pseudorandom numbers in [0,MAX), one per line. * * Usage: generate n [s] * * where n is number of pseudorandom numbers to print * and s is an optional seed */ #define _XOPEN_SOURCE #include <cs50.h> #include <stdio.h> #include <stdlib.h> #include <time.h> // upper limit on range of integers that can be generated #define LIMIT 65536 int main(int argc, string argv[]) { // TODO: if the command line doesn't have two strings after ./generate.c, it boots out. if (argc != 2 && argc != 3) { printf("Usage: ./generate n [s]\n"); return 1; } // TODO: changes the value in argv[1] into an integor. int n = atoi(argv[1]); // TODO: if there's a second integor in the command line, use it in tendem with srand, otherwise use the value time(NULL) if (argc == 3) { srand48((long) atoi(argv[2])); } else { srand48((long) time(NULL)); } // TODO: prints random numbers until it meets the quota set in argv[1] for (int i = 0; i < n; i++) { printf("%i\n", (int) (drand48() * LIMIT)); } // success return 0; }
Java
UTF-8
5,911
1.546875
2
[]
no_license
package com.arteriatech.emami.mbo; import java.io.Serializable; /** * Created by e10526 on 06-07-2018. */ public class InvoiceCreateBean implements Serializable { String CPNo = ""; String PaymentModeID = ""; String CPGUID32 = ""; String ParentTypeID = ""; String ParentName = ""; String comingFrom = ""; String ParentID = ""; String SpNo = ""; String SpFirstName = ""; String RouteSchGuid = ""; String PODate = ""; public String getDeliveryPerson() { return DeliveryPerson; } public void setDeliveryPerson(String deliveryPerson) { DeliveryPerson = deliveryPerson; } String DeliveryPerson = ""; public String getVehicleNo() { return VehicleNo; } public void setVehicleNo(String vehicleNo) { VehicleNo = vehicleNo; } String VehicleNo = ""; public String getDriverName() { return DriverName; } public void setDriverName(String driverName) { DriverName = driverName; } public String getDriverMobile() { return DriverMobile; } public void setDriverMobile(String driverMobile) { DriverMobile = driverMobile; } String DriverName = ""; String DriverMobile = ""; public String getPODate() { return PODate; } public void setPODate(String PODate) { this.PODate = PODate; } public String getPONo() { return PONo; } public void setPONo(String PONo) { this.PONo = PONo; } String PONo = ""; public String getSSSoGuid() { return SSSoGuid; } public void setSSSoGuid(String SSSoGuid) { this.SSSoGuid = SSSoGuid; } String SSSoGuid = ""; String DeviceNo = ""; String cpUID = ""; public DmsDivQryBean getDmsDivQryBean() { return dmsDivQryBean; } public void setDmsDivQryBean(DmsDivQryBean dmsDivQryBean) { this.dmsDivQryBean = dmsDivQryBean; } DmsDivQryBean dmsDivQryBean = null; public String getDmsDivision() { return DmsDivision; } public void setDmsDivision(String dmsDivision) { DmsDivision = dmsDivision; } public String getDmsDivisionDesc() { return DmsDivisionDesc; } public void setDmsDivisionDesc(String dmsDivisionDesc) { DmsDivisionDesc = dmsDivisionDesc; } String DmsDivision = ""; String DmsDivisionDesc = ""; public String getMatQry() { return matQry; } public void setMatQry(String matQry) { this.matQry = matQry; } String matQry = ""; public String getDelDate() { return DelDate; } public void setDelDate(String delDate) { DelDate = delDate; } String DelDate = ""; public String getComingFrom() { return comingFrom; } public void setComingFrom(String comingFrom) { this.comingFrom = comingFrom; } public String getCpUID() { return cpUID; } public void setCpUID(String cpUID) { this.cpUID = cpUID; } public String getDeviceNo() { return DeviceNo; } public void setDeviceNo(String deviceNo) { DeviceNo = deviceNo; } public String getParentName() { return ParentName; } public void setParentName(String parentName) { ParentName = parentName; } public String getParentTypeID() { return ParentTypeID; } public void setParentTypeID(String parentTypeID) { ParentTypeID = parentTypeID; } public String getRouteSchGuid() { return RouteSchGuid; } public void setRouteSchGuid(String routeSchGuid) { RouteSchGuid = routeSchGuid; } public String getCPGUID32() { return CPGUID32; } public void setCPGUID32(String CPGUID32) { this.CPGUID32 = CPGUID32; } public String getBeatGuid() { return BeatGuid; } public void setBeatGuid(String beatGuid) { BeatGuid = beatGuid; } String BeatGuid = ""; public String getCPName() { return CPName; } public void setCPName(String CPName) { this.CPName = CPName; } String CPName = ""; public String getCPTypeID() { return CPTypeID; } public void setCPTypeID(String CPTypeID) { this.CPTypeID = CPTypeID; } String CPTypeID = ""; public String getCurrency() { return Currency; } public void setCurrency(String currency) { Currency = currency; } String Currency = ""; public String getParentID() { return ParentID; } public void setParentID(String parentID) { ParentID = parentID; } public String getSpNo() { return SpNo; } public void setSpNo(String spNo) { SpNo = spNo; } public String getSpFirstName() { return SpFirstName; } public void setSpFirstName(String spFirstName) { SpFirstName = spFirstName; } public String getPaymentModeDesc() { return PaymentModeDesc; } public void setPaymentModeDesc(String paymentModeDesc) { PaymentModeDesc = paymentModeDesc; } String PaymentModeDesc = ""; public String getSPGUID() { return SPGUID; } public void setSPGUID(String SPGUID) { this.SPGUID = SPGUID; } String SPGUID = ""; public String getCPGUID() { return CPGUID; } public void setCPGUID(String CPGUID) { this.CPGUID = CPGUID; } String CPGUID = ""; public String getCPNo() { return CPNo; } public void setCPNo(String CPNo) { this.CPNo = CPNo; } public String getPaymentModeID() { return PaymentModeID; } public void setPaymentModeID(String paymentModeID) { PaymentModeID = paymentModeID; } }
Markdown
UTF-8
1,470
2.6875
3
[]
no_license
# Note * Here we are using EC2 and Route53. * NS and SOA records will be present by default. ## Simple Routing Policy * One record with multiple IPs. 1. Note down the IPs of the EC2 instances you wish to use. 2. Goto Services > Route53 > Hosted Zones > Create Record 3. Select Simple routing 4. Configure records > Define simple record * Record name `If you want to allow traffic to main domain then leave it empty if not then mention subdomain name.` * Value/Route traffic to `I chose IP address or another value, depending on the record type for my LAB` * Define simple record * TTL `For clearing IP from DNS cache.` 5. Create records ## Weighted Routing Policy * Splits the traffic based on assigned weights. * You have to repeat from step 4 to 5 because you want to distribute the weight. 1. Note down the IPs of the EC2 instances you wish to use. 2. Goto Services > Route53 > Hosted Zones > Create Record 3. Select Weighted Routing Policy 4. Configure records * Basic configuration * Record name `If you want to allow traffic to main domain then leave it empty if not then mention subdomain name.` * Record type `Choose your record type` * TTL * Weighted records to add to **your_domain** * Define weighted record * Value/Route traffic to `Same as above ` * Mention IP/s to distribute weight. 5. Create records
PHP
UTF-8
1,750
3.4375
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1> Coding exercise </h1> <p>In the following example, we will create an abstract User class and two child classes (Admin and Viewer classes) that inherit from the abstract class.</p> <ol> <li>Create an abstract class with the name of User, which has an abstract method with the name of stateYourRole.</li> <li>Add to the class a protected variable with the name of $username, and public setter and getter methods to set and get the $username.</li> <li>Create an Admin class that inherits the abstract User class.</li> <li>Which method should be defined in the class?</li> <li>Define the method stateYourRole() in the child class and make it return the string “admin”;</li> <li>Create another class, Viewer that inherits the User abstract class. Define the method that should be defined in each child class of the User class.</li> <li>Create an object from the Admin class, set the username to “Balthazar”, and make it return the string “admin”.</li> </ol> <?php /** * */ abstract class User { protected $username; public function setName($n) { $this->username; } public function getName() { return $this->username; } abstract function stateYourRole(); } /** * */ class Admin extends User { function stateYourRole() { return "admin"; } } class Viewer extends User { function stateYourRole() { return "viewer"; } } $usuari = new Admin; $usuari->setname("Basaltar"); echo $usuari->stateYourRole(); ?> </body> </html>
JavaScript
UTF-8
1,300
4.125
4
[]
no_license
/** * 寄生式继承 继承原型 * 传递参数 subClass 子类 * 传递参数 superClass 父类 */ function inheritObject(o){ //声明一个过渡函数 function F(){} //过渡对象的原型继承父对象 F.prototype = o; return new F(); } function inheritPrototype(subClass,superClass){ //复制一份父类的原型副本保存在变量 var p = inheritObject(superClass.prototype); //修正因为重写子类原型导致子类的constructor指向父类 p.constructor = subClass; //设置子类的原型 subClass.prototype = p; } //定义父类 function SuperClass(name){ this.name = name; this.colors = ['red','blue']; } //定义父类原型方法 SuperClass.prototype.getName = function(){ return this.name; } //定义子类 function SubClass(name,time){ //构造函数继承 SuperClass.call(this,name); //子类新增属性 this.time = time; } //寄生式继承父类原型 inheritPrototype(SubClass,SuperClass); //子类新增原型方法 SubClass.prototype.getTime =function(){ return this.time; } var test1 = new SubClass('js book',2014); var test2 = new SubClass('csc book',2013); test1.colors.push('black'); console.log(test1.colors); //['red','blue','black'] console.log(test2.colors); //['red','blue'] console.log(test2.getName()); console.log(test2.getTime());
Java
UTF-8
479
2.46875
2
[]
no_license
import javax.swing.JFrame; public class ApplicationMain extends JFrame { public ApplicationMain(){ AsciiPanel panel = new AsciiPanel(80, 24); add(panel); GuiController gui = new GuiController(panel, new PlayerController(null)); addKeyListener(gui); gui.startScreen(); } static public void main(String argv[]) { ApplicationMain app = new ApplicationMain(); app.pack(); app.setVisible(true); } }
Java
UTF-8
1,327
2.671875
3
[]
no_license
import java.awt.Color; import java.awt.Font; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; public class RegistrationComplete extends GUIDesign { JLabel stringLabel; String[] columns = { "Course Code", "Title", "Section", "Mode of Grading" }; int courses; Object[][] data; JTable table; JPanel termPanel = new JPanel(); JPanel departmentPanel = new JPanel(); JButton homeButton = new JButton("Go to Homepage"); public RegistrationComplete() { super("Registration Complete", 3); setLayout(new BoxLayout(this, 3)); header = new JPanel(); header.setSize(getWidth(), 30); body = new JPanel(); body.setLayout(new BoxLayout(body, 1)); header.setBackground(Color.yellow); title.setFont(new Font("Helvetica", 1, 20)); header.add(title); stringLabel = new JLabel("You have registered for the following courses"); data = new Object[10][4]; table = new JTable(data, columns); termPanel.add(stringLabel); body.add(termPanel); body.add(departmentPanel); body.add(table.getTableHeader()); body.add(table); buttonPanel.add(homeButton); add(header); add(body); add(buttonPanel); } }
C
UHC
2,361
4
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> // 丮 ϱ int factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); } // x n ϱ double power(int x, int n) { if (n == 0) return 1; else return (double)x * (double)power(x, n - 1); } // Ǻġ ϱ int fibonacci(int n) { if (n < 2) return n; else return fibonacci(n - 1) + fibonacci(n - 2); } // ִ ϱ int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a%b); } // ڿ ϱ int length(char *str) { if (*str == '\0') return 0; else return 1 + length(str + 1); } // ڿ ϱ void printChars(char *str) { if (*str == '\0') return; else { printf("%c", *str); printChars(str + 1); } } // ڿ Ųٷ ϱ void printCharsReverse(char *str) { if (*str == '\0') return; else { printCharsReverse(str + 1); printf("%c", *str); } } // Žϱ int search(int data[], int n, int target) { if (n <= 0) return -1; else if (target == data[n - 1]) return n - 1; else return search(data, n - 1, target); } int MAX(int a, int b) { if (a < b) { return b; } else { return a; } } // ִ밪 ã int findMax(int n, int data[]) { if (n == 1) return data[0]; else return MAX(data[n - 1], findMax(n - 1, data)); } // ϱ void printInBinary(int n) { if (n < 2) printf("%d", n); else { printInBinary(n / 2); printf("%d", n % 2); } } int main() { srand(time(NULL)); int data[20]; data[14] = 3; int data2[5]; for (int i = 0; i < 5; i++) { int num = (rand() % 60) + 1; data2[i] = num; } printf("丮 ϱ \t: %d\n", factorial(5)); printf("x n ϱ \t\t: %.f\n", power(3, 4)); printf("Ǻġ ϱ \t: %d\n", fibonacci(15)); printf("ִ ϱ \t: %d\n", gcd(50, 4)); printf("ڿ ϱ \t: %d\n", length("hhhhhhh")); printf("ڿ ϱ \t: "); printChars("Hello"); printf("\nڿ Ųٷ ϱ \t: "); printCharsReverse("Hello"); printf("\n Žϱ \t\t: %d\n", search(data, 20, 3)); printf("ִ밪 ã(1~60) \t: %d \n", findMax(5, data2)); printf(" ϱ \t: "); printInBinary(555); }
Python
UTF-8
1,805
3
3
[]
no_license
''' find underrated businesses - have a low average review, but only because reviewers of that business tended to be harsher critics ''' from objects import * from networkx import * from helpers import * import load_data import re def run(): businesses = load_data.load_objects("business") users = load_data.load_objects("user") reviews = load_data.load_objects("review", 100000) business_dict = {} for b in businesses: business_dict[b.business_id] = b user_dict = {} for u in users: user_dict[u.user_id] = u # user gave 4.5, usually gives 3 b_dict = {} # business -> (total_reviewer_plus_or_minus, num_reviews_seen) for review in reviews: if review.business_id not in business_dict or review.user_id not in user_dict: continue b = business_dict[review.business_id] u = user_dict[review.user_id] diff = review.stars - u.average_stars if b in b_dict: b_dict[b] = (b_dict[b][0] + diff, b_dict[b][1] + 1) else: b_dict[b] = (diff, 1) normalized_businesses = [] for b in b_dict: diff, count = b_dict[b] if count > 1: new_rating = b.stars + diff normalized_businesses += [(b, new_rating, count)] normalized_businesses = sorted(normalized_businesses, key=lambda t: t[1], reverse=True) print "\n\nunderrated businesses" for b, rating, count in normalized_businesses[:20]: print '{:<80}'.format(str(b)), "\t\t\t", rating, "\t\t\t", count, "/", b.review_count, "\t\t\t", b.stars print "\n\noverrated businesses" for b, rating, count in normalized_businesses[-20:]: print '{:<80}'.format(str(b)), "\t\t\t", rating, "\t\t\t", count, "/", b.review_count, "\t\t\t", b.stars run()
Python
UTF-8
1,005
4.0625
4
[]
no_license
# 给定一个序列[1, 2, 3, ... , n],其长度为n(n为1至9),给定一个数k(k为1至n!),输出该序列全排列中的第k个序列 # Input: n = 4, k = 9 # Output: 2314 # 思路: # 首位数每个数字重复次数为(n - 1)! # 第二位数每个数字重复次数为(n - 2)! # ...... # 末位数字每个数字重复次数为1 # 用除法和取余操作上述步骤,放弃减法和乘法!!! import math class Solution: def getPermutation(self, n, k): fact = [1] * n nums = [x for x in range(1, n + 1)] result = [] for i in range(1, n): fact[i] = fact[i - 1] * i i = n while i > 0: j = k / fact[i - 1] k = k % fact[i - 1] j = math.ceil(j) result.append(nums[j - 1]) nums.pop(j - 1) i = i - 1 return result if __name__ == '__main__': n = 4 k = 9 s = Solution() result = s.getPermutation(n, k) print(result)
PHP
UTF-8
3,083
2.59375
3
[]
no_license
<?php class Admin_model extends CI_Model{ public function can_login($email, $password) { $this->db->where('email', $email); $this->db->where('password', $password); $query = $this->db->get('users'); if($query->num_rows() > 0) { return true; } else { return false; } } public function all_books(){ $query=$this->db->select('books.id,books.name as book_name,authors.name as author_name,genres.name as genre_name,books.description,books.publication_date,books.ISBN,books.cover') ->from('books') ->join('authors','authors.id=books.author_id') ->join('genres','genres.id=books.genre_id') ->get(); $result = $query->result(); return $result; } public function all_authors(){ $query=$this->db->select('*') ->from('authors') ->get(); $result = $query->result(); return $result; } public function all_genres(){ $query=$this->db->select('*') ->from('genres') ->get(); $result = $query->result(); return $result; } public function count_books(){ return $num_results = $this->db->count_all_results('books'); } public function count_authors(){ return $num_results = $this->db->count_all_results('authors'); } public function count_genres(){ return $num_results = $this->db->count_all_results('genres'); } public function add_book($data){ $this->db->insert('books',$data); redirect('/Admin/all_books'); } public function add_author($data){ $this->db->insert('authors',$data); redirect('/Admin/all_authors'); } public function add_genre($data){ $this->db->insert('genres',$data); redirect('/Admin/all_genres'); } public function update_run($id, $data){ $book_id = $id; foreach($data as $key => $item){ if($item == null){ unset($data[$key]); } else { $data[$key] = $item; } } $this->db->where('id', $book_id); $this->db->update('books',$data); redirect('/Admin/all_books'); } public function update_book($id){ $detail=$this->db->select('books.id,books.name as book_name,authors.name as author_name,genres.name as genre_name,books.description,books.publication_date,books.ISBN,books.cover,books.quote,books.quote_2,books.quote_3') ->from('books') ->join('authors','authors.id = books.author_id') ->join('genres','genres.id = books.genre_id') ->where('books.id',$id) ->get(); $books = $detail->result(); return $books; } }
C#
UTF-8
517
2.515625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; public class Session { private static Session _instance = null; public static Session Instance { get { if (_instance == null) _instance = new Session(); return _instance; } } private Partie _partie; public Partie Partie { get { return _partie; } set { _partie = value; } } private Session() { _partie = null; } }
Java
UTF-8
1,309
2.984375
3
[]
no_license
package com.hrms.practice; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class JdbsTask1Way2 { // retrieve all data, store in array list and retrieve from the ArrayList one by // one String userName = "syntax_hrm"; String password = "syntaxhrm123"; String dbURL = "jdbc:mysql://54.167.125.15:3306/syntaxhrm_mysql"; @Test public void retrieveAllJobTitles() throws SQLException { List<String> job_titles = new ArrayList<>(); // get collection method Connection connection = DriverManager.getConnection(dbURL, userName, password); // create an object of the statement class Statement st = connection.createStatement(); // execute the query ResultSet rset = st.executeQuery("select * from ohrm_job_title"); while (rset.next()) { job_titles.add(rset.getString("job_title")); } System.out.println(job_titles); //or for loop, bc? why not! for(String data:job_titles) { System.out.println(data); } rset.close(); st.close(); connection.close(); } }
JavaScript
UTF-8
4,673
2.59375
3
[]
no_license
/** * Bootstrap * (sails.config.bootstrap) * * An asynchronous bootstrap function that runs just before your Sails app gets lifted. * > Need more flexibility? You can also do this by creating a hook. * * For more information on bootstrapping your app, check out: * https://sailsjs.com/config/bootstrap */ module.exports.bootstrap = async function (done) { // By convention, this is a good place to set up fake data during development. // // For example: // ``` // // Set up fake development data (or if we already have some, avast) // if (await User.count() > 0) { // return done(); // } // // await User.createEach([ // { emailAddress: 'ry@example.com', fullName: 'Ryan Dahl', }, // { emailAddress: 'rachael@example.com', fullName: 'Rachael Shaw', }, // // etc. // ]); // ``` sails.getInvalidIdMsg = function (opts) { if (opts.id && isNaN(parseInt(opts.id))) { return "Primary key specfied is invalid (incorrect type)."; } if (opts.fk && isNaN(parseInt(opts.fk))) { return "Foreign key specfied is invalid (incorrect type)."; } return null; // falsy } sails.bcrypt = require('bcryptjs'); const saltRounds = 10 const hash = await sails.bcrypt.hash('123456', saltRounds); await User.createEach([ { "username": "admin", "password": hash, "role":"admin" }, { "username": "student0", "password": hash,"role":"student" }, { "username": "student1", "password": hash,"role":"student" }, { "username": "student2", "password": hash,"role":"student" }, // etc. ]); await Event.createEach([ { "eventname": "A simple event", "shortdescription": "This is an innitial event", "fulldescription": "This event is saved in bootstrap.js", "imageurl": "https://seanwes.com/wp-content/uploads/2013/06/simple.jpg", "organizer": "Department of Computer Science", "eventdate": "11/26/2018", "time": "3:00", "venue": "POD", "quota": "123", "highlight": "Highlighted Event", }, { "eventname": "A complex event", "shortdescription": "This is an innitial event", "fulldescription": "This event is saved in bootstrap.js", "imageurl": "http://www.abc.net.au/reslib/201401/r1222464_16033207.JPG", "organizer": "Department of Music", "eventdate": "11/26/2018", "time": "3:00", "venue": "POD", "quota": "123", "highlight": "Highlighted Event", }, { "eventname": "A simple event copy", "shortdescription": "This is an innitial event", "fulldescription": "This event is saved in bootstrap.js", "imageurl": "https://pic1.zhimg.com/80/v2-40b17763b4eb99ed91c3be971516cc98_hd.jpg", "organizer": "Department of Computer Science", "eventdate": "11/26/2018", "time": "3:00", "venue": "SWT501", "quota": "123", "highlight": "", }, { "eventname": "A complex event copy", "shortdescription": "This is an innitial event", "fulldescription": "This event is saved in bootstrap.js", "imageurl": "https://pic1.zhimg.com/80/v2-40b17763b4eb99ed91c3be971516cc98_hd.jpg", "organizer": "Department of Music", "eventdate": "11/26/2018", "time": "3:00", "venue": "SWT501", "quota": "123", "highlight": "", }, // etc. ]); const sim = await Event.findOne({ eventname: "A simple event" }); const simc = await Event.findOne({ eventname: "A simple event copy" }); const com = await Event.findOne({ eventname: "A complex event" }); const comc = await Event.findOne({ eventname: "A complex event copy" }); const student0 = await User.findOne({ username: "student0" }); const student1 = await User.findOne({ username: "student1" }); const student2 = await User.findOne({ username: "student2" }); await User.addToCollection(student0.id, 'register').members(com.id); await User.addToCollection(student0.id, 'register').members(simc.id); await User.addToCollection(student0.id, 'register').members(comc.id); await User.addToCollection(student1.id, 'register').members(com.id); await User.addToCollection(student1.id, 'register').members(simc.id); await User.addToCollection(student1.id, 'register').members(comc.id); await User.addToCollection(student2.id, 'register').members(com.id); await User.addToCollection(student2.id, 'register').members(simc.id); await User.addToCollection(student2.id, 'register').members(comc.id); // Don't forget to trigger `done()` when this bootstrap function's logic is finished. // (otherwise your server will never lift, since it's waiting on the bootstrap) return done(); };
Python
UTF-8
4,556
2.953125
3
[ "BSD-3-Clause", "CC-BY-4.0" ]
permissive
# SPDX-FileCopyrightText: 2021 Lukas Schrangl <lukas.schrangl@tuwien.ac.at> # # SPDX-License-Identifier: BSD-3-Clause import math from typing import Optional, Union from PyQt5 import QtCore, QtGui, QtQml, QtQuick import numpy as np class PyImage(QtQuick.QQuickPaintedItem): """QtQuick item that displays an image from Python-supplied data Works for single-channel (grayscale) data only. Black and white points can be set via :py:attr:`black` and :py:attr:`white` properties, respectively. """ def __init__(self, parent: Optional[QtQuick.QQuickItem] = None): """Parameters ---------- parent Parent item. """ super().__init__(parent) self._source = None self._qImage = None self._qImageData = None # Raw data needs to be kept for QImage self._black = 0.0 self._white = 1.0 blackChanged = QtCore.pyqtSignal(float) """Black point changed""" @QtCore.pyqtProperty(float, notify=blackChanged) def black(self) -> float: """Black point. Every pixel with a value less than or equal to this will be displayed black. """ return self._black @black.setter def black(self, b: float): if math.isclose(self._black, b): return self._black = b self.blackChanged.emit(b) self._sourceToQImage() whiteChanged = QtCore.pyqtSignal(float) @QtCore.pyqtProperty(float, notify=whiteChanged) def white(self) -> float: """White point. Every pixel with a value greater than or equal to this will be displayed white. """ return self._white @white.setter def white(self, w: float): if math.isclose(self._white, w): return self._white = w self.whiteChanged.emit(w) self._sourceToQImage() sourceChanged = QtCore.pyqtSignal(QtCore.QVariant) """Source image data changed""" @QtCore.pyqtProperty(QtCore.QVariant, notify=sourceChanged) def source(self) -> Union[np.ndarray, None]: """Image data array. For now, only single-channel (grayscale) data are supported. """ return self._source @source.setter def source(self, data: Union[np.ndarray, None]): if self._source is data: return self._source = data self.sourceChanged.emit(self._source) self.sourceWidthChanged.emit(self.sourceWidth) self.sourceHeightChanged.emit(self.sourceHeight) self._sourceToQImage() def _sourceToQImage(self): """Create QImage instance from source respecting black and white points This sets self._qImage, self._qImageData and triggers a repaint. """ if self._source is None: self._qImage = None self._qImageData = None self.update() return if math.isclose(self._black, self._white): img = np.zeros_like(self._source, dtype=np.uint8) else: img = (self._source - self._black) / (self._white - self._black) img = np.clip(img, 0.0, 1.0) * 255 img = img.astype(np.uint8) self._qImageData = img.tobytes() # Rescue from garbage collector self._qImage = QtGui.QImage(self._qImageData, img.shape[1], img.shape[0], img.shape[1], QtGui.QImage.Format_Grayscale8) self.update() def paint(self, painter: QtGui.QPainter): if self._qImage is None: return # Maybe use self._qImage.scaled(), which would allow to specifiy # whether to do interpolation or not? painter.drawImage(QtCore.QRectF(0, 0, self.width(), self.height()), self._qImage, QtCore.QRectF(0, 0, self.sourceWidth, self.sourceHeight)) sourceWidthChanged = QtCore.pyqtSignal(int) """Width of the image changed.""" @QtCore.pyqtProperty(int, notify=sourceWidthChanged) def sourceWidth(self) -> int: """Width of the image.""" return self._source.shape[1] if self._source is not None else 0 sourceHeightChanged = QtCore.pyqtSignal(int) """Height of the image changed.""" @QtCore.pyqtProperty(int, notify=sourceHeightChanged) def sourceHeight(self) -> int: """Height of the image.""" return self._source.shape[0] if self._source is not None else 0 QtQml.qmlRegisterType(PyImage, "SdtGui", 0, 1, "PyImage")
Python
UTF-8
749
2.921875
3
[]
no_license
from threading import current_thread class CurrentRequest(object): ''' get_request can also be staticmethod ''' _request_dict = {} @classmethod def get_request(cls): try: return cls._request_dict[current_thread()] except KeyError: return None def process_request(self, request): CurrentRequest._request_dict[current_thread()] = request def process_response(self, request, response): thread = current_thread() try: # delete the request before sending response del CurrentRequest._request_dict[thread] except KeyError: pass return response def get_current_request(): return CurrentRequest.get_request()
PHP
UTF-8
1,868
3.09375
3
[]
no_license
<?php class user { /* CREATE TABLE IF NOT EXISTS user ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(390) NOT NULL, pass VARCHAR(390) NOT NULL, register VARCHAR(390) NOT NULL, role ENUM("watcher", "writer", "wizard")) */ public $name; public $pass; public $role; function __construct($name = '', $pass = '', $role = '') { $this->name = $name; $this->pass = $pass; $this->role = $role; } public function getList() { $connect = new connection(); $result = $connect->db->query('SELECT * FROM user'); $response = array(); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $response[] = $row; } } return $response; } public function getOne() { $connect = new connection(); $username = $connect->db->real_escape_string($this->name); $result = $connect->db->query('SELECT * FROM user WHERE name = "'.$name.'"'); if ($result && $result->num_rows > 0) { return $result->fetch_assoc(); } else { return false; } } public function auth() { $connect = new connection(); $name = $connect->db->real_escape_string($this->name); $pass = $connect->db->real_escape_string($this->pass); $result = $connect->db->query('SELECT * FROM user WHERE name = "'.$name.'" AND pass = "'.$pass.'"'); if ($result->num_rows > 0) { $_SESSION['user'] = json_encode($result->fetch_assoc()); return true; } return false; } }
TypeScript
UTF-8
4,910
3.015625
3
[ "ISC" ]
permissive
declare var require; export class DateUtilities { public static locale = require('../locale/en.json');; public static loadLocale(locale): void { this.locale = locale; //this.locale = require("i18n!./locale/ru.json"); // this.locale = require('bundle?name=[path][name].[ext]!./locale/' + name + '.json'); // require.ensure([], function(require){ // this.locale = require('./locale/' + name + '.json'); // }); // const req = require.context('bundle?lazy&name=/dist/locale/lll!./locale/!./pages', // true, // Load files recursively. Pass false to skip recursion. // /^\.\/.*\.json$/ // Match files ending with .json. // ); } /** * Add zero before value if value.length < length */ public static pad(value: string, length: number) { while (value.length < length) value = "0" + value; return value; } /** * Clonning date */ public static clone(date: Date) { // getFullYear - get year // getMonth - get month // getDate - get day of the month // ... return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()); } /** * Format date */ public static formatDate(date: Date) { let format = this.locale.format; format = format.replace(/dd/g, DateUtilities.pad(date.getDate().toString(), 2)); format = format.replace("MM", DateUtilities.pad((date.getMonth() + 1).toString(), 2)); format = format.replace("YYYY", date.getFullYear().toString()); format = format.replace("HH", DateUtilities.pad(date.getHours().toString(), 2)); format = format.replace("mm", DateUtilities.pad(date.getMinutes().toString(), 2)); return format;//date.getFullYear() + "-" + DateUtilities.pad((date.getMonth() + 1).toString(), 2) + "-" + DateUtilities.pad(date.getDate().toString(), 2); } /** * Format UTC date */ public static formatDateUTC(date: Date) { let format = this.locale.format; format = format.replace(/dd/g, DateUtilities.pad(date.getUTCDate().toString(), 2)); format = format.replace("MM", DateUtilities.pad((date.getUTCMonth() + 1).toString(), 2)); format = format.replace("YYYY", date.getUTCFullYear().toString()); format = format.replace("HH", DateUtilities.pad(date.getUTCHours().toString(), 2)); format = format.replace("mm", DateUtilities.pad(date.getUTCMinutes().toString(), 2)); return format;//date.getFullYear() + "-" + DateUtilities.pad((date.getMonth() + 1).toString(), 2) + "-" + DateUtilities.pad(date.getDate().toString(), 2); } /** * Convert day of the date to String */ public static toDayOfMonthString(date: Date) { return DateUtilities.pad(date.getDate().toString(), 0); } /** * Get month of the date */ public static toMonthString(date) { return this.locale.months[date.getMonth()]; } /** * Get year of the date */ public static toYearString(date) { return date.getFullYear().toString(); } /** * Get hours of the date */ public static toHoursString(date) { return DateUtilities.pad(date.getHours().toString(), 2); } /** * Get minutes of the date */ public static toMinutesString(date) { return DateUtilities.pad(date.getMinutes().toString(), 2); } /** * Get day of the week at number the "dayOfWeek", start from the "date" an dgo to the last */ public static moveToDayOfWeek(date: Date, dayOfWeek: number) { while (DateUtilities.getDayOfWeekWithLocal(date) !== dayOfWeek) date.setDate(date.getDate() - 1); return date; } /** * Get day of the week with "locale" */ public static getDayOfWeekWithLocal(date: Date): number { // date.getDay() returns number of day of a week starting from Sunday – 0, Monday – 1, Tuesday – 2 let currentDayOfWeek = date.getDay(); if (this.locale.name === 'ru') { switch (currentDayOfWeek) { case 0: currentDayOfWeek = 6; break; default: currentDayOfWeek = currentDayOfWeek - 1; break; } } return currentDayOfWeek; } public static isSameDay(first, second) { return first.getFullYear() === second.getFullYear() && first.getMonth() === second.getMonth() && first.getDate() === second.getDate(); } public static isBefore(first, second) { return first.getTime() < second.getTime(); } public static isAfter(first, second) { return first.getTime() > second.getTime(); } };
Java
UTF-8
1,055
2.4375
2
[]
no_license
package com.example.barungsofthomehwrk.repository.customer; import com.example.barungsofthomehwrk.model.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class CustomerRepositoryImpl implements CustomerRepository { private final CrudCustomerRepository crudCustomerRepository; @Autowired public CustomerRepositoryImpl(CrudCustomerRepository crudCustomerRepository) { this.crudCustomerRepository = crudCustomerRepository; } @Override public boolean isCustomer(String customerId) { return crudCustomerRepository.exists(customerId); } @Override public List<Customer> getAllCustomers() { return crudCustomerRepository.findAll(); } @Override public Customer save(Customer customer) { return crudCustomerRepository.save(customer); } @Override public Customer getCustomerById(String id) { return crudCustomerRepository.findOne(id); } }
PHP
UTF-8
1,901
2.90625
3
[]
no_license
<?php namespace UACapabilities; use Symfony\Component\Yaml\Yaml; class Translator { private $yamlParser; public function __construct() { $this->yamlParser = new Yaml(); } public function translate($yamlRegexData) { $data = $this->yamlParser->parse($yamlRegexData); $data = $this->transformRegexes($data); $data = $this->changeKeyCaseRecursive($data); return $data; } private function changeKeyCaseRecursive(array $arr) { return array_map(function($item){ if(is_array($item)) $item = $this->changeKeyCaseRecursive($item); return $item; }, array_change_key_case($arr, CASE_LOWER)); } private function transformRegexes(array $data) { foreach($this->findNestedByKey($data, 'regexes') as $keys) { $ref = &$data; foreach($keys as $key) { $ref = &$ref[$key]; } $newItem = array(); foreach($ref as $regex) { $newItem[json_encode(array_intersect_key($regex, ['regex' => 1, 'regex_not' => 1]))] = $regex; } $ref = $newItem; } return $data; } private function findNestedByKey(array $items, $search) { $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($items), \RecursiveIteratorIterator::SELF_FIRST); $foundKeys = array(); foreach($iterator as $key => $item) { if($key === $search) { $keys = array(); for ($i = 0; $i < $iterator->getDepth(); $i++) { $keys[] = $iterator->getSubIterator($i)->key(); } $keys[] = $key; $foundKeys[] = $keys; } } return $foundKeys; } }
C
UTF-8
1,820
4.03125
4
[]
no_license
// 피보나치 검색 // 정렬된 데이터에서 피보나치(Fibonacci) 수열을 이용하는 방법. 피보나치수열이란 F(0) = 0, F(1) = 1, (F2) = F(0) + F(1), ... , F(i) = F(i-2)+F(i-1) // 즉 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... /* [검색 순서] (1) fiboNum[k]<n을 만족하는 가장 큰 k를 구한다. (2) 비교위치(pos) = index + fiboNum[--k] //index 초기값은 0 (3) pos 위치에 찾을 값이 있으면 완료 (4) pos가 찾을 범위를 벗어나거나 pos 위치의 값보다 찾을 값이 작으면 (2) 수행 pos 위치의 값보다 찾을 값이 크면 index는 pos로 변경, k는 1 감소 후 (2) 수행 (5) k=0 일 때까지 (3)을 만나지 못하면 '없는 데이터' */ #include <stdio.h> #include <limits.h> int fiboSearch(int a[], int n, long s_value){ int index = 0, pos, k = 0; static int fibo[] = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6465, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811,39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 183611903, INT_MAX}; while(fibo[k]<n) k++; while(k>0){ pos = index + fibo[--k]; if(pos>=n||s_value<a[pos]); else if(s_value>a[pos]){ //찾고자 하는 값이 큰 경우 index = pos; k--; } else return pos; } return -1; } int main(void){ int a[] = {5, 12, 17, 20, 25, 33, 38, 41, 59, 65, 68, 70, 75, 87, 92, 95, 99}; int n, search_data, i, pos; n = sizeof(a)/sizeof(int); for(i=0; i<n; i++){ printf("%d ", a[i]); printf("\n"); printf("찾고자 하는 값 입력 : "); scanf_s("%d", &search_data); pos = fiboSearch(a, n, search_data); if(pos>=0) printf("\nfound %d at %d\n", search_data, pos); else printf("\nnot found.\n"); return 0; }
Python
UTF-8
668
3.328125
3
[]
no_license
class Solution: """ 1. j starts from 1 2. whenever does a write at j, move j to the next """ def compress(self, chars: List[str]) -> int: count, j = 0, 1 for i, c in enumerate(chars): if i > 0 and c != chars[i - 1]: if count > 1: for n in str(count): chars[j] = n j += 1 chars[j] = c j += 1 count = 1 else: count += 1 if count > 1: for n in str(count): chars[j] = n j += 1 return j
JavaScript
UTF-8
986
2.640625
3
[]
no_license
'use strict' var sentence = require('./sentence'); var maths = require('./maths.js'); var request = require('request'); var http = require('http'); var md5 = require('md5'); var server = http.createServer(function(req, res){ var params = req.url.split('/'); var operatorID = params[1]; // console.log('params:', params); var response; switch (operatorID) { case 'gravatar': var emailAddress = params[2]; var hash = md5(emailAddress); response = "http://www.gravatar.com/avatar/" + hash; break; case 'math': var mathVars = params.slice(3); // console.log(mathVars); response = maths.maths(params[2], mathVars); break; case 'sentence': response = sentence.sentence(params[2]); break; } res.write(response + '\n'); res.end(); }); server.listen(3000); // request('http://www.google.com', function (error, response, body) { // if (!error && response.statusCode == 200) { // // } // })
Java
UTF-8
9,262
2.03125
2
[]
no_license
package com.example.sina.specificcontact; import android.app.ActivityOptions; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Objects; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { static Context context; Typeface font_Medium; Typeface font_Bold; boolean isExit; public static Boolean currentUser; public static Dialog ActivityDialogInternetConnection; @Override public void onStart() { Log.d("looog", "onStart: "); try { if (ActivityDialogInternetConnection.isShowing()) ActivityDialogInternetConnection.dismiss(); } catch (Exception e) { e.printStackTrace(); } super.onStart(); isExit=false; Connection(); } @Override protected void onResume() { isExit=false; super.onResume(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(1); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){ View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); } setContentView(R.layout.activity_main); context=getApplicationContext(); font_Medium=Typeface.createFromAsset(MainActivity.context.getAssets(),"fonts/IRANSans_Medium.ttf"); font_Bold=Typeface.createFromAsset(MainActivity.context.getAssets(),"fonts/IRANSans_Bold.ttf"); } public void Connection() { Log.d("loog", "Connection: "); OkHttpClient client = new OkHttpClient(); String url = "http://217.218.215.67:6608/api/api-status"; OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(10, TimeUnit.SECONDS); builder.readTimeout(10, TimeUnit.SECONDS); builder.writeTimeout(10, TimeUnit.SECONDS); Request request = new Request.Builder() .url(url) .build(); client=builder.build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { public void run() { try { if (ActivityDialogInternetConnection.isShowing()) ActivityDialogInternetConnection.dismiss(); } catch (Exception e) { e.printStackTrace(); } if(!isFinishing()) { ActivityDialogShowInternetConnection(); } } }); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ final String myResponce=response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { JSONObject jObject = null; try { jObject = new JSONObject(myResponce); String Status=jObject.getString("status"); if (Status.equals("ok")) { final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void run() { try { if (ActivityDialogInternetConnection.isShowing()) ActivityDialogInternetConnection.dismiss(); } catch (Exception e) { e.printStackTrace(); } if(!isFinishing() && !isExit) { currentUser = getSharedPreferences("PREFERENCE",MODE_PRIVATE).getBoolean("currentUser",false); if (currentUser) { startActivity(new Intent(MainActivity.this, RankActivity.class)); finish(); } else { if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) { ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this); Intent intent = new Intent(MainActivity.this, Authentication.class); startActivity(intent, options.toBundle()); finish(); } else { startActivity(new Intent(MainActivity.this, Authentication.class)); finish(); } } } } }, 3000); } } catch (JSONException e) { e.printStackTrace(); } } }); } } }); } public void ActivityDialogShowInternetConnection() { ActivityDialogInternetConnection=new Dialog(MainActivity.this); ActivityDialogInternetConnection.requestWindowFeature(Window.FEATURE_NO_TITLE); Objects.requireNonNull(ActivityDialogInternetConnection.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); ActivityDialogInternetConnection.getWindow().getAttributes().windowAnimations=R.style.DialogScale; ActivityDialogInternetConnection.setContentView(R.layout.error_connection_dialog); TextView TitleErrorConnectionDialog=(TextView)ActivityDialogInternetConnection.findViewById(R.id.TitleErrorConnectionDialog); TextView TextErrorConnectionDialog=(TextView)ActivityDialogInternetConnection.findViewById(R.id.TextErrorConnectionDialog); TitleErrorConnectionDialog.setTypeface(font_Bold); TextErrorConnectionDialog.setTypeface(font_Medium); ActivityDialogInternetConnection.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){ View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); } Connection(); } }); ActivityDialogInternetConnection.show(); } @Override protected void onStop() { isExit=true; try { if (ActivityDialogInternetConnection.isShowing()) ActivityDialogInternetConnection.dismiss(); } catch (Exception e) { e.printStackTrace(); } super.onStop(); } }
PHP
UTF-8
1,558
2.78125
3
[ "Apache-2.0" ]
permissive
<?php /** * This file is part of amfPHP * * LICENSE * * This source file is subject to the license that is bundled * with this package in the file license.txt. * @package Amfphp__BackOffice_ClientGenerator * */ /** * loads the generators * * @author Ariel Sommeria-klein * @package Amfphp__BackOffice_ClientGenerator */ class Amfphp_BackOffice_ClientGenerator_GeneratorManager { /** * load generators * @param array of strings $generatorFolders */ public function loadGenerators($generatorFolders) { $ret = array(); foreach ($generatorFolders as $generatorFolderRootPath) { if (!is_dir($generatorFolderRootPath)) { throw new Amfphp_Core_Exception('invalid path for loading generator at ' . $generatorFolderRootPath); } $folderContent = scandir($generatorFolderRootPath); foreach ($folderContent as $generatorName) { if (!is_dir($generatorFolderRootPath . '/' . $generatorName)) { continue; } //avoid system folders if ($generatorName[0] == '.') { continue; } if (!class_exists($generatorName, false)) { require_once $generatorFolderRootPath . '/' . $generatorName . '/' . $generatorName . '.php'; } $generatorInstance = new $generatorName(); $ret[$generatorName] = $generatorInstance; } } return $ret; } } ?>
C++
UTF-8
8,925
2.859375
3
[]
no_license
// #include <SoftwareSerial.h> #include <FastLED.h> #define NUM_LEDS 398 #define NUM_BARNACLES 43 #define NUM_SENSORS 7 #define DATA_PIN 13 #define BRIGHTNESS 255 #define FRAMES_PER_SECOND 50 CRGB leds[NUM_LEDS]; class Barnacle { public: int type; // sm = 1, md = 2, lg = 3 int center; // center LED CHSV primaryColor; // fiber optic color CHSV secondaryColor; // body color // Constructor Barnacle(int _type, int _center, CHSV _primaryColor, CHSV _secondaryColor) { type = _type; center = _center; primaryColor = _primaryColor; secondaryColor = _secondaryColor; } /** * Update Barnacle */ void setCluster(CHSV primary, CHSV secondary) { int center = this->center; this->primaryColor = primary; this->secondaryColor = secondary; if (this->type == 2) { leds[center] = primary; leds[(center + 2)] = secondary; leds[(center + 4)] = secondary; leds[(center + 6)] = secondary; leds[(center + 8)] = secondary; leds[(center + 10)] = secondary; leds[(center + 12)] = secondary; } else { leds[center] = primary; leds[(center + 1)] = secondary; leds[(center + 2)] = secondary; leds[(center + 3)] = secondary; leds[(center + 4)] = secondary; leds[(center + 5)] = secondary; leds[(center + 6)] = secondary; } } }; class Sensor { public: int pin; // Pin number int barnacle; // Barnacle ID int state; // 0 = off, 1 = on int pressed; // Is pressed? 0 = false, 1 = true // Constructor Sensor(int _pin, int _barnacle, int _state, int _pressed) { pin = _pin; barnacle = _barnacle; state = _state; pressed = _pressed; } }; class LightningEffect { public: int duration; // Counter for duration char type; // lightning, ... int up; // Upward LED counter int down; // Downward LED counter // Constructor LightningEffect(int _duration, char _type, int _up, int _down) { duration = _duration; type = _type; up = _up; down = _down; } }; // Barnacle array Barnacle *barnacles[44]; // Sensor array Sensor *sensors[7]; // Section array int sections[7][2] = { {0, 6}, // 0 {6, 11}, // 1 {10, 16}, // 2 {16, 23}, // 3 {21, 28}, // 4 {27, 34}, // 5 {35, 43} // 6 }; // Set software serial pins that communicate with MIDI shield // SoftwareSerial softSerial(8, 9); // RX, TX void setup() { // Set MIDI baud rate: Serial.begin(31250); // Sensor mapping sensors[0] = new Sensor(4, 4, 0, 0); sensors[1] = new Sensor(5, 6, 0, 0); sensors[2] = new Sensor(6, 11, 0, 0); sensors[3] = new Sensor(7, 17, 0, 0); sensors[4] = new Sensor(10, 25, 0, 0); sensors[5] = new Sensor(11, 28, 0, 0); sensors[6] = new Sensor(12, 35, 0, 0); // Enable pins for(int i = 0; i < NUM_SENSORS; ++i) { pinMode(sensors[i]->pin, INPUT_PULLUP); } // Barnacle mapping barnacles[0] = new Barnacle(1, 0, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[1] = new Barnacle(1, 10, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[2] = new Barnacle(1, 20, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[3] = new Barnacle(1, 27, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[4] = new Barnacle(3, 34, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Large barnacles[5] = new Barnacle(1, 41, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[6] = new Barnacle(3, 50, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Large barnacles[7] = new Barnacle(1, 57, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[8] = new Barnacle(2, 65, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[9] = new Barnacle(1, 81, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[10] = new Barnacle(2, 92, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[11] = new Barnacle(3, 105, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Large barnacles[12] = new Barnacle(2, 112, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[13] = new Barnacle(2, 125, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[14] = new Barnacle(1, 138, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[15] = new Barnacle(1, 145, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[16] = new Barnacle(1, 152, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[17] = new Barnacle(3, 159, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Large barnacles[18] = new Barnacle(2, 166, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[19] = new Barnacle(1, 180, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[20] = new Barnacle(1, 190, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[21] = new Barnacle(2, 197, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[22] = new Barnacle(2, 210, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[23] = new Barnacle(1, 223, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[24] = new Barnacle(1, 232, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[25] = new Barnacle(3, 239, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Large barnacles[26] = new Barnacle(2, 246, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[27] = new Barnacle(1, 253, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[28] = new Barnacle(3, 260, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Large barnacles[29] = new Barnacle(1, 267, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[30] = new Barnacle(2, 274, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[31] = new Barnacle(1, 287, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[32] = new Barnacle(1, 295, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[33] = new Barnacle(1, 305, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[34] = new Barnacle(2, 312, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[35] = new Barnacle(3, 325, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Large barnacles[36] = new Barnacle(1, 332, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[37] = new Barnacle(2, 339, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[38] = new Barnacle(2, 352, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[39] = new Barnacle(1, 365, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[40] = new Barnacle(1, 372, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[41] = new Barnacle(1, 379, CHSV(64, 255, 255), CHSV(64, 255, 255)); barnacles[42] = new Barnacle(1, 386, CHSV(64, 255, 255), CHSV(64, 255, 255)); // Initialize LEDs FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS); FastLED.setBrightness(BRIGHTNESS); FastLED.clear(); } /* * Main loop */ void loop() { midiSend(128, 72, 100); checkInputs(); ambientEffect(); renderEffects(); FastLED.show(); FastLED.delay(1000/FRAMES_PER_SECOND); setPressed(); } /** * Check our inputs and set the button state */ void checkInputs() { // Read pins for(int i = 0; i < NUM_SENSORS; ++i) { if (digitalRead(sensors[i]->pin) == HIGH) { sensors[i]->state = 1; } else { sensors[i]->state = 0; sensors[i]->pressed = 0; } } } /** * Mark input as pressed after first loop */ void setPressed() { // Read pins for(int i = 0; i < NUM_SENSORS; ++i) { if (digitalRead((sensors[i]->pin) == HIGH) && ((sensors[i]->pressed) != 0)) { sensors[i]->pressed = 1; } } } /** * Handle the button states to render effects */ void renderEffects() { // Render effects based on sensors touched for(int i = 0; i < NUM_SENSORS; ++i) { if (sensors[i]->state == 1) { illuminateEffect(sections[i]); } /* if (sensors[i]->state == 1) && (sensors[i]->pressed != 1)) { lightningEffect(sensors[i]->barnacle); } */ /* if ((sensors[i]->state == 1) && (sensors[i]->pressed != 1)) { midiSend(128, i, 100); } */ } } void ambientEffect() { //fadeToBlackBy(leds, NUM_LEDS, 6); fadeLightBy(leds, NUM_LEDS, 6); int pos = random8(NUM_BARNACLES); barnacles[pos]->setCluster(CHSV(0, 255, 255), CHSV(random8(130, 165), 255, 255)); } void illuminateEffect(int section[]) { fadeToBlackBy(leds, NUM_LEDS, 3); int pos = random8(section[0], section[1]); barnacles[pos]->setCluster(CHSV(0, 255, 255), CHSV(random8(36, 64), 255, 255)); } void lightningEffect(int start) { int up = start; int down = start; for(int i = 0; i < NUM_BARNACLES; i++) { up = up + 1; down = down - 1; barnacles[up]->setCluster(CHSV(0, 255, 255), CHSV(45, 255, 255)); barnacles[down]->setCluster(CHSV(0, 255, 255), CHSV(45, 255, 255)); } } // plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that // data values are less than 127: void midiSend(int cmd, int pitch, int velocity) { Serial.write(cmd); Serial.write(pitch); Serial.write(velocity); }
Markdown
UTF-8
2,441
2.546875
3
[]
no_license
# 科学网—某大学勤工助学岗位每人每天15元 - 徐传胜的博文 # 某大学勤工助学岗位每人每天15元 已有 1814 次阅读2013-9-25 18:01|系统分类:[生活其它](http://blog.sciencenet.cn/home.php?mod=space&do=blog&view=all&uid=542302&catid=4)|关键词:大学|[大学](misc.php?mod=tag&id=270) 2013年“国庆节”校内勤工助学工作安排通知 各单位: 根据我校实际,现将“国庆节”期间校内勤工助学工作安排事宜通知如下: **一、岗位设置数量:** 各勤工助学设岗单位(各处室、各学院),设岗数量参考假期安排的勤工助学岗位数量,尽量缩减勤工助学设岗数量。各行政处室原则上不设岗位,如有特殊需要需提前申请,待批准后方可设岗。 **二、岗位工资报酬:** 10月1日(周二)-10月7日(周一):每工作日8元外,每日另发放伙食补贴7元,即每生每工作日共计15元。 **三、要求:** (一)按照学校有关学生资助工作要求,校内固定勤工助学岗位原则上须聘用已被学校认定注册、持有家庭经济困难学生认定等级证书的在校学生上岗。 (二)各设岗单位须加强学生教育管理,确保上岗学生安全,调动学生参加勤工助学活动积极性,充分发挥勤工助学作用。 (三)各设岗单位须严格进行考核,尽量缩减设岗数量,于9月27日(周五)前报送岗位数量和人员名单。 (四)未经学校学生资助管理部门同意,聘任学生人数超过平时设岗数量的,超出部分由单位自行承担。 (五)各带岗教师须认真负责,一旦发现一生两岗或冒名顶替的,将扣除应发报酬,并取消其参加勤工助学岗资格。 (六)各位单位带岗教师一定做好学生管理和教育工作,在工作中做好全面育人工作,切实让勤工助学成为解决学生生活困难和综合素质全面提升的平台。 学生工作处 2013年9月23日 转载本文请联系原作者获取授权,同时请注明本文来自徐传胜科学网博客。 链接地址:[http://blog.sciencenet.cn/blog-542302-727766.html](http://blog.sciencenet.cn/blog-542302-727766.html) 上一篇:[儿时中秋节记忆](blog-542302-726337.html) 下一篇:[三角形全等的判定定理1(sss)](blog-542302-727931.html)
Java
UTF-8
1,069
3.21875
3
[]
no_license
/* package whatever; // don't place package name! */ import java.util.regex.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { String text = "#include<stdio.h>\n#comment\nnot comment yet # now comment" + "\nthis is another not comment //ooh comment lol\n" + "heh/*\n * comment\n * comment\n * comment\n */ lolll\nboop"; System.out.println(text); Matcher m = Pattern.compile("#(?<firstWord>\\w+)?.*?\n").matcher(text); while(m.find()) { String first = m.group("firstWord"); if(first != null && first.equals("include")) { //System.out.prtinln("C"); //return; } } m.reset(); text = m.replaceAll("\n"); text = text.replaceAll("//.*?\n", "\n"); text = text.replaceAll("/\\*(.|\n)*?\\*/", "\n"); System.out.println(); System.out.println(); System.out.println(text); } }
Python
UTF-8
489
2.6875
3
[]
no_license
import unittest from json_to_html import json_to_html class TestJsonToHtmlConverter(unittest.TestCase): def test(self): data = {"p.my-class#my-id": "hello", "p.my-class1.my-class2": "example<a>asd</a>"} example = json_to_html() data = json_to_html.list_checking(data) self.assertEqual(data, u'<p id="my-id" class="my-class">hello</p><p class="my-class1 my-class2">example&lt;a&gt;asd&lt;/a&gt;</p>') if __name__ == '__main__': unittest.main()
SQL
UTF-8
1,327
3.640625
4
[]
no_license
Use ADPPCTU2012 -- create temp table create table #ManagerList( Tnum varchar (6), UserID int, Tman varchar (6), ManID Int, Mion varchar (200), CID int) Insert into #ManagerList (Tnum,Tman) SELECT [T Number], SUBSTRING(Manager, CHARINDEX('=', Manager) + 1, CHARINDEX(',', Manager) - CHARINDEX('=', Manager) - 1) AS Tman FROM LDAPUsers WHERE (SUBSTRING(Manager, CHARINDEX('=', Manager) + 1, CHARINDEX(',', Manager) - CHARINDEX('=', Manager) - 1) IS NOT NULL) Update #ManagerList Set ManID = [User].UserID, Mion = SUBSTRING(EmailAddress, 0, CHARINDEX('@', EmailAddress)) From #Managerlist Join [User] on #ManagerList.Tman = [user].ID Update #ManagerList Set UserID = [User].UserID From #Managerlist Join [User] on #ManagerList.Tnum = [user].ID Update #ManagerList Set Cid = UserComputer.ComputerID From #Managerlist Join [UserComputer] on #ManagerList.UserID =[UserComputer].UserID Select * From #ManagerList Where UserID is not null and CID is not null Update MigrationComputerRegistration Set ManagerUserID = [#ManagerList].ManID, ManagerID = [#ManagerList].Mion From #Managerlist Join MigrationComputerRegistration on #Managerlist.CID = MigrationComputerRegistration.ComputerID Where (MigrationComputerRegistration.ManagerID is null) drop table #ManagerList
C#
UTF-8
3,329
2.75
3
[]
no_license
using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WeatherApi.Dto; using WeatherApi.Entity; using WeatherApi.Models; namespace WeatherApi.Controllers { [ApiController] [Route("[controller]")] public class WeatherDataController : ControllerBase { private readonly IMapper _mapper; private readonly ILogger<WeatherDataController> _logger; private const string SERVER_ERROR = "Server error"; private WeatherDataContext _weatherDataContext { get; } public WeatherDataController(WeatherDataContext weatherDataContext, IMapper mapper, ILogger<WeatherDataController> logger) { this._weatherDataContext = weatherDataContext; this._mapper = mapper; this._logger = logger; } /// <summary> /// Get weather data for one date /// </summary> /// <param name="date"></param> /// <returns></returns> [HttpGet("{date}")] public ObjectResult Get(string date) { try { //DateTime dateDt = DateTime.Parse(date); DateTime date1 = DateTime.Parse(date).Date; var date2 = date1.AddDays(1); var data = _weatherDataContext.WeatherDatas .Where(d => d.date_time_local >= date1 && d.date_time_local < date2).ToList(); // Map to DTO return Ok(data.ConvertAll(d => _mapper.Map<WeatherDataDto>(d))); } catch(Exception ex) { _logger.LogError(ex, ex.Message); return Problem(SERVER_ERROR); } } /// <summary> /// Get weather data for one hour. /// </summary> /// <param name="date"></param> /// <param name="hour"></param> /// <returns></returns> [HttpGet("{date}/{hour}")] public ObjectResult Get(string date, string hour) { try { int time1 = int.Parse(hour); var date1 = DateTime.Parse(date).Date.AddHours(time1); var data = _weatherDataContext.WeatherDatas .FirstOrDefault(d => d.date_time_local == date1); // Map to DTO return Ok(_mapper.Map<WeatherDataDto>(data)); } catch (Exception ex) { _logger.LogError(ex, ex.Message); return Problem(SERVER_ERROR); } } /// <summary> /// Create new entry /// </summary> /// <param name="weatherData"></param> /// <returns></returns> [HttpPost] public async Task<IActionResult> Post(WeatherData weatherData) { try { await _weatherDataContext.AddAsync(weatherData); _weatherDataContext.SaveChanges(); return Ok(new { count = 1}); } catch(Exception ex) { _logger.LogError(ex, ex.Message); return Problem(SERVER_ERROR); } } } }
PHP
UTF-8
9,754
2.6875
3
[ "MIT" ]
permissive
<?php /** * @package StartupAPI * @subpackage Subscriptions */ require_once(__DIR__ . '/Account.php'); require_once(__DIR__ . '/StartupAPIModule.php'); /** * Abstract class representing payment engines users can use to pay for subscription */ abstract class PaymentEngine extends StartupAPIModule { /** * @var string Payment engine slug */ protected $slug; /** * Creates pagement engine and registers it in the system */ public function __construct() { parent::__construct(); UserConfig::$payment_modules[] = $this; } /** * Returns true if module requires prepayment to be used. * * Modules that require pre-payment will only enable payment schedules that * require payment that is less then account balance. * * @return boolean True if module requires prepayment */ public function requiresPrePayment() { return FALSE; } /** * Returns action URL to send user to to accept payments for specific plan and schedule. * * Must be defined by all engines that do not require prepayment. * * @param Plan $plan Payment plan user is trying to switch to * @param PaymentSchedule $schedule Payment schedule user is trying to use * @param Account $account Account to change subscription for * * @return null */ public function getActionURL($plan = null, $schedule = null, $account = null) { return null; } /** * Returns button label to use for payment engine sign up * * @param Plan $plan Payment plan user is trying to switch to * @param PaymentSchedule $schedule Payment schedule user is trying to use * @param Account $account Account to change subscription for * * @return string */ public function getActionButtonLabel($plan = null, $schedule = null, $account = null) { return "Sign Up"; } /** * Called when subscription for account changes * * @param int $account_id Account ID * @param string $plan_slug Plan slug * @param string $schedule_slug Payment schedule slug */ public abstract function changeSubscription($account_id, $plan_slug, $schedule_slug); /** * Returns engine slug * * @return string Engine slug */ public function getSlug() { return $this->slug; } /** * Returns payment engine for a specififed slug * * @param string $slug Payment engine slug * * @return PaymentEngine|null Payment engine or null if payment engine is not registered */ public static function getEngineBySlug($slug) { return StartupAPIModule::get($slug); } /** * Records transaction details, must be overriden if there are any details available * * @param int $transaction_id Transaction ID * @param mixed[] $details Transaction details array */ public function storeTransactionDetails($transaction_id, $details) { return TRUE; } /** * Returns details for transaction, specific to particular payment engine * * @param int $transaction_id Transaction ID * * @return mixed[]|false Retrieves array of transaction details or false if none available */ public function expandTransactionDetails($transaction_id) { return FALSE; } /** * Renders transation details if they are available * * @param int $transaction_id Transaction ID * * @return string HTML rendering of transaction details */ public function renderTransactionLogDetails($transaction_id) { return ""; } /** * Indicates that user interaction required and therefore admins * can't just switch plans through admin UI * * For most classes it would return TRUE (default), but for manual (pre-payment / invoicing) * engine, which process payments offline, this will return FALSE. * * @return boolean */ public function isUserInteractionRequired() { return TRUE; } /** * This method should be called by subsclasses which actually receives information about payment * * @param array $data Array with "account_id" and "amount" keys * * @return int|false Transaction id or false if account ID not specified * * @throws Exception */ public function paymentReceived($data) { // data is array with following required keys: // account_id // amount // if (!(isset($data['account_id']) && isset($data['amount']))) { throw new Exception("No account_id in element " . print_r($data, 1)); } $account = Account::getByID($data['account_id']); if (is_null($account)) { return FALSE; } $account->paymentReceived($data['amount']); return $account->getLastTransactionID(); } /** * Process refund * * @param array $data Array with "account_id" and "amount" keys * * @return int|false Transaction id or false if account ID not specified * * @throws Exception */ public function refund($data) { // refund is generally the same, as payment if (!(isset($data['account_id']) && isset($data['amount']))) { throw new Exception("No account_id in element " . print_r($data, 1)); } $account = Account::getByID($data['account_id']); if (is_null($account)) { return FALSE; } $account->paymentIsDue($data['amount']); return $account->getLastTransactionID(); } /** * Unsubscribes user from all plans * * @param type $account_id * * @return false if account does not exist */ public function unsubscribe($account_id) { $account = Account::getByID($account_id); if (is_null($account)) { return FALSE; } while ($account->deactivatePlan()) { } } /** * Returns payment engine slug (not ID) * * @return string Payment engine slug * * @todo Rename getID in StartupAPIModule to getSlug() */ public function getID() { return $this->getSlug(); } /** * This method is called daily to initiate payments and update accounts * * @throws DBException */ public function cronHandler() { $db = UserConfig::getDB(); // Deactivate all accounts where grace period is expired // Those accounts should have negative balance, so we can restrict 'where' condition if (!($stmt = $db->prepare('SELECT a.id, UNIX_TIMESTAMP(MIN(ac.date_time)) FROM u_accounts a INNER JOIN u_account_charge ac ON a.id = ac.account_id AND ac.amount > 0 AND engine_slug = ? GROUP BY a.id'))) { throw new DBPrepareStmtException($db); } if (!$stmt->bind_param('s', $this->slug)) { throw new DBBindParamException($db, $stmt); } if (!$stmt->execute()) { throw new DBExecuteStmtException($db, $stmt); } if (!$stmt->store_result()) { throw new DBException($db, $stmt, "Can't store result"); } if (!$stmt->bind_result($account_id, $date_time)) { throw new DBBindResultException($db, $stmt); } while ($stmt->fetch() === TRUE) { if (is_null($account = Account::getByID($account_id))) { continue; } $plan = $account->getPlan(); // can be FALSE if (!$plan) { continue; } $grace_period = $plan->getGracePeriod(); if ($grace_period && $grace_period * 86400 + $date_time > time()) { $account->deactivatePlan(); } } // Find all accounts which are served by this Payment Engine and which has next_charge date earlier than now if (!($stmt = $db->prepare('SELECT id, plan_slug, next_plan_slug, schedule_slug, next_schedule_slug, next_engine_slug ' . 'FROM u_accounts ' . 'WHERE engine_slug = ? AND active = 1 AND next_charge < ?'))) { throw new DBPrepareStmtException($db); } if (!$stmt->bind_param('ss', $this->slug, date('Y-m-d H:i:s'))) { throw new DBBindParamException($db, $stmt); } if (!$stmt->execute()) { throw new DBExecuteStmtException($db, $stmt); } if (!$stmt->store_result()) { throw new DBException($db, $stmt, "Can't store result"); } if (!$stmt->bind_result($account_id, $plan_slug, $next_plan_slug, $schedule_slug, $next_schedule_slug, $next_engine_slug)) { throw new DBBindResultException($db, $stmt); } while ($stmt->fetch() === TRUE) { // If plan/schedule change requested, perform // Again, check if user balance is sufficient to do this change if (is_null($account = Account::getByID($account_id))) { continue; } $billed = 0; if (!is_null($next_plan_slug) || !is_null($next_schedule_slug) || !is_null($next_engine_slug)) { $next_plan = Plan::getPlanBySlug($next_plan_slug); $next_schedule = is_null($next_plan) ? NULL : $next_plan->getPaymentScheduleBySlug($next_schedule_slug); $next_engine = PaymentEngine::getEngineBySlug($next_schedule_slug); // ok if either no next_schedule, or balance is sufficient $ok = is_null($next_schedule) || $account->getBalance() >= $next_schedule->getChargeAmount() && !is_null($next_engine); if (!is_null($next_plan) && $ok) { // next_plan found, change could be performed if ($next_plan_slug == $plan_slug) { // only change schedule $account->setPaymentSchedule($next_schedule_slug, $next_engine_slug); // schedule changed, user billed automatically $billed = 1; } else { // change plan and schedule $account->activatePlan($next_plan_slug, $next_schedule_slug, $next_engine_slug); $billed = 1; } } // othrewise plan and schedule left as it was before } // Bill user if not yet billed if (!$billed) { $account->paymentIsDue(); $plan = $account->getPlan(); // can be FALSE if ($plan && !is_null($schedule = $account->getSchedule())) { // Set new next_charge if (!($stmt2 = $db->prepare('UPDATE u_accounts SET next_charge = next_charge + INTERVAL ? DAY WHERE id = ?'))) { throw new DBPrepareStmtException($db); } if (!$stmt2->bind_param('ii', $schedule->getChargePeriod(), $account->getID())) { throw new DBBindParamException($db, $stmt); } if (!$stmt2->execute()) { throw new DBExecuteStmtException($db, $stmt); } $stmt2->close(); } } } // end of while } }
Java
UTF-8
2,747
2.8125
3
[]
no_license
package test.traffic; import com.hokageinc.models.Orbit; import com.hokageinc.models.Place; import com.hokageinc.models.Vehicle; import com.hokageinc.traffic.MinimumTimeTracker; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class MinimumTimeTrackerTest { private static Vehicle bike; private static Vehicle vehicle; private static Vehicle fasterVehicle; private static Orbit orbit; private static Orbit shorterOrbit; private MinimumTimeTracker minimumTimeTracker; @BeforeClass public static void globalSetup() { bike = new Vehicle(0, "Bike", 20, 2); vehicle = new Vehicle(1, "Test Vehicle 1", 10, 2); fasterVehicle = new Vehicle(2, "Test Vehicle 1", 20, 2); orbit = new Orbit(0, "Test Orbit 1", 40, 3, new Place("Test Place 1"), new Place("Test Place 2")); shorterOrbit = new Orbit(0, "Test Orbit 1", 30, 3, new Place("Test Place 1"), new Place("Test Place 2")); } @Before public void setup() { minimumTimeTracker = MinimumTimeTracker.create(); } @Test public void shouldUpdateTheMinimum() { minimumTimeTracker.setIfMinimum(10.0f, vehicle, orbit); Assert.assertEquals(vehicle, minimumTimeTracker.getOptimalVehicle()); Assert.assertEquals(orbit, minimumTimeTracker.getOptimalOrbit()); minimumTimeTracker.setIfMinimum(8.0f, fasterVehicle, shorterOrbit); Assert.assertEquals(fasterVehicle, minimumTimeTracker.getOptimalVehicle()); Assert.assertEquals(shorterOrbit, minimumTimeTracker.getOptimalOrbit()); } @Test public void vehicleNamedBikeShouldGetPreferenceAndOverride() { minimumTimeTracker.setIfMinimum(10.0f, vehicle, orbit); Assert.assertEquals(vehicle, minimumTimeTracker.getOptimalVehicle()); Assert.assertEquals(orbit, minimumTimeTracker.getOptimalOrbit()); minimumTimeTracker.setIfMinimum(10.0f, bike, shorterOrbit); Assert.assertEquals(bike, minimumTimeTracker.getOptimalVehicle()); Assert.assertEquals(shorterOrbit, minimumTimeTracker.getOptimalOrbit()); } @Test public void vehicleNamedBikeShouldGetPreferenceAndStay() { minimumTimeTracker.setIfMinimum(10.0f, bike, shorterOrbit); Assert.assertEquals(bike, minimumTimeTracker.getOptimalVehicle()); Assert.assertEquals(shorterOrbit, minimumTimeTracker.getOptimalOrbit()); minimumTimeTracker.setIfMinimum(10.0f, vehicle, orbit); Assert.assertEquals(bike, minimumTimeTracker.getOptimalVehicle()); Assert.assertEquals(shorterOrbit, minimumTimeTracker.getOptimalOrbit()); } }
Python
UTF-8
1,670
2.671875
3
[]
no_license
# -*- coding:utf8 -*- from myGlobal.myCls.BrokerCls import Broker from myGlobal.myCls.Stock import Stock from myGlobal.myCls.msql import DBHelper from multiprocessing.dummy import Pool as ThreadPool from functools import partial import myGlobal.myTime as myTime import datetime from myGlobal.myCls.multiProcess import threads #多线程模拟每日机构买卖股票 def _DailySimulate(brokercode,strdate,tablename,amount,type): b = Broker(brokercode,strdate) b.simulate(tablename=tablename,ts_date=strdate,amount=amount,ftype=type) #根据输入日期,找出当日上榜机构 def _getBrokerToday(strdate): sql = "select broker_code from broker_buy_summary where b_count>0 and ts_date='%s'" % strdate t_broker = DBHelper().fetchall(sql) #将机构列表存入list,以便后续计算 li_broker = [] for i in range(len(t_broker)): if t_broker[i][0] not in li_broker: li_broker.append(t_broker[i][0]) return li_broker #多线程执行每日模拟计算(方法1+方法2) #@threads(10) def DailySimulate(strdate,tablename,amount,type): #先根据输入日期找出当日上榜机构,存入list li_broker = _getBrokerToday(strdate) [_DailySimulate(brokercode,strdate=strdate,tablename=tablename,amount=amount,type=type) for brokercode in li_broker] if __name__ =='__main__': simulate_list =[1,2] startdate = "2017-01-01" enddate = "2019-04-01" date = myTime.strTodate(startdate) while date <= myTime.strTodate(enddate): for ftype in simulate_list: DailySimulate(str(date), "simulate_buy", 1000, int(ftype)) date = date+datetime.timedelta(days=1)
Java
UTF-8
2,953
2.8125
3
[]
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 grabdatafromdb.megamillions; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; /** * * @author Devon */ public class ConnectToDB { private String url; private String user; private String pw; private String jdbcClassName; private Connection con; public ConnectToDB(String url, String user, String pw, String jdbcClassName) { this.url = url; this.user = user; this.pw = pw; this.jdbcClassName = jdbcClassName; } public void connectToDB() { try { Class.forName(jdbcClassName); con = DriverManager.getConnection(url, user, pw); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("ClassNotFoundException"); } catch (SQLException e) { e.printStackTrace(); System.out.println("SQLException"); } finally { if (con != null) { System.out.println("Connected Successfully."); } } } public void getDataFromDB() throws SQLException { int rowcount = 0; int count = 1; if (con != null) { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("select * from DEVON.MEGAMILLIONS order by DATE Desc"); ResultSetMetaData rsm = rs.getMetaData(); if (rs.last()) { rowcount = rs.getRow(); rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element } System.out.println("Row count: " + rowcount); for (int x = 1; x <= rsm.getColumnCount(); x++) { System.out.printf("%-10s\t", rsm.getColumnLabel(x).trim()); } System.out.println(); for (int x = 1; x <= rsm.getColumnCount(); x++) { System.out.printf("%-10s\t", "----------"); } System.out.println(); while (rs.next()) { count++; for (int x = 1; x <= rsm.getColumnCount(); x++) { System.out.printf("%-10s\t", rs.getString(rsm.getColumnLabel(x)).trim()); } System.out.println(); } con.close(); System.out.println("Connection Closed."); } else { con.close(); System.out.println("No Connection! Connection Closed. "); } } }
TypeScript
UTF-8
2,092
2.671875
3
[]
no_license
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { CREW_OPEN_CHANGE, API_KEY } from "../constants"; const initialState = { isCrewOpen: false, fetchingFilm: false, data: { info: {}, people: [], known: [], images: [], }, }; interface InputsType { selectedMovie: any; languageSelected: String; } export const getFilm = createAsyncThunk( "movie/getFilm", async (input: InputsType) => { const index = input.selectedMovie; const languageIn = input.languageSelected; const obj = { index: 0, data: { info: {}, people: [], known: [], images: [] }, }; await fetch( `https://api.themoviedb.org/3/movie/${index}?api_key=${API_KEY}&language=${languageIn.toLowerCase()}` ) .then((data) => data.json()) .then((data) => (obj.data.info = data)); await fetch(` https://api.themoviedb.org/3/movie/${index}/credits?api_key=${API_KEY}&language=${languageIn.toLowerCase()}`) .then((data) => data.json()) .then((data) => (obj.data.people = data.cast)); await fetch( `https://api.themoviedb.org/3/movie/${index}/recommendations?api_key=${API_KEY}&language=${languageIn.toLowerCase()}&page=1` ) .then((data) => data.json()) .then((data) => (obj.data.known = data.results)); await fetch( `https://api.themoviedb.org/3/movie/${index}/images?api_key=${API_KEY}&language=${languageIn.toLowerCase()}` ) .then((data) => data.json()) .then((data) => (obj.data.images = data.backdrops)); obj.index = index; return obj; } ); const movie = createSlice({ name: "movie", initialState, reducers: {}, extraReducers: (builder) => { builder .addCase(getFilm.pending, (state, action) => { state.fetchingFilm = true; }) .addCase(getFilm.fulfilled, (state, action) => { state.fetchingFilm = false; state.data = action.payload.data; }) .addCase(CREW_OPEN_CHANGE, (state, action: any) => { state.isCrewOpen = action.payload; }); }, }); export default movie.reducer;
Python
UTF-8
327
4.75
5
[]
no_license
''' Write a script that prints out all the squares of numbers from a user inputed lower to a user inputed upper bound. Use a for loop that demonstrates the use of the range function. ''' lower = int(input("type a number ")) upper = int(input ("type a higher number ")) + 1 for num in range(lower, upper): print(num ** 2)
JavaScript
UTF-8
2,291
3.25
3
[]
no_license
const fs = require('fs'); const input = fs.readFileSync('input', 'utf8'); const IntcodeComputer = require('../shared/IntcodeComputer'); const program = input.split(',').map(Number); const droid = new IntcodeComputer(program); const map = {}; const pathStack = []; const getKey = (x, y) => `${x}.${y}`; const setTile = (x, y, tile) => { map[getKey(x, y)] = tile; } const getTile = (x, y) => map[getKey(x, y)]; const isVisited = (x, y) => getTile(x, y) !== undefined; const isPath = (x, y) => getTile(x, y) == 1; const getNextDir = (x, y) => { return !isVisited(x, y+1) ? 1 : !isVisited(x, y-1) ? 2 : !isVisited(x-1, y) ? 3 : !isVisited(x+1, y) ? 4 : false; } const getNewCoordinates = (tx, ty, dir) => { switch(dir) { case 1: ty++; break; case 2: ty--; break; case 3: tx--; break; case 4: tx++; break; } return [tx, ty]; } const getReverseDir = dir => { switch(dir) { case 1: return 2; case 2: return 1; case 3: return 4; case 4: return 3; } } const getAdjacentTiles = (x, y) => { return [ [x+1, y], [x-1, y], [x, y+1], [x, y-1] ]; } const getBfsDepth = (x, y) => { let queue = [[x,y]]; let depth = -1; while(queue.length != 0) { const temp = []; queue.forEach(coord => { getAdjacentTiles(...coord) .filter(adjCoord => isPath(...adjCoord)) .forEach(adjCoord => { setTile(...adjCoord, 'O'); temp.push(adjCoord) }) }); queue = temp; depth++; } return depth; } let x = 0, y = 0; let dir, backTrack, tile, tx, ty; setTile(x, y, 1); do { dir = getNextDir(x, y) || pathStack.pop(); backTrack = !getNextDir(x, y); droid.input(dir); tile = droid.output(); ([tx, ty] = getNewCoordinates(x, y, dir)); setTile(tx, ty, tile); if (tile == 0) { continue; } !backTrack && pathStack.push(getReverseDir(dir)); [x, y] = [tx, ty]; } while(tile != 2); console.log(pathStack.length); // Part 1 console.log(getBfsDepth(x, y)); // Part 2
C++
UTF-8
987
2.703125
3
[]
no_license
// Ball.h /* #pragma once should always be at the top of your header files * it prevents other headers like "ofMain.h" from being included more than once in your app * (note that ofMain.h is also included in ofApp.h) */ #pragma once #include "ofMain.h" // ofMain.h lets our Ball "see" openFrameworks #include "Bubble.h" class Ball { public: // other classes can access the following functions & variables: Ball(float x, float y); // "constructor" function - required for every class // this is automatically called whenever we create a new ball void update(); void draw(); float waterLevel = 500.0; float yspeed; float acclerate; float waterDamp = 0.2 ; float shrinkRate = 0.98; float radius; // size float preRadius; float x, y; // position float dirX, dirY; // "direction" (a.k.a. velocity or speed) float dissolvedAmt = 0.0; float dissolvedRate = 0.0; ofColor color; vector<Bubble> Bubbles; };
C#
UTF-8
1,810
2.890625
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Futuclass.EventBus { internal static class HandlerFinder { internal static MethodInfo[] GetPublicInstanceMethods(object eventProxy) { var proxyType = eventProxy.GetType(); return proxyType.GetMethods(BindingFlags.Public | BindingFlags.Instance); } internal static List<HandlerMethodData> GetHandlersData(MethodInfo[] methodInfo) { var rt = new List<HandlerMethodData>(); foreach (var method in methodInfo) { if (TryCreateHandlerData(method, out var data)) rt.Add(data); } return rt; } internal static bool TryCreateHandlerData(MethodInfo methodInfo, out HandlerMethodData data) { //No attribute found, handler cannot be created if (!(methodInfo.GetCustomAttributes(typeof(HandlerAttribute), true).FirstOrDefault() is HandlerAttribute attribute)) { data = null; return false; } var methodParams = methodInfo.GetParameters(); //Method doesn't mach handler pattern, handler cannot be created if (methodParams.Length != 1) { data = null; return false; } var methodParameter = methodParams.FirstOrDefault(); var paramType = methodParameter?.ParameterType; var handlerData = new HandlerMethodData() { AttachedAttribute = attribute, Method = methodInfo, ParameterType = paramType }; data = handlerData; return true; } } }
Ruby
UTF-8
3,893
2.90625
3
[ "LicenseRef-scancode-generic-cla", "BSD-3-Clause" ]
permissive
require 'spec_helper_min' require 'minitest/autorun' require_relative '../../../structures/collection' include DataRepository describe Collection do before do @repository = DataRepository::Repository.new @dummy_class = Class.new do attr_accessor :id def initialize(arguments={}); self.id = arguments.fetch(:id); end def fetch; self; end def to_hash; { id: id }; end def ==(other); id.to_s == other.id.to_s; end end @defaults = { repository: @repository, member_class: @dummy_class} end describe '#add' do it 'adds a member to the collection' do member = @dummy_class.new(id: 1) collection = Collection.new(@defaults) collection.add(member) collection.to_a.must_include member end end describe '#delete' do it 'deletes a member from the collection' do member = @dummy_class.new(id: 1) collection = Collection.new(@defaults) collection.add(member) collection.delete(member) collection.to_a.wont_include member end end #delete describe '#each' do it 'yields members of the collection as the initialized member_class' do member = @dummy_class.new(id: 1) collection = Collection.new(@defaults) collection.add(member) collection.store rehydrated_collection = Collection.new(@defaults.merge(signature: collection.signature)) rehydrated_collection.fetch rehydrated_collection.to_a.first.must_be_instance_of @dummy_class end it 'returns an enumerator if no block given' do member = @dummy_class.new(id: 1) collection = Collection.new({ repository: @repository }) collection.add(member) collection.store rehydrated_collection = Collection.new(@defaults.merge(signature: collection.signature)) rehydrated_collection.fetch enumerator = rehydrated_collection.each enumerator.next.must_be_instance_of @dummy_class end end #each describe '#fetch' do it 'resets the collection with data from the data repository' do member1 = @dummy_class.new(id: 1) member2 = @dummy_class.new(id: 2) collection = Collection.new(@defaults) collection.add(member1) collection.store rehydrated_collection = Collection.new(@defaults.merge(signature: collection.signature)) rehydrated_collection.add(member2) rehydrated_collection.to_a.must_include(member2) rehydrated_collection.to_a.wont_include(member1) rehydrated_collection.fetch rehydrated_collection.to_a.must_include(member1) rehydrated_collection.to_a.wont_include(member2) end it 'empties the collection if it was not persisted to the repository' do member = @dummy_class.new(id: 1) collection = Collection.new(@defaults) collection.add(member) collection.to_a.length.must_equal 1 collection.fetch collection.to_a.must_be_empty end end #fetch describe '#store' do it 'persists the collection to the data repository' do member = @dummy_class.new(id: 1) collection = Collection.new(@defaults) collection.add(member) collection.store rehydrated_collection = Collection.new(@defaults.merge(signature: collection.signature)) rehydrated_collection.fetch rehydrated_collection.map { |member| member.id }.must_include member.id end end #store describe '#to_json' do it 'renders a JSON representation of the collection' do member = @dummy_class.new(id: 1) collection = Collection.new(@defaults) collection.add(member) collection.store representation = JSON.parse(collection.to_json) representation.size.must_equal 1 representation.first.fetch('id').must_equal member.id end end #to_json end # Collection
C#
UTF-8
1,522
2.6875
3
[ "MIT" ]
permissive
using Faturamento.Api.Infra; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Faturamento.Api.Dominio.Comandos { public class CriarPedidoComando { public CriarPedidoComando(string processoId, int socioId, List<Item> itens) { ProcessoId = processoId; SocioId = socioId; Itens = itens; } public string ProcessoId { get; set; } public int SocioId { get; set; } public List<Item> Itens { get; set; } public sealed class Item { public Item(int dividaId, decimal valor) { DividaId = dividaId; Valor = valor; } public int DividaId { get; set; } public decimal Valor { get; set; } } } public sealed class CriarPedidoGerenciadorComando { private readonly EFContexto _contextoSql; public CriarPedidoGerenciadorComando(EFContexto contextoSql) { _contextoSql = contextoSql; } public async Task<Pedido> ExecutarAsync(CriarPedidoComando comando) { var pedido = Pedido.Criar( comando.ProcessoId, comando.SocioId, comando.Itens.Select(i=> Pedido.Item.Criar(i.DividaId, i.Valor)).ToList()); await _contextoSql.Pedidos.AddAsync(pedido); await _contextoSql.SaveChangesAsync(); return pedido; } } }
Python
UTF-8
373
2.5625
3
[ "BSD-2-Clause" ]
permissive
try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from django.template import Library register = Library() @register.filter def slice(items, group_size=1): args = [iter(items)] * group_size return (filter(None, group) for group in zip_longest(*args, fillvalue=None))
Java
UTF-8
6,055
1.8125
2
[]
no_license
package com.megvii.meglive_sdk.volley.toolbox; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.megvii.meglive_sdk.volley.AbstractC1628m; import com.megvii.meglive_sdk.volley.C1620e; import com.megvii.meglive_sdk.volley.C1625j; import com.megvii.meglive_sdk.volley.C1627l; import com.megvii.meglive_sdk.volley.C1631o; import com.megvii.meglive_sdk.volley.C1654u; /* renamed from: com.megvii.meglive_sdk.volley.toolbox.h */ public final class C1650h extends AbstractC1628m<Bitmap> { /* renamed from: r */ public static final Object f2948r = new Object(); /* renamed from: a */ public final C1631o.AbstractC1633b<Bitmap> f2949a; /* renamed from: b */ public final Bitmap.Config f2950b; /* renamed from: c */ public final int f2951c; /* renamed from: p */ public final int f2952p; /* renamed from: q */ public final ImageView.ScaleType f2953q; public C1650h(String str, C1631o.AbstractC1633b<Bitmap> bVar, int i, int i2, ImageView.ScaleType scaleType, Bitmap.Config config, C1631o.AbstractC1632a aVar) { super(0, str, aVar); this.f2893n = new C1620e(1000, 2, 2.0f); this.f2949a = bVar; this.f2950b = config; this.f2951c = i; this.f2952p = i2; this.f2953q = scaleType; } /* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object] */ @Override // com.megvii.meglive_sdk.volley.AbstractC1628m /* renamed from: a */ public final /* bridge */ /* synthetic */ void mo17347a(Bitmap bitmap) { Bitmap bitmap2 = bitmap; C1631o.AbstractC1633b<Bitmap> bVar = this.f2949a; if (bVar != null) { bVar.mo16992a(bitmap2); } } @Override // com.megvii.meglive_sdk.volley.AbstractC1628m /* renamed from: f */ public final AbstractC1628m.EnumC1629a mo17353f() { return AbstractC1628m.EnumC1629a.LOW; } /* renamed from: a */ public static int m2864a(int i, int i2, int i3, int i4, ImageView.ScaleType scaleType) { if (i == 0 && i2 == 0) { return i3; } if (scaleType == ImageView.ScaleType.FIT_XY) { return i == 0 ? i3 : i; } if (i == 0) { double d = (double) i2; double d2 = (double) i4; Double.isNaN(d); Double.isNaN(d2); double d3 = (double) i3; Double.isNaN(d3); return (int) (d3 * (d / d2)); } else if (i2 == 0) { return i; } else { double d4 = (double) i4; double d5 = (double) i3; Double.isNaN(d4); Double.isNaN(d5); double d6 = d4 / d5; if (scaleType == ImageView.ScaleType.CENTER_CROP) { double d7 = (double) i; Double.isNaN(d7); double d8 = (double) i2; if (d7 * d6 >= d8) { return i; } Double.isNaN(d8); return (int) (d8 / d6); } double d9 = (double) i; Double.isNaN(d9); double d10 = (double) i2; if (d9 * d6 <= d10) { return i; } Double.isNaN(d10); return (int) (d10 / d6); } } @Override // com.megvii.meglive_sdk.volley.AbstractC1628m /* renamed from: a */ public final C1631o<Bitmap> mo17346a(C1625j jVar) { Bitmap bitmap; C1631o<Bitmap> oVar; synchronized (f2948r) { try { byte[] bArr = jVar.f2878b; BitmapFactory.Options options = new BitmapFactory.Options(); if (this.f2951c == 0 && this.f2952p == 0) { options.inPreferredConfig = this.f2950b; bitmap = BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options); } else { options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options); int i = options.outWidth; int i2 = options.outHeight; int a = m2864a(this.f2951c, this.f2952p, i, i2, this.f2953q); int a2 = m2864a(this.f2952p, this.f2951c, i2, i, this.f2953q); options.inJustDecodeBounds = false; options.inSampleSize = m2863a(i, i2, a, a2); bitmap = BitmapFactory.decodeByteArray(bArr, 0, bArr.length, options); if (bitmap != null && (bitmap.getWidth() > a || bitmap.getHeight() > a2)) { Bitmap createScaledBitmap = Bitmap.createScaledBitmap(bitmap, a, a2, true); bitmap.recycle(); bitmap = createScaledBitmap; } } if (bitmap == null) { oVar = C1631o.m2809a(new C1627l(jVar)); } else { oVar = C1631o.m2810a(bitmap, C1642d.m2850a(jVar)); } } catch (OutOfMemoryError e) { C1654u.m2874c("Caught OOM for %d byte image, url=%s", Integer.valueOf(jVar.f2878b.length), this.f2884e); return C1631o.m2809a(new C1627l(e)); } catch (Throwable th) { throw th; } } return oVar; } /* renamed from: a */ public static int m2863a(int i, int i2, int i3, int i4) { double d = (double) i; double d2 = (double) i3; Double.isNaN(d); Double.isNaN(d2); double d3 = (double) i2; double d4 = (double) i4; Double.isNaN(d3); Double.isNaN(d4); double min = Math.min(d / d2, d3 / d4); float f = 1.0f; while (true) { float f2 = 2.0f * f; if (((double) f2) > min) { return (int) f; } f = f2; } } }
Java
UTF-8
3,476
1.992188
2
[]
no_license
package online.kingdomkeys.kingdomkeys.client.render.entity; import javax.annotation.Nullable; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRendererManager; import net.minecraft.client.renderer.entity.MobRenderer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3f; import net.minecraftforge.fml.client.registry.IRenderFactory; import online.kingdomkeys.kingdomkeys.KingdomKeys; import online.kingdomkeys.kingdomkeys.client.model.entity.MoogleModel; import online.kingdomkeys.kingdomkeys.entity.mob.MoogleEntity; public class MoogleRenderer extends MobRenderer<MoogleEntity, MoogleModel<MoogleEntity>> { public static final MoogleRenderer.Factory FACTORY = new MoogleRenderer.Factory(); public MoogleRenderer(EntityRendererManager renderManagerIn) { super(renderManagerIn, new MoogleModel<>(), 0.35F); } @Override public void render(MoogleEntity entityIn, float entityYaw, float partialTicks, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int packedLightIn) { if (entityIn.isFakeMoogle()) { IVertexBuilder builder = bufferIn.getBuffer(this.entityModel.getRenderType(this.getEntityTexture(entityIn))); matrixStackIn.pop(); { float f = MathHelper.interpolateAngle(partialTicks, entityIn.prevRenderYawOffset, entityIn.renderYawOffset); float f7 = this.handleRotationFloat(entityIn, partialTicks); this.applyRotations(entityIn, matrixStackIn, f7, f, partialTicks); matrixStackIn.scale(-1.0F, -1.0F, 1.0F); this.preRenderCallback(entityIn, matrixStackIn, partialTicks); matrixStackIn.translate(0.5D, (double) -1.501F, -0.5D); matrixStackIn.rotate(Vector3f.YP.rotationDegrees(Minecraft.getInstance().player.rotationYaw + 180)); this.entityModel.render(matrixStackIn, builder, packedLightIn, getPackedOverlay(entityIn, 0.0F), 1.0F, 1.0F, 1.0F, entityIn.isFakeMoogle() ? 0.5F : 1.0F); } matrixStackIn.push(); } else { super.render(entityIn, entityYaw, partialTicks, matrixStackIn, bufferIn, packedLightIn); } } @Override public ResourceLocation getEntityTexture(MoogleEntity entity) { if (!entity.isFakeMoogle()) { return new ResourceLocation(KingdomKeys.MODID, "textures/entity/mob/moogle.png"); } else { return new ResourceLocation(KingdomKeys.MODID, "textures/entity/mob/fake_moogle.png"); } } @Nullable @Override //probably is called getRenderType or something protected RenderType func_230496_a_(MoogleEntity p_230496_1_, boolean p_230496_2_, boolean p_230496_3_, boolean p_230496_4_) { return super.func_230496_a_(p_230496_1_, p_230496_2_, p_230496_3_, p_230496_4_); } public static class Factory implements IRenderFactory<MoogleEntity> { @Override public EntityRenderer<? super MoogleEntity> createRenderFor(EntityRendererManager entityRendererManager) { return new MoogleRenderer(entityRendererManager); } } }
C++
UTF-8
1,372
2.671875
3
[]
no_license
#include<bits/stdc++.h> #define ll long long int using namespace std; int main() { int t; cin>>t; for(int i=1;i<=t;i++) { stack<string>backward; stack<string>forward; string current="http://www.lightoj.com/"; string s; printf("Case %d:\n",i); while(cin>>s) { if(s=="QUIT")break; if(s=="VISIT"){ string ss; cin>>ss; backward.push(current); current=ss; cout<<current<<endl; stack<string>news; forward=news; } if(s=="BACK") { if(backward.size()==0) cout<<"Ignored"<<endl; else{ forward.push(current); current=backward.top(); backward.pop(); cout<<current<<endl; } } if(s=="FORWARD") { if(forward.size()==0)cout<<"Ignored"<<endl; else{ backward.push(current); current=forward.top(); forward.pop(); cout<<current<<endl; } } } } return 0; }
PHP
UTF-8
2,278
2.84375
3
[ "MIT" ]
permissive
<?php namespace lajax\translatemanager\services; use yii\helpers\Console; use lajax\translatemanager\services\Scanner; use lajax\translatemanager\models\LanguageSource; /** * Optimizer class for optimizing database tables * * @author Lajos Molnár <lajax.m@gmail.com> * @since 1.0 */ class Optimizer { /** * @var Scanner */ private $_scanner; /** * @var array a Current language elements in the translating system */ private $_languageElements = []; /** * Removing unused language elements from database. * @return int Number of unused language elements detected. * @deprecated since version 1.4 */ public function optimization() { return $this->run(); } /** * Removing unused language elements from database. * @return integer The number of removed language elements. */ public function run() { $this->_scanner = new Scanner; $this->_scanner->run(); $this->_scanner->stdout('Deleted language elements - BEGIN', Console::FG_RED); $languageSourceIds = $this->_scanner->getRemovableLanguageSourceIds(); $this->_initLanguageElements($languageSourceIds); LanguageSource::deleteAll(['id' => $languageSourceIds]); $this->_scanner->stdout('Deleted language elements - END', Console::FG_RED); return count($languageSourceIds); } /** * Returns removed language elements. * @return array */ public function getRemovedLanguageElements() { return $this->_languageElements; } /** * Initializing $_languageElements array. * @param array $languageSourceIds */ private function _initLanguageElements($languageSourceIds) { $languageSources = LanguageSource::findAll(['id' => $languageSourceIds]); foreach ($languageSources as $languageSource) { $this->_languageElements[$languageSource->category][$languageSource->message] = $languageSource->id; $category = Console::ansiFormat($languageSource->category, [Console::FG_RED]); $message = Console::ansiFormat($languageSource->message, [Console::FG_RED]); $this->_scanner->stdout('category: ' . $category . ', message: ' . $message); } } }
JavaScript
UTF-8
1,417
2.734375
3
[]
no_license
const initState={ posts:[], post:null } const getPostsReducer=(state=initState,action)=>{ switch(action.type){ case "GET_POSTS": return{ ...state, posts:action.posts } case "GET_POST": return{ ...state, post:action.post } case "ADD_POST": return{ ...state, posts:[...state.posts,action.post] } case "DELETE_POST": const postList=state.posts.map(post=>{ if(post._id !== action.id){ return post; } }) return{ ...state, // posts:postList, post:null } case "UPDATE_POST": const postsList=state.posts.map(post=>{ if(post._id === action.id){ post.title = action.body.title; post.body =action.body.body; } return post; }) console.log(postsList); return{ ...state, posts:postsList } case "CLEAN_POST": return{ ...state, post:null } default: return state } } export default getPostsReducer
Java
GB18030
71,452
2.734375
3
[]
no_license
package strategy9Enhance; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Properties; //횫@ȡÿrgγ public class Strategy9Enhance { public static void main(String[] args) throws IOException { ArrayList<Double> result = new ArrayList<Double>(); double patternCount = 0; double profitTime = 0; double lossTime = 0; double totalProfit = 0; double maxloss = 0; double patternDivideCount = 0; double totalLoss = 0; File file = new File(workPath() + "/input"); File[] fileArr = file.listFiles(); for (int i = 0; i < fileArr.length; i++) { result = strategy9(fileArr[i]); patternCount += result.get(0); patternCount += result.get(5); profitTime += result.get(1); lossTime += result.get(2); totalProfit += result.get(3); maxloss += result.get(4); patternDivideCount += result.get(5); totalLoss+=result.get(6); } writeTxt(workPath() + "/history.txt", "patternF" + (int)patternCount + "2ǰ1r"+(int)patternDivideCount+" "+(int)patternCount+" гɽ" + (int)(profitTime + lossTime) + " @ " + totalProfit + " @Δ " + (int)profitTime + " ̝pΔ " + (int)lossTime + " " + ((double) profitTime / (double) (profitTime + lossTime)) * 100 + "% _̝p"+maxloss+""+" Ѯa̝pĆȫõ̝p~"+totalLoss+"c", true); System.out.println("patternF" + (int) patternCount + " 2ǰ1r" + (int) patternDivideCount + " " + (int) patternCount + "гɽ" + (int) (profitTime + lossTime) + " @ " + totalProfit + " @Δ " + (int) profitTime + " ̝pΔ " + (int) lossTime + " " + ((double) profitTime / (double) (profitTime + lossTime)) * 100 + "% _̝p" + maxloss + ""+" Ѯa̝pĆȫõ̝p~"+totalLoss+"c"); } // File file,int timeRange,double spread,double markup,int multiple,int // laterNumber,int firstProfit,int secondProfit,int maxLoss public static ArrayList<Double> strategy9(File file) throws IOException { ArrayList<Double> result = new ArrayList<Double>(); Properties properties = new Properties(); File fileConfig = new File(workPath() + "/config.ini"); FileInputStream fis = new FileInputStream(fileConfig); properties.load(fis); fis.close(); BufferedReader br = new BufferedReader(new FileReader(file)); String line = null; int timeRange = Integer.parseInt(properties.getProperty("timeRange")); double spread = Integer.parseInt(properties.getProperty("spread")); double markup = Integer.parseInt(properties.getProperty("markup")); int multiple = Integer.parseInt(properties.getProperty("multiple")); int laterNumber = Integer.parseInt(properties.getProperty("laterNumber")); int firstProfit = Integer.parseInt(properties.getProperty("firstProfit")); int secondProfit = Integer.parseInt(properties.getProperty("secondProfit")); int maxLoss = Integer.parseInt(properties.getProperty("maxLoss")); // xListtimeListbrg List<String> timeList = new ArrayList<String>(); // xListpriceListbɽr List<Double> priceList = new ArrayList<Double>(); // xListvolumeListbɽ List<Double> volumeList = new ArrayList<Double>(); // xListindexListbÿrg_ʼ List<Integer> indexList = new ArrayList<Integer>(); // xListnewIndexListindexListеBmȡһMnewIndexList List<Integer> newIndexList = new ArrayList<Integer>(); // xListopenNowbÿrgε_Pr List<Double> openNow = new ArrayList<Double>(); // xListhighNowbÿrgε߃r List<Double> highNow = new ArrayList<Double>(); // xListlowNowbÿrgἐr List<Double> lowNow = new ArrayList<Double>(); // xListcloseNowbÿrgεձPr List<Double> closeNow = new ArrayList<Double>(); // xListvolumeNowbÿrgεĿ List<Double> volumeNow = new ArrayList<Double>(); // xListpatternIndexbpatternFĕrgγ List<Integer> patternIndex = new ArrayList<Integer>(); // xListpatternIndexbɸǰһǷNpatternFĕrgγ List<Integer> patternDivideIndex = new ArrayList<Integer>(); // xListkeyPatternbpatternFĴ_Еrg(_Ηl) List<Integer> keyPattern = new ArrayList<Integer>(); // xListpatternNewIndexbpatternFĴ_ЕrgnewIndexListλ List<Integer> patternNewIndex = new ArrayList<Integer>(); // xListpatternDivideNewIndexbpatternFĴ_ЕrgnewIndexListλ List<Integer> patternDivideNewIndex = new ArrayList<Integer>(); // xListkeyPatternIndexbkeyPatternnewIndexListλ List<Integer> keyPatternIndex = new ArrayList<Integer>(); // xListdynamicHighPricebPatternFrĮǰ߃r List<Double> dynamicHighPrice = new ArrayList<Double>(); // xListdynamicLowPricebPatternFrĮǰ̓r List<Double> dynamicLowPrice = new ArrayList<Double>(); // xListbuyTypebIMķN(Նζ) List<Integer> buyType = new ArrayList<Integer>(); // xListbuyIndexbɽεĕrg List<Integer> buyIndex = new ArrayList<Integer>(); // xListbuyKeyPatternbɽrgĕrg List<Integer> buyKeyPattern = new ArrayList<Integer>(); // xListbuyPricebIMĜʴ_rλ List<Double> buyPrice = new ArrayList<Double>(); int profitTime = 0; int lossTime = 0; double totalProfit = 0; double totalLoss = 0; double firstPercent = 50; double secondPercent = 50; // ======================̎rgList====================== while ((line = br.readLine()) != null) { String[] item = line.split(","); if (isTitle(item[3])) { continue; // ДǷtitle } timeList.add(item[2]); priceList.add(Double.parseDouble(item[3])); volumeList.add(Double.parseDouble(item[4])); } br.close(); // @ȡYϹP int totalSize = timeList.size(); // vוrg // System.out.println(timeList); // vɽr // System.out.println(priceList); // vɽ // System.out.println(volumeList); // @ȡÿrgγ int timeRangeToHour = timeRange / 60; for (int i = 0; i < totalSize; i++) { int minute = Integer.parseInt(timeList.get(i).substring(15, 17)); int hour = Integer.parseInt(timeList.get(i).substring(12, 14)); // System.out.println(timeList.get(i)); if (timeRange <= 60) { if (minute % timeRange == 0) { indexList.add(i); } } else { if (hour % timeRangeToHour == 0 && minute % timeRange == 0) { indexList.add(i); } } } // @ȡrgγĹP totalSize = indexList.size(); // indexListеBmȡһMnewIndexList // ȰindexListеĵһMnewIndexList // System.out.println(indexList); if (indexList.isEmpty()) { result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); return result; } newIndexList.add(indexList.get(0)); for (int i = 0; i < totalSize - 1; i++) { if (i + 1 < totalSize - 1 && indexList.get(i + 1) - indexList.get(i) != 1) { newIndexList.add(indexList.get(i + 1)); } } // System.out.println(newIndexList); // vÿrgγ // ======================̎_PrList====================== for (int i = 0; i < newIndexList.size(); i++) { openNow.add(priceList.get(newIndexList.get(i))); } // System.out.println(openNow); //vÿrgγ_Pr // ======================̎߃rList====================== double maxPrice = 0; for (int i = 0; i < newIndexList.size() - 1; i++) { for (int j = newIndexList.get(i); j < newIndexList.get(i + 1); j++) { if (priceList.get(j) > maxPrice) { maxPrice = priceList.get(j); } } highNow.add(maxPrice); maxPrice = 0; } // System.out.println(highNow); //vÿrgε߃r // ======================̎̓rList====================== double minPrice = 10000; for (int i = 0; i < newIndexList.size() - 1; i++) { for (int j = newIndexList.get(i); j < newIndexList.get(i + 1); j++) { if (priceList.get(j) < minPrice) { minPrice = priceList.get(j); } } lowNow.add(minPrice); minPrice = 10000; } // System.out.println(lowNow); //vÿrgἐr // ======================̎ձPrList====================== for (int i = 0; i < newIndexList.size() - 1; i++) { closeNow.add(priceList.get(newIndexList.get(i + 1) - 1)); } // System.out.println(closeNow); //vÿrgεձPr // ======================̎rgεĿList====================== double volume = 0; for (int i = 0; i < newIndexList.size() - 1; i++) { for (int j = newIndexList.get(i); j < newIndexList.get(i + 1); j++) { volume += volumeList.get(j); } volumeNow.add(volume); volume = 0; } // System.out.println(volumeNow); //vÿrgεĿ // ======================̎patternĕrgμnewIndexList====================== // *****x_PorձP????????***** // patternFĴΔ int patternCount = 0; int patternDivideCount = 0; for (int i = 0; i < newIndexList.size() - 1; i++) { if (i - 2 >= 0) { if ((Math.abs(lowNow.get(i) - highNow.get(i)) >= spread) && (volumeNow.get(i) / volumeNow.get(i - 1) >= multiple)) { patternIndex.add(newIndexList.get(i)); patternNewIndex.add(i); patternCount++; } else { if ((Math.abs(lowNow.get(i) - highNow.get(i)) >= spread && (volumeNow.get(i) + volumeNow.get(i - 1)) / volumeNow.get(i - 2) >= multiple)) { if(volumeNow.get(i - 1)/volumeNow.get(i - 2)<=multiple||(volumeNow.get(i - 1)/volumeNow.get(i - 2)>=multiple&&Math.abs(lowNow.get(i-1) - highNow.get(i-1)) < spread)){ patternDivideIndex.add(newIndexList.get(i)); patternDivideNewIndex.add(i); patternDivideCount++; } } } } } // System.out.println(patternCount); // System.out.println(patternDivideCount); // System.out.println("patternlĕrgγ" + patternIndex); // // vÿpatternlĕrgγ // System.out.println(patternCount);//patternFĴΔ // System.out.println(patternNewIndex);//vÿpatternFĕrgnewIndexListλ // System.out.println(patternIndex.get(0)); // System.out.println(newIndexList.get(40)); // ======================̎keyPattern====================== // ****ӑB߃r̓r(SkeyPatternrg{) double volumeNumber = 0; double dynamicHigh = 0; double dynamicLow = 10000; // ******pattern****** for (int i = 0; i < patternCount; i++) { // patternFǿ̕rgһֱߵһrg for (int j = patternIndex.get(i); j < newIndexList.get(patternNewIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } volumeNumber += volumeList.get(j); // ǂrg;е^ǰһmultiple҄ӑB߃r̓rxЃr^spreadԒtԔlĕrgkeyPattern if (volumeNumber > volumeNow.get(patternNewIndex.get(i) - 1) * multiple && (dynamicHigh - priceList.get(j) >= spread || priceList.get(j) - dynamicLow >= spread)) { keyPattern.add(j); keyPatternIndex.add(patternNewIndex.get(i)); dynamicHighPrice.add(dynamicHigh); dynamicLowPrice.add(dynamicLow); break; } } volumeNumber = 0; dynamicHigh = 0; dynamicLow = 10000; } // ******dividePattern****** ArrayList<Integer> keyDividePattern = new ArrayList<Integer>(); ArrayList<Integer> keyDividePatternIndex = new ArrayList<Integer>(); ArrayList<Double> dynamicDivideHighPrice = new ArrayList<Double>(); ArrayList<Double> dynamicDivideLowPrice = new ArrayList<Double>(); for (int i = 0; i < patternDivideCount; i++) { // dividePatternFǿ̕rgһֱߵһrg volumeNumber += volumeNow.get(patternDivideNewIndex.get(i) - 1); for (int j = patternDivideIndex.get(i); j < newIndexList.get(patternDivideNewIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } volumeNumber += volumeList.get(j); // System.out.println(volumeNumber); // ǂrg;е^ǰһmultiple҄ӑB߃r̓rxЃr^spreadԒtԔlĕrgkeyDividePattern if (volumeNumber > volumeNow.get(patternDivideNewIndex.get(i) - 2) * multiple && (dynamicHigh - priceList.get(j) >= spread || priceList.get(j) - dynamicLow >= spread)) { keyDividePattern.add(j); keyDividePatternIndex.add(patternDivideNewIndex.get(i)); dynamicDivideHighPrice.add(dynamicHigh); dynamicDivideLowPrice.add(dynamicLow); // System.out.println(volumeNow.get(patternDivideNewIndex.get(i) // - 2)); // System.out.println(dynamicHigh); // System.out.println(dynamicLow); break; } } volumeNumber = 0; dynamicHigh = 0; dynamicLow = 10000; } // System.out.println("keyDividePattern(_Ηl)ĕrg" + // keyDividePattern);// vÿkeyDividePattern(_Ηl)ĕrg // System.out.println("keyPattern(_Ηl)ĕrg" + keyPattern); // // vÿkeyPattern(_Ηl)ĕrg // System.out.println(keyPatternIndex); // System.out.println(newIndexList.get(keyPatternIndex.get(0)+1)); // System.out.println(dynamicHighPrice);//vÿ_keyPatternrǰo䛵߃r // System.out.println(dynamicLowPrice);//vÿ_keyPatternrǰo䛵̓r // ======================֮̎ɽԔr(pattern)====================== int countPatternVersion = 0; // System.out.println(priceList.get(patternIndex.get(0))); //@ȡrgγăr for (int i = 0; i < keyPattern.size(); i++) { // keyPattern_ʼһֱǸY // dynamicHigh = dynamicHighPrice.get(i); // dynamicLow = dynamicLowPrice.get(i); // System.out.println(dynamicHigh); // System.out.println(dynamicLow); dynamicHigh = 0; dynamicLow = 10000; for (int j = keyPattern.get(i); j < newIndexList.get(keyPatternIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } // keyPatternǰ߃rpkeyPattern̵ărspreadԒǜʂAbuy if (dynamicHighPrice.get(i) - priceList.get(keyPattern.get(i)) > spread && priceList.get(j) <= priceList.get(keyPattern.get(i)) - markup && priceList.get(patternIndex.get(i)) - priceList.get(keyPattern.get(i)) > 0) { buyType.add(1); buyIndex.add(j); buyPrice.add(priceList.get(keyPattern.get(i)) - markup); buyKeyPattern.add(keyPatternIndex.get(i)); countPatternVersion++; break; } else if (priceList.get(keyPattern.get(i)) - dynamicLowPrice.get(i) > spread && priceList.get(j) >= priceList.get(keyPattern.get(i)) + markup && priceList.get(keyPattern.get(i)) - priceList.get(patternIndex.get(i)) > 0) { // System.out.println(dynamicHigh); // System.out.println(dynamicLow); buyType.add(2); buyIndex.add(j); // IMrλpriceList.get(keyPattern.get(i)) + markup buyPrice.add(priceList.get(keyPattern.get(i)) + markup); buyKeyPattern.add(keyPatternIndex.get(i)); break; } } } // System.out.println(keyPattern); // System.out.println(buyType); // vIMķN(BUYorSELL) // System.out.println(buyIndex); // vIMĕrg // System.out.println(buyKeyPattern);// vIMr̵ĕrg // System.out.println(newIndexList.size()); // System.out.println(buyIndex.size()); // ======================֮̎ɽԔr(dividePattern)====================== for (int i = 0; i < keyDividePattern.size(); i++) { // keyPattern_ʼһֱǸY // dynamicHigh = dynamicHighPrice.get(i); // dynamicLow = dynamicLowPrice.get(i); // System.out.println(dynamicHigh); // System.out.println(dynamicLow); dynamicHigh = 0; dynamicLow = 10000; for (int j = keyDividePattern.get(i); j < newIndexList.get(keyDividePatternIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } // keyPatternǰ߃rpkeyPattern̵ărspreadԒǜʂAbuy if (dynamicDivideHighPrice.get(i) - priceList.get(keyDividePattern.get(i)) > spread && priceList.get(j) <= priceList.get(keyDividePattern.get(i)) - markup && priceList.get(patternDivideIndex.get(i)) - priceList.get(keyDividePattern.get(i)) > 0) { buyType.add(1); buyIndex.add(j); buyPrice.add(priceList.get(keyDividePattern.get(i)) - markup); buyKeyPattern.add(keyDividePatternIndex.get(i)); break; } else if (priceList.get(keyDividePattern.get(i)) - dynamicDivideLowPrice.get(i) > spread && priceList.get(j) >= priceList.get(keyDividePattern.get(i)) + markup && priceList.get(keyDividePattern.get(i)) - priceList.get(patternDivideIndex.get(i)) > 0) { // System.out.println(dynamicHigh); // System.out.println(dynamicLow); buyType.add(2); buyIndex.add(j); // IMrλpriceList.get(keyPattern.get(i)) + markup buyPrice.add(priceList.get(keyDividePattern.get(i)) + markup); buyKeyPattern.add(keyDividePatternIndex.get(i)); break; } } } // ======================̎ɽ֮ī@ͣpr====================== for (int i = 0; i < buyIndex.size(); i++) { // newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) // ֹYϱ if (buyKeyPattern.get(i) + laterNumber + 1 > newIndexList.size() - 1) { break; } // buy if (buyType.get(i) == 1) { // IMһֱߵͣprg(laterNumber) for (int j = buyIndex.get(i); j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { // Ѓr-IMr(buy)>-firstProfit if (priceList.get(j) - buyPrice.get(i) >= firstProfit) { totalProfit += firstProfit * firstPercent / 100; if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out .println("[Buy]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "urg" + timeList.get(j) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + firstProfit + "c"); writeTxt(workPath() + "/history.txt", "[Buy]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "urg" + timeList.get(j) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + firstProfit + "c", true); } else { System.out .println("[Buy]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "urg" + timeList.get(j) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + firstProfit + "c"); writeTxt(workPath() + "/history.txt", "[Buy]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "urg" + timeList.get(j) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + firstProfit + "c", true); } for (; j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { if (priceList.get(j) - buyPrice.get(i) >= secondProfit) { profitTime++; totalProfit += secondProfit * secondPercent / 100; System.out.println("[Buy]ϲ," + timeList.get(j) + "u,@" + secondProfit + "c"); writeTxt(workPath() + "/history.txt", "[Buy]ϲ," + timeList.get(j) + "u,@" + secondProfit + "c", true); System.out.println("============================================================="); writeTxt(workPath() + "/history.txt", "=============================================================", true); break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += (priceList.get(j) - buyPrice.get(i)) * secondPercent / 100; if (firstProfit * firstPercent / 100 + (priceList.get(j) - buyPrice.get(i)) * secondPercent / 100 > 0) { profitTime++; } else { lossTime++; } System.out.println("[Buy]***ͣp***,ϧ" + timeList.get(j) + "ͣp,@" + (priceList.get(j) - buyPrice.get(i)) + "c"); writeTxt(workPath() + "/history.txt", "[Buy]***ͣp***,ϧ" + timeList.get(j) + "ͣp,@" + (priceList.get(j) - buyPrice.get(i)) + "c", true); System.out.println("============================================================="); writeTxt(workPath() + "/history.txt", "=============================================================", true); break; } } break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += priceList.get(j) - buyPrice.get(i); if (priceList.get(j) - buyPrice.get(i) > 0) { profitTime++; } else { lossTime++; } if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out.println("[Buy]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + (priceList.get(j) - buyPrice.get(i)) + "c"); writeTxt(workPath() + "/history.txt", "[Buy]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + (priceList.get(j) - buyPrice.get(i)) + "c", true); } else { System.out.println("[Buy]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + (priceList.get(j) - buyPrice.get(i)) + "c"); writeTxt(workPath() + "/history.txt", "[Buy]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + (priceList.get(j) - buyPrice.get(i)) + "c", true); } System.out.println("============================================================="); writeTxt(workPath() + "/history.txt", "=============================================================", true); break; } } // sell } else if (buyType.get(i) == 2) { // IMһֱߵͣprg(laterNumber) for (int j = buyIndex.get(i); j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { // IMr(sell)-Ѓr>-firstProfit if (buyPrice.get(i) - priceList.get(j) >= firstProfit) { totalProfit += firstProfit * firstPercent / 100; // System.out.println("@"+firstProfit*firstPercent/100); if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out.println("[Sell]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + "urg" + timeList.get(j) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + firstProfit + "c"); writeTxt(workPath() + "/history.txt", "[Sell]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + "urg" + timeList.get(j) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + firstProfit + "c", true); } else { System.out.println("[Sell]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + "urg" + timeList.get(j) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + firstProfit + "c"); writeTxt(workPath() + "/history.txt", "[Sell]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + "urg" + timeList.get(j) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + firstProfit + "c", true); } // ͣһֱߵͣprg(laterNumber) for (; j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { if (buyPrice.get(i) - priceList.get(j) >= secondProfit) { profitTime++; totalProfit += secondProfit * secondPercent / 100; // System.out.println("@"+secondProfit*secondPercent/100); System.out.println("[Sell]ϲ," + timeList.get(j) + "u,@" + secondProfit + "c"); writeTxt(workPath() + "/history.txt", "[Sell]ϲ," + timeList.get(j) + "u,@" + secondProfit + "c", true); System.out.println("============================================================="); writeTxt(workPath() + "/history.txt", "=============================================================", true); break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += (buyPrice.get(i) - priceList.get(j)) * secondPercent / 100; // System.out.println("@"+(buyPrice.get(i) - // priceList.get(j))*secondPercent/100); if (firstProfit * firstPercent / 100 + (buyPrice.get(i) - priceList.get(j)) * secondPercent / 100 > 0) { profitTime++; } else { lossTime++; } System.out.println("[Sell]***ͣp***,ϧ" + timeList.get(j) + "ͣp,@" + (buyPrice.get(i) - priceList.get(j)) + "c"); writeTxt(workPath() + "/history.txt", "[Sell]***ͣp***,ϧ" + timeList.get(j) + "ͣp,@" + (buyPrice.get(i) - priceList.get(j)) + "c", true); System.out.println("============================================================="); writeTxt(workPath() + "/history.txt", "=============================================================", true); break; } } break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += buyPrice.get(i) - priceList.get(j); // System.out.println("@"+(buyPrice.get(i) - // priceList.get(j))); if (buyPrice.get(i) - priceList.get(j) > 0) { profitTime++; } else { lossTime++; } if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out.println("[Sell]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + (buyPrice.get(i) - priceList.get(j)) + "c"); writeTxt(workPath() + "/history.txt", "[Sell]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + (buyPrice.get(i) - priceList.get(j)) + "c", true); } else { System.out.println("[Sell]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + (buyPrice.get(i) - priceList.get(j)) + "c"); writeTxt(workPath() + "/history.txt", "[Sell]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + (buyPrice.get(i) - priceList.get(j)) + "c", true); } System.out.println("============================================================="); writeTxt(workPath() + "/history.txt", "=============================================================", true); break; } } } } // System.out.println("patternF" + patternCount + " ɽ" + (profitTime // + lossTime) + " @ " + totalProfit // + " @Δ " + profitTime + " ̝pΔ " + lossTime + " " // + ((double) profitTime / (double) (profitTime + lossTime)) * 100 + // "%"); // writeTxt(workPath() + "/history.txt", // "patternF" + patternCount + " ɽ" + (profitTime + lossTime) + " // @ " + totalProfit + " @Δ " // + profitTime + " ̝pΔ " + lossTime + " " // + ((double) profitTime / (double) (profitTime + lossTime)) * 100 + // "%", // true); // System.out.println("@Ӌ㷽ʽ (һͣc) " + firstProfit + " x // (һͣcuĂ}λٷֱ) " + firstPercent + "%" // + " + (ڶͣc) " + secondProfit + " x (ڶͣcuĂ}λٷֱ)" + // secondPercent + "%"); // writeTxt(workPath() + "/history.txt", "@Ӌ㷽ʽ (һͣc) " + // firstProfit + " x (һͣcuĂ}λٷֱ) " + firstPercent // + "%" + " + (ڶͣc) " + secondProfit + " x (ڶͣcuĂ}λٷֱ)" + // secondPercent + "%", true); writeTxt(workPath() + "/history.txt", "", true); // ======================̝̎pПo_maxLoss====================== int maxloss = 0; for (int i = 0; i < buyIndex.size(); i++) { if (buyKeyPattern.get(i) + laterNumber + 1 > newIndexList.size() - 1) { break; } for (int j = buyIndex.get(i); j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { // buy if (buyType.get(i) == 1) { // Ir-ЃrmaxLoss if (priceList.get(j) - buyPrice.get(i) >= secondProfit) { break; } if (buyPrice.get(i) - priceList.get(j) >= maxLoss) { maxloss++; writeTxt(workPath() + "/history.txt", "" + timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) + ",IMrg" + timeList.get(buyIndex.get(i)), true); System.out.println("" + timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) + ",IMrg" + timeList.get(buyIndex.get(i))); break; } } else if (buyType.get(i) == 2) { // Ir-ЃrmaxLoss if (buyPrice.get(i) - priceList.get(j) >= secondProfit) { break; } if (priceList.get(j) - buyPrice.get(i) >= maxLoss) { maxloss++; writeTxt(workPath() + "/history.txt", "" + timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) + ",IMrg" + timeList.get(buyIndex.get(i)), true); System.out.println("" + timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) + ",IMrg" + timeList.get(buyIndex.get(i))); break; } } } } result.add((double) patternCount); result.add((double) profitTime); result.add((double) lossTime); result.add(totalProfit); result.add((double) maxloss); result.add((double) patternDivideCount); result.add(totalLoss); return result; } public static ArrayList<Double> strategyRandom9(File file, int timeRange, double spread, double markup, int multiple, int laterNumber, int firstProfit, int secondProfit, int maxLoss) throws IOException { double totalLoss = 0; ArrayList<Double> result = new ArrayList<Double>(); Properties properties = new Properties(); File fileConfig = new File(workPath() + "/config.ini"); FileInputStream fis = new FileInputStream(fileConfig); properties.load(fis); fis.close(); BufferedReader br = new BufferedReader(new FileReader(file)); String line = null; /* * int timeRange = * Integer.parseInt(properties.getProperty("timeRange")); double spread * = Integer.parseInt(properties.getProperty("spread")); double markup = * Integer.parseInt(properties.getProperty("markup")); int multiple = * Integer.parseInt(properties.getProperty("multiple")); int laterNumber * = Integer.parseInt(properties.getProperty("laterNumber")); int * firstProfit = * Integer.parseInt(properties.getProperty("firstProfit")); int * secondProfit = * Integer.parseInt(properties.getProperty("secondProfit")); int maxLoss * = Integer.parseInt(properties.getProperty("maxLoss")); */ // xListtimeListbrg List<String> timeList = new ArrayList<String>(); // xListpriceListbɽr List<Double> priceList = new ArrayList<Double>(); // xListvolumeListbɽ List<Double> volumeList = new ArrayList<Double>(); // xListindexListbÿrg_ʼ List<Integer> indexList = new ArrayList<Integer>(); // xListnewIndexListindexListеBmȡһMnewIndexList List<Integer> newIndexList = new ArrayList<Integer>(); // xListopenNowbÿrgε_Pr List<Double> openNow = new ArrayList<Double>(); // xListhighNowbÿrgε߃r List<Double> highNow = new ArrayList<Double>(); // xListlowNowbÿrgἐr List<Double> lowNow = new ArrayList<Double>(); // xListcloseNowbÿrgεձPr List<Double> closeNow = new ArrayList<Double>(); // xListvolumeNowbÿrgεĿ List<Double> volumeNow = new ArrayList<Double>(); // xListpatternIndexbpatternFĕrgγ List<Integer> patternIndex = new ArrayList<Integer>(); // xListpatternIndexbɸǰһǷNpatternFĕrgγ List<Integer> patternDivideIndex = new ArrayList<Integer>(); // xListkeyPatternbpatternFĴ_Еrg(_Ηl) List<Integer> keyPattern = new ArrayList<Integer>(); // xListpatternNewIndexbpatternFĴ_ЕrgnewIndexListλ List<Integer> patternNewIndex = new ArrayList<Integer>(); // xListpatternDivideNewIndexbpatternFĴ_ЕrgnewIndexListλ List<Integer> patternDivideNewIndex = new ArrayList<Integer>(); // xListkeyPatternIndexbkeyPatternnewIndexListλ List<Integer> keyPatternIndex = new ArrayList<Integer>(); // xListdynamicHighPricebPatternFrĮǰ߃r List<Double> dynamicHighPrice = new ArrayList<Double>(); // xListdynamicLowPricebPatternFrĮǰ̓r List<Double> dynamicLowPrice = new ArrayList<Double>(); // xListbuyTypebIMķN(Նζ) List<Integer> buyType = new ArrayList<Integer>(); // xListbuyIndexbɽεĕrg List<Integer> buyIndex = new ArrayList<Integer>(); // xListbuyKeyPatternbɽrgĕrg List<Integer> buyKeyPattern = new ArrayList<Integer>(); // xListbuyPricebIMĜʴ_rλ List<Double> buyPrice = new ArrayList<Double>(); int profitTime = 0; int lossTime = 0; double totalProfit = 0; double firstPercent = 50; double secondPercent = 50; // ======================̎rgList====================== while ((line = br.readLine()) != null) { String[] item = line.split(","); if (isTitle(item[3])) { continue; // ДǷtitle } timeList.add(item[2]); priceList.add(Double.parseDouble(item[3])); volumeList.add(Double.parseDouble(item[4])); } br.close(); // @ȡYϹP int totalSize = timeList.size(); // vוrg // System.out.println(timeList); // vɽr // System.out.println(priceList); // vɽ // System.out.println(volumeList); // @ȡÿrgγ int timeRangeToHour = timeRange / 60; for (int i = 0; i < totalSize; i++) { int minute = Integer.parseInt(timeList.get(i).substring(15, 17)); int hour = Integer.parseInt(timeList.get(i).substring(12, 14)); // System.out.println(timeList.get(i)); if (timeRange <= 60) { if (minute % timeRange == 0) { indexList.add(i); } } else { if (hour % timeRangeToHour == 0 && minute % timeRange == 0) { indexList.add(i); } } } // @ȡrgγĹP totalSize = indexList.size(); // indexListеBmȡһMnewIndexList // ȰindexListеĵһMnewIndexList // System.out.println(indexList); if (indexList.isEmpty()) { result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); result.add((double) 0); return result; } newIndexList.add(indexList.get(0)); for (int i = 0; i < totalSize - 1; i++) { if (i + 1 < totalSize - 1 && indexList.get(i + 1) - indexList.get(i) != 1) { newIndexList.add(indexList.get(i + 1)); } } // System.out.println(newIndexList); // vÿrgγ // ======================̎_PrList====================== for (int i = 0; i < newIndexList.size(); i++) { openNow.add(priceList.get(newIndexList.get(i))); } // System.out.println(openNow); //vÿrgγ_Pr // ======================̎߃rList====================== double maxPrice = 0; for (int i = 0; i < newIndexList.size() - 1; i++) { for (int j = newIndexList.get(i); j < newIndexList.get(i + 1); j++) { if (priceList.get(j) > maxPrice) { maxPrice = priceList.get(j); } } highNow.add(maxPrice); maxPrice = 0; } // System.out.println(highNow); //vÿrgε߃r // ======================̎̓rList====================== double minPrice = 10000; for (int i = 0; i < newIndexList.size() - 1; i++) { for (int j = newIndexList.get(i); j < newIndexList.get(i + 1); j++) { if (priceList.get(j) < minPrice) { minPrice = priceList.get(j); } } lowNow.add(minPrice); minPrice = 10000; } // System.out.println(lowNow); //vÿrgἐr // ======================̎ձPrList====================== for (int i = 0; i < newIndexList.size() - 1; i++) { closeNow.add(priceList.get(newIndexList.get(i + 1) - 1)); } // System.out.println(closeNow); //vÿrgεձPr // ======================̎rgεĿList====================== double volume = 0; for (int i = 0; i < newIndexList.size() - 1; i++) { for (int j = newIndexList.get(i); j < newIndexList.get(i + 1); j++) { volume += volumeList.get(j); } volumeNow.add(volume); volume = 0; } // System.out.println(volumeNow); //vÿrgεĿ // ======================̎patternĕrgμnewIndexList====================== // *****x_PorձP????????***** // patternFĴΔ int patternCount = 0; int patternDivideCount = 0; for (int i = 0; i < newIndexList.size() - 1; i++) { if (i - 2 >= 0) { if ((Math.abs(lowNow.get(i) - highNow.get(i)) >= spread) && (volumeNow.get(i) / volumeNow.get(i - 1) >= multiple)) { patternIndex.add(newIndexList.get(i)); patternNewIndex.add(i); patternCount++; } else { if ((Math.abs(lowNow.get(i) - highNow.get(i)) >= spread && (volumeNow.get(i) + volumeNow.get(i - 1)) / volumeNow.get(i - 2) >= multiple)) { if((volumeNow.get(i - 1)/volumeNow.get(i - 2)<=multiple)||(volumeNow.get(i - 1)/volumeNow.get(i - 2)>=multiple&&Math.abs(lowNow.get(i-1) - highNow.get(i-1)) < spread)){ patternDivideIndex.add(newIndexList.get(i)); patternDivideNewIndex.add(i); patternDivideCount++; } } } } } // System.out.println(patternCount); // System.out.println(patternDivideCount); // System.out.println("patternlĕrgγ" + patternIndex); // // vÿpatternlĕrgγ // System.out.println(patternCount);//patternFĴΔ // System.out.println(patternNewIndex);//vÿpatternFĕrgnewIndexListλ // System.out.println(patternIndex.get(0)); // System.out.println(newIndexList.get(40)); // ======================̎keyPattern====================== // ****ӑB߃r̓r(SkeyPatternrg{) double volumeNumber = 0; double dynamicHigh = 0; double dynamicLow = 10000; // ******pattern****** for (int i = 0; i < patternCount; i++) { // patternFǿ̕rgһֱߵһrg for (int j = patternIndex.get(i); j < newIndexList.get(patternNewIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } volumeNumber += volumeList.get(j); // ǂrg;е^ǰһmultiple҄ӑB߃r̓rxЃr^spreadԒtԔlĕrgkeyPattern if (volumeNumber > volumeNow.get(patternNewIndex.get(i) - 1) * multiple && (dynamicHigh - priceList.get(j) >= spread || priceList.get(j) - dynamicLow >= spread)) { keyPattern.add(j); keyPatternIndex.add(patternNewIndex.get(i)); dynamicHighPrice.add(dynamicHigh); dynamicLowPrice.add(dynamicLow); break; } } volumeNumber = 0; dynamicHigh = 0; dynamicLow = 10000; } // ******dividePattern****** ArrayList<Integer> keyDividePattern = new ArrayList<Integer>(); ArrayList<Integer> keyDividePatternIndex = new ArrayList<Integer>(); ArrayList<Double> dynamicDivideHighPrice = new ArrayList<Double>(); ArrayList<Double> dynamicDivideLowPrice = new ArrayList<Double>(); for (int i = 0; i < patternDivideCount; i++) { // dividePatternFǿ̕rgһֱߵһrg volumeNumber += volumeNow.get(patternDivideNewIndex.get(i) - 1); for (int j = patternDivideIndex.get(i); j < newIndexList.get(patternDivideNewIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } volumeNumber += volumeList.get(j); // System.out.println(volumeNumber); // ǂrg;е^ǰһmultiple҄ӑB߃r̓rxЃr^spreadԒtԔlĕrgkeyDividePattern if (volumeNumber > volumeNow.get(patternDivideNewIndex.get(i) - 2) * multiple && (dynamicHigh - priceList.get(j) >= spread || priceList.get(j) - dynamicLow >= spread)) { keyDividePattern.add(j); keyDividePatternIndex.add(patternDivideNewIndex.get(i)); dynamicDivideHighPrice.add(dynamicHigh); dynamicDivideLowPrice.add(dynamicLow); // System.out.println(volumeNow.get(patternDivideNewIndex.get(i) // - 2)); // System.out.println(dynamicHigh); // System.out.println(dynamicLow); break; } } volumeNumber = 0; dynamicHigh = 0; dynamicLow = 10000; } // System.out.println("keyDividePattern(_Ηl)ĕrg" + // keyDividePattern);// vÿkeyDividePattern(_Ηl)ĕrg // System.out.println("keyPattern(_Ηl)ĕrg" + keyPattern); // // vÿkeyPattern(_Ηl)ĕrg // System.out.println(keyPatternIndex); // System.out.println(newIndexList.get(keyPatternIndex.get(0)+1)); // System.out.println(dynamicHighPrice);//vÿ_keyPatternrǰo䛵߃r // System.out.println(dynamicLowPrice);//vÿ_keyPatternrǰo䛵̓r // ======================֮̎ɽԔr(pattern)====================== // System.out.println(priceList.get(patternIndex.get(0))); //@ȡrgγăr int countPatternVersion = 0; for (int i = 0; i < keyPattern.size(); i++) { // keyPattern_ʼһֱǸY // dynamicHigh = dynamicHighPrice.get(i); // dynamicLow = dynamicLowPrice.get(i); // System.out.println(dynamicHigh); // System.out.println(dynamicLow); dynamicHigh = 0; dynamicLow = 10000; for (int j = keyPattern.get(i); j < newIndexList.get(keyPatternIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } // keyPatternǰ߃rpkeyPattern̵ărspreadԒǜʂAbuy if (dynamicHighPrice.get(i) - priceList.get(keyPattern.get(i)) > spread && priceList.get(j) <= priceList.get(keyPattern.get(i)) - markup && priceList.get(patternIndex.get(i)) - priceList.get(keyPattern.get(i)) > 0) { buyType.add(1); buyIndex.add(j); buyPrice.add(priceList.get(keyPattern.get(i)) - markup); buyKeyPattern.add(keyPatternIndex.get(i)); countPatternVersion++; break; } else if (priceList.get(keyPattern.get(i)) - dynamicLowPrice.get(i) > spread && priceList.get(j) >= priceList.get(keyPattern.get(i)) + markup && priceList.get(keyPattern.get(i)) - priceList.get(patternIndex.get(i)) > 0) { // System.out.println(dynamicHigh); // System.out.println(dynamicLow); buyType.add(2); buyIndex.add(j); // IMrλpriceList.get(keyPattern.get(i)) + markup buyPrice.add(priceList.get(keyPattern.get(i)) + markup); buyKeyPattern.add(keyPatternIndex.get(i)); break; } } } // System.out.println(buyIndex.size()); // System.out.println(keyPattern); // System.out.println(buyType); // vIMķN(BUYorSELL) // System.out.println(buyIndex); // vIMĕrg // System.out.println(buyKeyPattern);// vIMr̵ĕrg // System.out.println(newIndexList.size()); // ======================֮̎ɽԔr(dividePattern)====================== for (int i = 0; i < keyDividePattern.size(); i++) { // keyPattern_ʼһֱǸY // dynamicHigh = dynamicHighPrice.get(i); // dynamicLow = dynamicLowPrice.get(i); // System.out.println(dynamicHigh); // System.out.println(dynamicLow); dynamicHigh = 0; dynamicLow = 10000; for (int j = keyDividePattern.get(i); j < newIndexList.get(keyDividePatternIndex.get(i) + 1); j++) { if (priceList.get(j) > dynamicHigh) { dynamicHigh = priceList.get(j); } if (priceList.get(j) < dynamicLow) { dynamicLow = priceList.get(j); } // keyPatternǰ߃rpkeyPattern̵ărspreadԒǜʂAbuy if (dynamicDivideHighPrice.get(i) - priceList.get(keyDividePattern.get(i)) > spread && priceList.get(j) <= priceList.get(keyDividePattern.get(i)) - markup && priceList.get(patternDivideIndex.get(i)) - priceList.get(keyDividePattern.get(i)) > 0) { buyType.add(1); buyIndex.add(j); buyPrice.add(priceList.get(keyDividePattern.get(i)) - markup); buyKeyPattern.add(keyDividePatternIndex.get(i)); break; } else if (priceList.get(keyDividePattern.get(i)) - dynamicDivideLowPrice.get(i) > spread && priceList.get(j) >= priceList.get(keyDividePattern.get(i)) + markup && priceList.get(keyDividePattern.get(i)) - priceList.get(patternDivideIndex.get(i)) > 0) { // System.out.println(dynamicHigh); // System.out.println(dynamicLow); buyType.add(2); buyIndex.add(j); // IMrλpriceList.get(keyPattern.get(i)) + markup buyPrice.add(priceList.get(keyDividePattern.get(i)) + markup); buyKeyPattern.add(keyDividePatternIndex.get(i)); break; } } } // System.out.println(buyIndex.size()); // ======================̎ɽ֮ī@ͣpr====================== for (int i = 0; i < buyIndex.size(); i++) { // newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) // ֹYϱ if (buyKeyPattern.get(i) + laterNumber + 1 > newIndexList.size() - 1) { break; } // buy if (buyType.get(i) == 1) { // IMһֱߵͣprg(laterNumber) for (int j = buyIndex.get(i); j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { // Ѓr-IMr(buy)>-firstProfit if (priceList.get(j) - buyPrice.get(i) >= firstProfit) { totalProfit += firstProfit * firstPercent / 100; if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out .println("[Buy]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "urg" + timeList.get(j) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + firstProfit + "c"); } else { System.out .println("[Buy]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "urg" + timeList.get(j) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + firstProfit + "c"); } // writeTxt(workPath() + "/history.txt", // "[Buy]ϲ," + buyPrice.get(i) + "IM,IMrg" + // timeList.get(buyIndex.get(i)) + ",IMrg" // + // timeList.get(newIndexList.get(buyKeyPattern.get(i))) // + "urg" // + timeList.get(j) + "" + // volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" // + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + // firstProfit + "c", // true); for (; j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { if (priceList.get(j) - buyPrice.get(i) >= secondProfit) { profitTime++; totalProfit += secondProfit * secondPercent / 100; System.out.println("[Buy]ϲ," + timeList.get(j) + "u,@" + secondProfit + "c"); // writeTxt(workPath() + "/history.txt", // "[Buy]ϲ," + timeList.get(j) + "u,@" + // secondProfit + "c", true); System.out.println("============================================================="); // writeTxt(workPath() + "/history.txt", // "=============================================================", // true); break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += (priceList.get(j) - buyPrice.get(i)) * secondPercent / 100; if (firstProfit * firstPercent / 100 + (priceList.get(j) - buyPrice.get(i)) * secondPercent / 100 > 0) { profitTime++; } else { lossTime++; } // [pʧ~] if ((priceList.get(j) - buyPrice.get(i)) < 0) { totalLoss += (priceList.get(j) - buyPrice.get(i)) * secondPercent / 100; } System.out.println("[Buy]***ͣp***,ϧ" + timeList.get(j) + "ͣp,@" + (priceList.get(j) - buyPrice.get(i)) + "c"); // writeTxt(workPath() + "/history.txt", // "[Buy]***ͣp***,ϧ" + timeList.get(j) + // "ͣp,@" // + (priceList.get(j) - buyPrice.get(i)) + "c", // true); System.out.println("============================================================="); // writeTxt(workPath() + "/history.txt", // "=============================================================", // true); break; } } break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += priceList.get(j) - buyPrice.get(i); if (priceList.get(j) - buyPrice.get(i) > 0) { profitTime++; } else { lossTime++; } // [pʧ~] if ((priceList.get(j) - buyPrice.get(i)) < 0) { totalLoss += (priceList.get(j) - buyPrice.get(i)) * 1; } if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out.println("[Buy]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + (priceList.get(j) - buyPrice.get(i)) + "c"); } else { System.out.println("[Buy]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + (priceList.get(j) - buyPrice.get(i)) + "c"); } // writeTxt(workPath() + "/history.txt", // "[Buy]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" // + priceList.get(j) + "ͣp,IMrg" // + timeList.get(buyIndex.get(i)) + ",IMrg" // + // timeList.get(newIndexList.get(buyKeyPattern.get(i))) // + "ͣprg" // + timeList.get(j) + "," + // volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" // + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" // + (priceList.get(j) - buyPrice.get(i)) + "c", // true); System.out.println("============================================================="); // writeTxt(workPath() + "/history.txt", // "=============================================================", // true); break; } } // sell } else if (buyType.get(i) == 2) { // IMһֱߵͣprg(laterNumber) for (int j = buyIndex.get(i); j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { // IMr(sell)-Ѓr>-firstProfit if (buyPrice.get(i) - priceList.get(j) >= firstProfit) { totalProfit += firstProfit * firstPercent / 100; // System.out.println("@"+firstProfit*firstPercent/100); if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out.println("[Sell]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + "urg" + timeList.get(j) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + firstProfit + "c"); } else { System.out.println("[Sell]ϲ," + buyPrice.get(i) + "IM,IMrg" + timeList.get(buyIndex.get(i)) + "urg" + timeList.get(j) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "" + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + firstProfit + "c"); } // writeTxt(workPath() + "/history.txt", // "[Sell]ϲ," + buyPrice.get(i) + "IM,IMrg" + // timeList.get(buyIndex.get(i)) + "urg" // + timeList.get(j) + ",IMrg" // + // timeList.get(newIndexList.get(buyKeyPattern.get(i))) // + "" // + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" // + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + // firstProfit + "c", // true); // ͣһֱߵͣprg(laterNumber) for (; j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { if (buyPrice.get(i) - priceList.get(j) >= secondProfit) { profitTime++; totalProfit += secondProfit * secondPercent / 100; // System.out.println("@"+secondProfit*secondPercent/100); System.out.println("[Sell]ϲ," + timeList.get(j) + "u,@" + secondProfit + "c"); // writeTxt(workPath() + "/history.txt", // "[Sell]ϲ," + timeList.get(j) + "u,@" // + secondProfit + "c", true); System.out.println("============================================================="); // writeTxt(workPath() + "/history.txt", // "=============================================================", // true); break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += (buyPrice.get(i) - priceList.get(j)) * (secondPercent / 100); // System.out.println("@"+(buyPrice.get(i) - // priceList.get(j))*secondPercent/100); if (firstProfit * firstPercent / 100 + (buyPrice.get(i) - priceList.get(j)) * secondPercent / 100 > 0) { profitTime++; } else { lossTime++; } if ((buyPrice.get(i) - priceList.get(j)) < 0) { totalLoss += (buyPrice.get(i) - priceList.get(j)) * (secondPercent / 100); } System.out.println("[Sell]***ͣp***,ϧ" + timeList.get(j) + "ͣp,@" + (buyPrice.get(i) - priceList.get(j)) + "c"); // writeTxt(workPath() + "/history.txt", // "[Sell]***ͣp***,ϧ" + timeList.get(j) + // "ͣp,@" // + (buyPrice.get(i) - priceList.get(j)) + "c", // true); System.out.println("============================================================="); // writeTxt(workPath() + "/history.txt", // "=============================================================", // true); break; } } break; } else if (j == newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1) - 1) { totalProfit += buyPrice.get(i) - priceList.get(j); // System.out.println("@"+(buyPrice.get(i) - // priceList.get(j))); if (buyPrice.get(i) - priceList.get(j) > 0) { profitTime++; } else { lossTime++; } if ((buyPrice.get(i) - priceList.get(j)) < 0) { totalLoss += (buyPrice.get(i) - priceList.get(j)) * 1; } if (buyKeyPattern.get(i) - 2 < volumeNow.size() && i >= countPatternVersion) { System.out.println("[Sell]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + " ǰǰ" + volumeNow.get(buyKeyPattern.get(i) - 2) + ",@" + (buyPrice.get(i) - priceList.get(j)) + "c"); } else { System.out.println("[Sell]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" + priceList.get(j) + "ͣp,IMrg" + timeList.get(buyIndex.get(i)) + ",IMrg" + timeList.get(newIndexList.get(buyKeyPattern.get(i))) + "ͣprg" + timeList.get(j) + "," + volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" + (buyPrice.get(i) - priceList.get(j)) + "c"); } // writeTxt(workPath() + "/history.txt", // "[Sell]***ͣp***," + buyPrice.get(i) + "IM" + ",ϧ" // + priceList.get(j) + "ͣp,IMrg" // + timeList.get(buyIndex.get(i)) + ",IMrg" // + // timeList.get(newIndexList.get(buyKeyPattern.get(i))) // + "ͣprg" // + timeList.get(j) + "," + // volumeNow.get(buyKeyPattern.get(i)) + ",ǰһ" // + volumeNow.get(buyKeyPattern.get(i) - 1) + ",@" // + (buyPrice.get(i) - priceList.get(j)) + "c", // true); System.out.println("============================================================="); // writeTxt(workPath() + "/history.txt", // "=============================================================", // true); break; } } } } // System.out.println("patternF" + patternCount + " ɽ" + (profitTime // + lossTime) + " @ " + totalProfit // + " @Δ " + profitTime + " ̝pΔ " + lossTime + " " // + ((double) profitTime / (double) (profitTime + lossTime)) * 100 + // "%"); // writeTxt(workPath() + "/history.txt", // "patternF" + patternCount + " ɽ" + (profitTime + lossTime) + " // @ " + totalProfit + " @Δ " // + profitTime + " ̝pΔ " + lossTime + " " // + ((double) profitTime / (double) (profitTime + lossTime)) * 100 + // "%", // true); // System.out.println("@Ӌ㷽ʽ (һͣc) " + firstProfit + " x // (һͣcuĂ}λٷֱ) " + firstPercent + "%" // + " + (ڶͣc) " + secondProfit + " x (ڶͣcuĂ}λٷֱ)" + // secondPercent + "%"); // writeTxt(workPath() + "/history.txt", "@Ӌ㷽ʽ (һͣc) " + // firstProfit + " x (һͣcuĂ}λٷֱ) " + firstPercent // + "%" + " + (ڶͣc) " + secondProfit + " x (ڶͣcuĂ}λٷֱ)" + // secondPercent + "%", true); // writeTxt(workPath() + "/history.txt", "", true); // ======================̝̎pПo_maxLoss====================== int maxloss = 0; for (int i = 0; i < buyIndex.size(); i++) { if (buyKeyPattern.get(i) + laterNumber + 1 > newIndexList.size() - 1) { break; } for (int j = buyIndex.get(i); j < newIndexList.get(buyKeyPattern.get(i) + laterNumber + 1); j++) { // buy if (buyType.get(i) == 1) { // Ir-ЃrmaxLoss if (priceList.get(j) - buyPrice.get(i) >= secondProfit) { break; } if (buyPrice.get(i) - priceList.get(j) >= maxLoss) { maxloss++; // writeTxt(workPath() + "/history.txt", "" + // timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) // + ",IMrg" + timeList.get(buyIndex.get(i)), true); System.out.println("" + timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) + ",IMrg" + timeList.get(buyIndex.get(i))); break; } } else if (buyType.get(i) == 2) { // Ir-ЃrmaxLoss if (buyPrice.get(i) - priceList.get(j) >= secondProfit) { break; } if (priceList.get(j) - buyPrice.get(i) >= maxLoss) { maxloss++; // writeTxt(workPath() + "/history.txt", "" + // timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) // + ",IMrg" + timeList.get(buyIndex.get(i)), true); System.out.println("" + timeList.get(j) + "_AOpʧc,IMrλ" + buyPrice.get(i) + ",IMrg" + timeList.get(buyIndex.get(i))); break; } } } } result.add((double) patternCount); result.add((double) profitTime); result.add((double) lossTime); result.add(totalProfit); result.add((double) maxloss); result.add((double) patternDivideCount); result.add(totalLoss); return result; } public static String workPath() { return System.getProperty("user.dir"); } public static void writeTxt(String filePath, String writeString, boolean noCover) { BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, noCover), "UTF-8")); out.write(writeString + "\r\n"); // } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); // P]YԴ } catch (IOException e) { e.printStackTrace(); } } } public static boolean isTitle(String str) { boolean flag = false; for (int index = 0; index < str.length(); index++) { if (!(Character.isDigit(str.charAt(index)) || str.charAt(index) == '.')) { flag = true; break; // ִгFһǔֵǷ.ԪͽY loop, @҂Ҫִ } } return flag; } }
Ruby
UTF-8
5,330
3.046875
3
[]
no_license
# frozen_string_literal: true require 'pry' require_relative '../paragraph_parser' RSpec.describe ParagraphParser do let(:paragraph) do <<~PGH Cupcake ipsum dolor sit amet. Soufflé liquorice pastry pie croissant soufflé jelly. Halvah croissant gummi bears. Jelly beans cake liquorice apple pie. Lemon drops fruitcake pudding tootsie roll sesame snaps sweet. Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie. Ice cream cupcake donut jelly. PGH end let(:parser) { ParagraphParser.new(paragraph) } describe '#sentences' do it 'should return an array' do expect(parser.sentences).to be_an_instance_of(Array) end it 'when joined, should equal the original paragraph' do expect(parser.sentences.join(' ')).to eq paragraph.strip end context 'when there is a sentence with an email address in it' do let(:paragraph) do <<~PGH Cupcake ipsum dolor sit amet. Soufflé liquorice pastry pie croissant soufflé info@example.com jelly. Halvah croissant gummi bears. Jelly beans cake liquorice apple pie. Lemon drops fruitcake pudding tootsie roll sesame snaps sweet. Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie. Ice cream cupcake donut jelly. PGH end it 'finds the correct sentence including the email address' do expect(parser.sentences[1]).to eq 'Soufflé liquorice pastry pie croissant soufflé info@example.com jelly.' end end context 'when there is a sentence with an elipsis at the end of it' do let(:paragraph) do <<~PGH Cupcake ipsum dolor sit amet. Soufflé liquorice pastry pie croissant soufflé jelly... Halvah croissant gummi bears. Jelly beans cake liquorice apple pie. Lemon drops fruitcake pudding tootsie roll sesame snaps sweet. Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie. Ice cream cupcake donut jelly. PGH end it 'finds the correct sentence including the elipsis' do expect(parser.sentences[1]).to eq 'Soufflé liquorice pastry pie croissant soufflé jelly...' end end context 'when a sentence ends in a question mark' do let(:paragraph) do <<~PGH Cupcake ipsum dolor sit amet. Soufflé liquorice pastry pie croissant soufflé jelly? Halvah croissant gummi bears. Jelly beans cake liquorice apple pie. Lemon drops fruitcake pudding tootsie roll sesame snaps sweet. Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie. Ice cream cupcake donut jelly. PGH end it 'finds the correct sentence including the question mark' do expect(parser.sentences[1]).to eq 'Soufflé liquorice pastry pie croissant soufflé jelly?' end end context 'when a sentence ends in an exclamation point' do let(:paragraph) do <<~PGH Cupcake ipsum dolor sit amet. Soufflé liquorice pastry pie croissant soufflé jelly! Halvah croissant gummi bears. Jelly beans cake liquorice apple pie. Lemon drops fruitcake pudding tootsie roll sesame snaps sweet. Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie. Ice cream cupcake donut jelly. PGH end it 'finds the correct sentence including the exclamation mark' do expect(parser.sentences[1]).to eq 'Soufflé liquorice pastry pie croissant soufflé jelly!' end end context 'when there is dialogue in the paragraph and a sentence ends in quotes' do let(:paragraph) do <<~PGH Cupcake ipsum dolor sit amet. "Soufflé liquorice pastry pie croissant soufflé jelly." Halvah croissant gummi bears. Jelly beans cake liquorice apple pie. Lemon drops fruitcake pudding tootsie roll sesame snaps sweet. Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie. Ice cream cupcake donut jelly. PGH end it 'finds the correct sentence including the quotes' do expect(parser.sentences[1]).to eq '"Soufflé liquorice pastry pie croissant soufflé jelly."' end end context 'when the paragraph has sentences with many of the above in it' do let(:paragraph) do <<~PGH Cupcake ipsum dolor sit amet! "Soufflé liquorice pastry pie croissant soufflé jelly.", she said. Halvah croissant gummi bears... Jelly beans cake liquorice apple pie? Lemon drops fruitcake pudding@example.com tootsie roll sesame snaps sweet. Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie?? Ice cream cupcake donut jelly!! "Yay!" PGH end it 'finds the correct sentences' do expect(parser.sentences[0]).to eq 'Cupcake ipsum dolor sit amet!' expect(parser.sentences[1]).to eq '"Soufflé liquorice pastry pie croissant soufflé jelly.", she said.' expect(parser.sentences[2]).to eq 'Halvah croissant gummi bears...' expect(parser.sentences[3]).to eq 'Jelly beans cake liquorice apple pie?' expect(parser.sentences[4]).to eq 'Lemon drops fruitcake pudding@example.com tootsie roll sesame snaps sweet.' expect(parser.sentences[5]).to eq 'Chocolate cake jujubes gummi bears dragée jelly cupcake jelly cookie??' expect(parser.sentences[6]).to eq 'Ice cream cupcake donut jelly!!' expect(parser.sentences[7]).to eq '"Yay!"' end end end end