language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
876
2.734375
3
[]
no_license
package com.bookstore.utility; import java.security.SecureRandom; import java.util.Random; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; @Component public interface SecurityUtility { public static final String SALT = "salt"; @Bean public static BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12,new SecureRandom(SALT.getBytes())); } @Bean public static String randomPassword() { String SALTCHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder salt=new StringBuilder(); Random rnd = new Random(); while(salt.length()<18) { int index=(int) (rnd.nextFloat()*SALTCHAR.length()); salt.append(SALTCHAR.charAt(index)); } String saltChar=salt.toString(); return saltChar; } }
JavaScript
UTF-8
1,963
2.875
3
[]
no_license
const { extractStoryID } = require('./story-controller-utils'); /** * Processes a story slug from the path * - injects req.context.pathStory property on success * @requires req.storySlug: the slug to exchange * @requires req.context.models DB models * @param {Request} req Request object * @param {Response} res Response object * @param {Function} next next step function * @returns {error} 400 JSON response if story slug is invalid * @returns {error} 404 JSON response if a corresponding story is not found */ const exchangeSlugForStory = async (req, res, next) => { const { params: { storySlug }, context: { models } } = req; const storyID = extractStoryID(storySlug); if (!storyID) return res.status(400).json({ error: 'invalid story slug' }); const story = await models.Story.findById(storyID); if (!story) return res.status(404).json({ error: 'story not found' }); req.context.pathStory = story; next(); }; /** * Enforces the authed User is the author of the Story resource * - proceeds and calls next() if the authed User is the author * @requires req.context.autheduser: the authenticated User * @requires req.context.pathStory: the story resource associated with this path * @requires req.context.models DB models * @param {Request} req Request object * @param {Response} res Response object * @param {Function} next next step function * @returns {error} 401 JSON response if the authed User is not the author */ const requireAuthorship = (req, res, next) => { const { authedUser, pathStory } = req.context; // author is an ObjectID type field // instance.id uses the default ID getter which converts to string // compare strings by calling toString on the author and default getter on authedUser if (pathStory.author.toString() !== authedUser.id) { return res.status(401).json({ error: 'authorship required' }); } next(); }; module.exports = { exchangeSlugForStory, requireAuthorship, };
Java
UTF-8
1,163
3.984375
4
[]
no_license
package javatutorials; public class StaticAndNonStaticConcept { //Global variable:scope of global variable String name="Tom";//Non Static Global Variable will be available across all the functions with same consitions static int age=25;//Static Global Variable public static void main(String[] args) { // TODO Auto-generated method stub //How to call Static Method and Variable? //1.direct Calling //2.Calling by Classname sum();//1.Direct Calling StaticAndNonStaticConcept.sum();//2.Calling by ClassName //How to call Non Static Method & variable? StaticAndNonStaticConcept obj=new StaticAndNonStaticConcept(); obj.sum();//Non Static method calling by creating Object obj.sendMail();//Non Static method calling by creating Object System.out.println(obj.name); //can I access Static method by object refrence-yes we can access but not a good practise obj.sum();//but 1 warning will come } public void sendMail() { System.out.println("Send mail method"); } public static void sum() {//Static Method System.out.println("Sum Method"); } }
JavaScript
UTF-8
1,926
2.78125
3
[ "MIT" ]
permissive
// 正则验证 export function isvalidUsername(str) { return true; // const validMap = ['admin', 'editor'] // return validMap.indexOf(str.trim()) >= 0 } // 合法uri export function validateURL(textval) { /* eslint max-len: 0 */ const urlRegex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/; return urlRegex.test(textval); } // 小写字母 export function validateLowerCase(str) { const reg = /^[a-z]+$/; return reg.test(str); } // 大写字母 export function validateUpperCase(str) { const reg = /^[A-Z]+$/; return reg.test(str); } /* 大小写字母 */ export function validateAlphabets(str) { const reg = /^[A-Za-z]+$/; return reg.test(str); } // validate email export function validateEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } // 邮箱 export function isEmail(s) { return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test( s ); } // 手机号码 export function isMobile(s) { return /^1[0-9]{10}$/.test(s); } // 电话号码 export function isPhone(s) { return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s); } // URL地址 export function isURL(s) { return /^http[s]?:\/\/.*/.test(s); } export const regMobile = /^(1[3-9][0-9])\d{8}$/; export const regEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; export const regMobileCode = /^(\d{6}|\d{4})$/; export const regChinese = /^[\u4e00-\u9fff]{0,}$/;
C++
UTF-8
723
2.78125
3
[]
no_license
#ifndef _NOTE_H_ #define _NOTE_H_ class Note { private: double Id; double Balance; public: Note(void); Note(double id); Note(double id, double summ); ~Note(void); void Push(double summ); bool Pop(double summ); double GetBalance(void); Note& operator =(Note& note); friend bool operator ==(Note& note1, Note& note2); friend bool operator !=(Note& note1, Note& note2); friend bool operator <(Note& note1, Note& note2); friend bool operator <=(Note& note1, Note& note2); friend bool operator >(Note& note1, Note& note2); friend bool operator >=(Note& note1, Note& note2); friend std::ostream& operator<<(std::ostream& os, const Note& note); void Import(FILE *file); void Export(FILE *file); }; #endif
C++
UTF-8
747
3.328125
3
[]
no_license
// // euler10.cpp // // // Created by José Miguel Molina Arboledas on 06/05/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include <iostream> using namespace std; unsigned int n = 2; unsigned int primesum = 0; bool isPrime(int number); int main(void) { while (n < 2000000) { if (isPrime(n)) { primesum += n; } n++; } cout << "The sum of the primes below 2M is " << primesum << endl; } bool isPrime(int number) { if (number <= 0 || number == 1 || (number % 2 == 0 && number != 2)) { return false; } else { for (int i = 3; i < number; i += 2) { if (number % i == 0) { return false; } } } return true; }
Go
UTF-8
413
3.015625
3
[]
no_license
package main import ( "design-pattern/singleton-pattern/service/one" "design-pattern/singleton-pattern/service/three" "design-pattern/singleton-pattern/service/two" ) func main() { for i := 0; i < 10; i++ { oneService := one.GetInstance() oneService.PrintSomething() twoService := two.GetInstance() twoService.DoSomething() threeService := three.GetInstance() threeService.DoSomething() } }
Swift
UTF-8
10,269
2.515625
3
[]
no_license
import AVFoundation import AudioToolbox import VideoToolbox struct IOID { let from: String let to: String let sid: String // session unique ID let gid: String // io group (audio + video) ID init(_ from: String, _ to: String, _ sid: String, _ gid: String) { self.from = from self.to = to self.sid = sid self.gid = gid } init(_ from: String, _ to: String) { self.from = from self.to = to self.sid = IOID.newID(from, to, "sid") self.gid = IOID.newID(from, to, "gid") } func groupNew() ->IOID { return IOID(from, to, IOID.newID(from, to, "sid"), gid) } static private func newID(_ from: String, _ to: String, _ kind: String) -> String { return "\(kind) \(from) - \(to) (\(UUID()))" } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Simple types //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enum IOKind : Int { case Audio case Video } protocol IODataProtocol { func process(_ data: NSData) } typealias IOSessionProtocol = SessionProtocol struct IOFormat { private static let kID = "kID" var data: [String: Any] init () { data = [String: Any]() data[IOFormat.kID] = UUID().uuidString } init(_ data: [String: Any]) { self.data = data } var id: String { get { return data[IOFormat.kID]! as! String } } } class IOData : IODataProtocol { private let next: IODataProtocol? init() { next = nil } init(_ next: IODataProtocol?) { self.next = next } func process(_ data: NSData) { next?.process(data) } } class IOSession : IOSessionProtocol { private let next: IOSessionProtocol? init() { next = nil } init(_ next: IOSessionProtocol?) { self.next = next } func start() throws { try next?.start() } func stop() { next?.stop() } } class IOSessionBroadcast : IOSessionProtocol { private var x: [IOSessionProtocol?] init(_ x: [IOSessionProtocol?]) { self.x = x } func start () throws { _ = try x.map({ try $0?.start() }) } func stop() { _ = x.reversed().map({ $0?.stop() }) } } func broadcast(_ x: [IOSessionProtocol?]) -> IOSessionProtocol? { if (x.count == 0) { return nil } if (x.count == 1) { return x.first! } return IOSessionBroadcast(x) } class IODataSession : IODataProtocol, IOSessionProtocol { private(set) var active = false private let next: IODataProtocol init(_ next: IODataProtocol) { self.next = next } func start() throws { assert(active == false) active = true } func stop() { assert(active == true) active = false } func process(_ data: NSData) { guard active else { logIO("received data after session stopped"); return } next.process(data) } } struct IOInputContext { let qos: IOQoS let balancer: IOQoSBalancerProtocol init(_ balancer: IOQoSBalancerProtocol) { self.qos = IOQoS() self.balancer = balancer } } struct IOOutputContext { let id: IOID? let session: IOSessionProtocol? let data: IODataProtocol? let timebase: IOTimebase? let balancer: IOBalancer? // concrete context init(_ id: IOID?, _ session: IOSessionProtocol?, _ data: IODataProtocol?, _ timebase: IOTimebase?, _ balancer: IOBalancer?) { self.id = id self.session = session self.data = data self.timebase = timebase self.balancer = balancer } // create context with shared info init(_ id: IOID, _ session: IOSessionProtocol, _ data: IODataProtocol, _ context: IOOutputContext) { self.init(id, session, data, context.timebase, context.balancer) } // context for sharing sync and balancer init() { self.init(nil, nil, nil, IOTimebase(), IOBalancer()) } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Time //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct IOTime { let hostSeconds: Float64 init() { hostSeconds = 0 } init(_ hostSeconds: Float64) { self.hostSeconds = hostSeconds } } protocol IOTimeProtocol { var time: IOTime { get } func copy(time: IOTime) -> Self } protocol IOTimeUpdaterProtocol { func time(_ data: NSData) -> Double func time(_ data: inout NSData, _ time: Double) } class IOTimeUpdater<T: IOTimeProtocol & InitProtocol> : IOTimeUpdaterProtocol { private let updater: PacketsUpdater<T> init(_ index: Int) { updater = PacketsUpdater<T>(index) } func concreteTime(_ data: NSData) -> T { var result = T() updater.getValue(data, &result) return result } func concreteTime(_ data: inout NSData, _ time: T) { updater.setValue(&data, time) } func time(_ data: NSData) -> Double { return concreteTime(data).time.hostSeconds } func time(_ data: inout NSData, _ time: Double) { concreteTime(&data, concreteTime(data).copy(time: IOTime(time))) } } class IOTimebase { var zero: Double? } class IOTimebaseReset : IODataProtocol { private let time: IOTimeUpdaterProtocol private var timebase: IOTimebase private let next: IODataProtocol? init(_ timebase: IOTimebase, _ time: IOTimeUpdaterProtocol, _ next: IODataProtocol?) { self.time = time self.timebase = timebase self.next = next } func process(_ data: NSData) { let dataTime = time.time(data) var copy = data if timebase.zero == nil { timebase.zero = dataTime } else if timebase.zero! > dataTime { return } time.time(&copy, dataTime - timebase.zero!) next?.process(copy) } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // QOS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// protocol IOQoSProtocol { func change(_ toQID: String, _ diff: Int) } protocol IOQoSBalancerProtocol { func process(_ qosID: String, _ gap: Double) } class IOQoSDispatcher : IOQoSProtocol { let queue: DispatchQueue let next: IOQoSProtocol init(_ queue: DispatchQueue, _ next: IOQoSProtocol) { self.queue = queue self.next = next } func change(_ toQID: String, _ diff: Int) { queue.sync { next.change(toQID, diff) } } } class IOQoSBroadcast : IOQoSProtocol { private var x: [IOQoSProtocol?] init(_ x: [IOQoSProtocol?]) { self.x = x } func change(_ toQID: String, _ diff: Int) { _ = x.map({ $0?.change(toQID, diff) }) } } class IOQoS { static let kInit = 0 static let kIncrease = 1 static let kDecrease = -1 var clients = [IOQoSProtocol]() var qid: String = UUID().uuidString func add(_ x: IOQoSProtocol) { clients.append(x) x.change(qid, IOQoS.kInit) } func change(_ diff: Int) { qid = UUID().uuidString _ = clients.map({ $0.change(qid, diff) }) } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Logging //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enum ErrorIO : Error { case Error(String) } func logIO(_ message: String) { logMessage("IO", message) } func logIOPrior(_ message: String) { logPrior("IO", message) } func logIOError(_ error: Error) { logError("IO", error) } func logIOError(_ error: String) { logError("IO", error) } func checkStatus(_ status: OSStatus, _ message: String) throws { guard status == 0 else { throw ErrorIO.Error(message + ", status code \(status)") } } func checkIO(_ x: FuncVVT) { do { try x() } catch { logIOError(error) } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // IOData dispatcher //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class IODataAsyncDispatcher : IODataProtocol { let queue: DispatchQueue private let next: IODataProtocol init(_ queue: DispatchQueue, _ next: IODataProtocol) { self.queue = queue self.next = next } func process(_ data: NSData) { queue.async { self.next.process(data) } } } class IOSessionDispatcher : IOSessionProtocol { typealias Call = (@escaping FuncVV) -> Void private let call: Call private let next: IOSessionProtocol? init(_ call: @escaping Call, _ next: IOSessionProtocol?) { self.call = call self.next = next } func start() throws { call { do { try self.next?.start() } catch { logIOError(error) } } } func stop() { call { self.next?.stop() } } } class IOSessionSyncDispatcher : IOSessionDispatcher { let queue: DispatchQueue init(_ queue: DispatchQueue, _ next: IOSessionProtocol?) { self.queue = queue super.init({ (block: @escaping FuncVV) in queue.sync(execute: block) }, next) } } class IOSessionAsyncDispatcher : IOSessionDispatcher { let queue: DispatchQueue init(_ queue: DispatchQueue, _ next: IOSessionProtocol?) { self.queue = queue super.init({ (block: @escaping FuncVV) in queue.async(execute: block) }, next) } }
JavaScript
UTF-8
4,044
2.515625
3
[]
no_license
/* global WaveSurfer:false */ const recorderRecordElm = document.querySelector('[data-recorder-record]') const recorderPauseElm = document.querySelector('[data-recorder-pause]') const recorderResumeElm = document.querySelector('[data-recorder-resume]') const recorderStopElm = document.querySelector('[data-recorder-stop]') const playerPlayElm = document.querySelector('[data-player-play]') const playerPauseElm = document.querySelector('[data-player-pause]') const playerStopElm = document.querySelector('[data-player-stop]') const downloadElm = window.document.createElement('a') downloadElm.download = 'recording.webm' downloadElm.textContent = 'Download' const player = WaveSurfer.create({ container: '[data-waveform]' }) window.__player = player const disableAndHide = (element) => { element.disabled = true element.style.display = 'none' } const enableAndShow = (element) => { element.disabled = false element.style.display = 'inline-block' } const showDownloadElm = () => { document.body.appendChild(downloadElm) } const hideDownloadElm = () => { downloadElm && downloadElm.parentNode && downloadElm.remove() } navigator.mediaDevices.getUserMedia({audio: true}) .then((stream) => { enableAndShow(recorderRecordElm) const mimeType = 'audio/webm' const recorder = new window.MediaRecorder(stream, {mimeType}) window.__recorder = recorder const chunks = [] recorder.ondataavailable = (e) => chunks.push(e.data) recorder.onstart = () => { player.empty() disableAndHide(recorderRecordElm) enableAndShow(recorderPauseElm) disableAndHide(recorderResumeElm) enableAndShow(recorderStopElm) disableAndHide(playerPlayElm) disableAndHide(playerPauseElm) disableAndHide(playerStopElm) hideDownloadElm() } recorder.onpause = () => { disableAndHide(recorderRecordElm) disableAndHide(recorderPauseElm) enableAndShow(recorderResumeElm) enableAndShow(recorderStopElm) disableAndHide(playerPlayElm) disableAndHide(playerPauseElm) disableAndHide(playerStopElm) hideDownloadElm() } recorder.onstop = () => { enableAndShow(recorderRecordElm) disableAndHide(recorderPauseElm) disableAndHide(recorderResumeElm) disableAndHide(recorderStopElm) enableAndShow(playerPlayElm) disableAndHide(playerPauseElm) disableAndHide(playerStopElm) let url = window.URL.createObjectURL(new window.Blob(chunks, {type: mimeType})) player.load(url) // to test player failure, comment this line chunks.length = 0 downloadElm.href = url showDownloadElm() } player.on('play', () => { disableAndHide(recorderRecordElm) disableAndHide(recorderPauseElm) disableAndHide(recorderResumeElm) disableAndHide(recorderStopElm) disableAndHide(playerPlayElm) enableAndShow(playerPauseElm) enableAndShow(playerStopElm) }) player.on('pause', () => { enableAndShow(recorderRecordElm) disableAndHide(recorderPauseElm) disableAndHide(recorderResumeElm) disableAndHide(recorderStopElm) enableAndShow(playerPlayElm) disableAndHide(playerPauseElm) if (player.getCurrentTime() === player.getDuration()) { disableAndHide(playerStopElm) } else { enableAndShow(playerStopElm) } }) // to test recorder failure, comment recorder.start() or whole line recorderRecordElm.addEventListener('click', () => { recorder.start() }) recorderPauseElm.addEventListener('click', () => { recorder.pause() }) recorderResumeElm.addEventListener('click', () => { recorder.resume() }) recorderStopElm.addEventListener('click', () => { recorder.stop() }) playerPlayElm.addEventListener('click', () => { player.play() }) playerPauseElm.addEventListener('click', () => { player.pause() }) playerStopElm.addEventListener('click', () => { player.stop() disableAndHide(playerStopElm) showDownloadElm() }) })
Swift
UTF-8
185
2.9375
3
[]
no_license
let person = "Swift Programmer" var greeting = "Hello, " greeting + person greeting = "Hi there, " greeting + person var newline: String newline = "\n" greeting + newline + person
Markdown
UTF-8
2,424
3.078125
3
[]
no_license
# PHP Slim 4 Basic restful API [![Codacy Badge](https://app.codacy.com/project/badge/Grade/f6fe2d1c42334960bcc3bf7c3b0ccea8)](https://www.codacy.com/gh/ajsevillano/api.uniondistribuidora.com/dashboard?utm_source=github.com&utm_medium=referral&utm_content=ajsevillano/api.uniondistribuidora.com&utm_campaign=Badge_Grade) This is a basic RESTful API designed for a customer.The API will allow you to fech information from a products and customers table in the databes and allow you to read,create and update them. Delete request is not allow at this time. ## Motivation Despite of my frontend background, I wanted to create a basic Restapi in PHP using [PHP Slim 4 framework](http://www.slimframework.com/) to serve as backend on some of my projects. ## Installation You can download the project in [zip](https://github.com/ajsevillano/api.uniondistribuidora.com/archive/main.zip) format or clone with: ```php gh repo clone ajsevillano/api.uniondistribuidora.com ``` - Download and install composer from [here](https://getcomposer.org/download/) - Then install all the project's dependencies: ```bash php composer.phar update ``` I will create a file with the database structure and some dummy data for testing in next releases. ## GET ENDPOINDS The API will provived you some endpoints: ```html GET /products <- It will return a full json list of the products in the DB. ``` ```html GET /products/id <- It will return an unique product based on its ID. Only numerics IDs are allow. ``` ```html GET /customers <- It will return a full json list of the customers in the DB. ``` ```html GET /customers/id <- It will return an unique customer based on its ID. Only numerics IDs are allow. ``` ## POST PRODUCTS ENDPOINDS ```html POST /products ``` You will need to send a json object to create a new item in the next format: ```json { "tipo": "type of drink", "marca": "Brand", "tamano": "Size", "nombre": "Name", "activo": "0" } ``` ## PUT PRODUCTS ENDPOINDS ```html Put /products ``` You will need to send a json object to update an item based in its ID in the next format: ```json { "id": "an numeric id", "tipo": "beer", "marca": "Brand", "tamano": "Size", "nombre": "Name", "activo": "0" } ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate.
JavaScript
UTF-8
2,350
2.625
3
[]
no_license
/** * Created by x on 11/16/16. */ // ACCEPTANCE TEST /** * Setup test suit configuration */ var chai = require('chai'), should = chai.should, expect = chai.expect, Promise = require('bluebird'), request = require('superagent-promise')(require('superagent'), Promise), chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var url = process.env.URL || 'http://localhost:5000/'; /** * Tests escenarios */ describe('Get home page', function () { var result; before(function () { result = get(url) }); it('Should be redirected to login', function () { return assert(result, "status").to.equals(200); }) }); // TEST 1 describe('Cross Origin Requests', function () { var result; before(function () { result = request('OPTIONS', url) .set('Origin', 'https://torrentjs.com') .end() }); // it('Should return the correct CORS headers', function () { // return assert(result, "header").to.contain.all.keys( // [ // 'access-control-allow-origin', // 'access-control-allow-methods', // 'access-control-allow-headers' // ] // ) // }); // it('Should allow all origins', function () { // return assert(result, "headers.access-control-allow-origin").to.equal('*') // }) }); // TEST 2 describe('Create object', function () { var result; before(function () { result = post(url, {username: "walk", password: "alone"}) }); // WARNING!! not implemented yet! it('Should return a 201 CREATED response', function () { // return assert(result, "status").to.equals(201); }); // should response with item location // if we query the item we should find the same item title after(function () { return del(url) }) }); /** * Tests features */ function post(url, data) { return request.post(url) .set('Content-Type', 'application/json') .set('Accept', 'application/json') .send(data) .end(); } function del(url) { return (url) } function get(url) { return request.get(url).end() } /** * Helper functions */ function assert(result, prop) { return expect(result).to.eventually.have.deep.property(prop) }
C++
UTF-8
2,732
2.734375
3
[ "BSD-3-Clause-Clear" ]
permissive
// // Created by tao on 19-1-17. // #include <unordered_map> #include "common_includes.h" #include "time_gap.hpp" TEST(test_test, 1) { std::map<int, int> typeMapRef; size_t threadGap = 100; for (int i = 0; i < 1024; ++i) { typeMapRef[i] = i; } using IteratorType = decltype(typeMapRef)::iterator; auto size = typeMapRef.size(); auto beginIt = typeMapRef.begin(); auto endIt = beginIt; auto process = [&typeMapRef](IteratorType beginIt, IteratorType endIt) { LOG_DEBUG("start at " << beginIt->first << "\t end at] :" << (--endIt)->first) }; while (size > 0) { auto diff = std::min(size, threadGap); size -= diff; std::advance(endIt, diff); process(beginIt, endIt); beginIt = endIt; } } TEST(test_test, 2) { TimeGap gap{}; int diffGap = 100000; int max = 100 * diffGap; { gap.resetStartNow(); std::map<int, int> map_data; for (int i = 0; i < max; ++i) { map_data[i] = i; } LOG_DEBUG("one " << gap.gap() << "\tsec" << gap.gapSec()) } { gap.resetStartNow(); std::map<int, std::map<int, int>> map_data; for (int i = 0; i < max; ++i) { map_data[(int)(i % diffGap)][i] = i; } LOG_DEBUG("one " << gap.gap() << "\tsec" << gap.gapSec()) } } struct EnumClassHash { template <typename T> size_t operator()(T t) const { return static_cast<size_t>(t); } }; TEST(test_test, 3) { TimeGap gap{}; int diffGap = 100000; int max = 100 * diffGap; { gap.resetStartNow(); std::unordered_map<int, int> map_data; for (int i = 0; i < max; ++i) { map_data[i] = i; } LOG_DEBUG("one " << gap.gap() << "\tsec" << gap.gapSec()) } { gap.resetStartNow(); std::unordered_map<int, std::unordered_map<int, int>> map_data; for (int i = 0; i < max; ++i) { map_data[(int)(i % diffGap)][i] = i; } LOG_DEBUG("one " << gap.gap() << "\tsec" << gap.gapSec()) } } TEST(test_test, 4) { TimeGap gap{}; int diffGap = 10000; int max = 1000 * diffGap; std::vector<int> data_vec{}; { for (int i = 0; i < max; ++i) { data_vec.push_back(rand()); } } { gap.resetStartNow(); std::unordered_map<int, int> map_data; for (auto i : data_vec) { map_data[i] = i; } LOG_DEBUG("one " << gap.gap() << "\tsec" << gap.gapSec()) } { gap.resetStartNow(); std::unordered_map<int, std::unordered_map<int, int>> map_data; for (auto i : data_vec) { map_data[(int)(i % diffGap)][i] = i; } LOG_DEBUG("one " << gap.gap() << "\tsec" << gap.gapSec()) } } int main(int argc, char **argv) { int iRet = 0; testing::InitGoogleTest(&argc, argv); iRet = RUN_ALL_TESTS(); sleep(1); return iRet; }
Python
UTF-8
1,321
2.609375
3
[]
no_license
from flask import Flask,url_for,redirect,render_template from url2list import ListConverter from jsonify_resp import JSONResponse app = Flask(__name__) #将自定义的响应类赋值给当前的app,从而替换响应类 app.response_class=JSONResponse #将新建的转换器类型加入内建类型中 app.url_map.converters['list']=ListConverter @app.route('/') def index(): return render_template('index.html') @app.route('/list1/<list:page_names>/') def list1(page_names): return '分隔符: {} {}'.format('+',page_names) #url_for自定义 @app.route('/list2/name/') def list2(): return url_for('list2',id=6,next='/') #/list2/name/?id=6&next=%2F #redirect @app.route('/search/<keyword>/') def search(keyword): if (keyword=='hello'): return redirect(url_for('index')) else: return 'hello {}'.format(keyword) #jsonify @app.route('/json_resp/<id>/') def json_resp(id): return {'id':id} @app.errorhandler(404) def not_found(error): return render_template('404.html'),404 @app.route('/item/<int:id>/') def item(id): if (id==520): return redirect(url_for('dailyLife')) return ('item {}'.format(id)) @app.route('/secret/') def secret(): abort(404) print('不会执行到这里!!!') if __name__ == '__main__': app.run(debug=True)
C++
UTF-8
840
3.1875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int solution(vector<int> &A){ sort(A.begin(), A.end()); int candidate = *A.begin(); int count = 1; int max_cand; int max_count = 0; for (vector<int>::iterator it = A.begin()+1; it != A.end(); it++){ if (*it == candidate){ count++; } else{ if (max_count < count){ max_cand = candidate; max_count = count; count = 0; candidate = *it; } } } if (max_count < count){ max_cand = candidate; max_count = count; count = 0; } return max_cand; } int main() { vector<int> A = {6, 8, 4, 6, 8, 6, 6}; int cand = solution(A); cout << cand; return 0; }
JavaScript
UTF-8
4,272
3.75
4
[]
no_license
// Troll Game Project 7/22/2020 "use strict"; // Set up an evemt listener for the button to trigger the game document.getElementById("button").addEventListener("click", trollBattle); // Function to run the game function trollBattle(){ // Initial prompt question for the user stored in a variable var action = window.prompt("You're walking through the forest minding your own business and A TROLL SUDDENLY APPEARS!\n\nDo you FIGHT the troll?\n\nDo you RUN from the troll?\n\nDo you BRIBE the troll?").toUpperCase(); // Switch statement to handle the initial player's choice switch(action) { case "FIGHT": var skill = window.prompt("Are you a skilled warrior? (YES or NO)").toUpperCase(); var strong = window.prompt("Are you stronger than a troll? (YES or NO)").toUpperCase(); // IF statement that analyzes the user's responses if(skill === "YES" || strong === "YES") { // write the positive result to the page document.getElementById("result").innerHTML = "You can either be stronger or more skilled than a troll to survive!<br/>You live another day!"; // clear any bad messages from the page document.getElementById("death").innerHTML = ""; // play the winning audio file document.getElementById("win").play(); } else { // clear any good messages from the page document.getElementById("result").innerHTML = ""; // write the negative result to the page document.getElementById("death").innerHTML = "You're not strong OR smart? Why did you fight a troll?</br>You have died!"; // play the losing audio file document.getElementById("lose").play(); } break; case "RUN": var fast = window.prompt("Are you fast? (YES or NO)").toUpperCase(); // IF statement that analyzes the user's responses if(fast === "YES") { // write the positive result to the page document.getElementById("result").innerHTML = "Your speed has allowed you to survive.<br/>But can you live with your cowardice?"; // clear any bad messages from the page document.getElementById("death").innerHTML = ""; // play the winning audio file document.getElementById("win").play(); } else { // clear any good messages from the page document.getElementById("result").innerHTML = ""; // write the negative result to the page document.getElementById("death").innerHTML = "You coward, if you're going to run, atleast be fast...</br>You have died!"; // play the losing audio file document.getElementById("lose").play(); } break; case "BRIBE": var money = window.prompt("You have to pay the troll-toll.\nDo you have money?(YES or NO)").toUpperCase(); // If you have money, continue asking how much if(money === "YES"){ var amount = window.prompt("How much money do you have?\n(Please enter a NUMERIC VALUE!)"); // convert the string to an integer amount = parseInt(amount); // Check to see if the amount is enough to survive if(amount > 50){ // write the positive result to the page document.getElementById("result").innerHTML ="Great job! The troll is happy!<br/>You get to pass with your life!"; // clear any bad messages from the page document.getElementById("death").innerHTML = ""; // play the winning audio file document.getElementById("win").play(); } else { // clear any good messages from the page document.getElementById("result").innerHTML = ""; // write the negative result to the page document.getElementById("death").innerHTML = "The troll needs more than that to let you pass!</br>You have died!"; // play the losing audio file document.getElementById("lose").play(); } } else { // if you have no money, you lose // clear any good messages from the page document.getElementById("result").innerHTML = ""; // write the negative result to the page document.getElementById("death").innerHTML = "What were you going to bribe with, your looks?</br>You have died!"; // play the losing audio file document.getElementById("lose").play(); } break; default: window.alert("Please enter a valid choice!"); trollBattle(); break; } // end of switch statement } // end of trollBattle() function
Java
UTF-8
1,867
3
3
[]
no_license
/** * Copyright (c) 1999-2007, Fiorano Software Technologies Pvt. Ltd. and affiliates. * Copyright (c) 2008-2015, Fiorano Software Pte. Ltd. and affiliates. * * All rights reserved. * * This software is the confidential and proprietary information * of Fiorano Software ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * enclosed with this product or entered into with Fiorano. */ package com.fiorano.openesb.utils.queue; import java.util.NoSuchElementException; /** * class </code> FioranoQueueEnumerator </code> implements * Enumerator used for enumerating the contents of a Queue. */ public class FioranoQueueEnumerator implements java.util.Enumeration { // current position of pointer in the Queue. private IFioranoQueueable m_current; // Total size of Queue private int m_iSize; /** * Create a new enumerator, starting from the given node. */ public FioranoQueueEnumerator (IFioranoQueueable head, int size) { m_current = head; m_iSize = size; } /** * @return true is more data ia available in this Queue. */ public boolean hasMoreElements() { return (m_current != null); } /** * @return next element from this Queue. * @throws NoSuchElementException if there is the enumerator * has reached end of the Queue. */ public Object nextElement() { if (m_current == null) throw new NoSuchElementException("No More Elements."); IFioranoQueueable toReturn = m_current; m_current = m_current.getNext (); return toReturn.getData (); } /** * @return size of Queue */ public int getLength () { return m_iSize; } }
C++
UTF-8
451
2.6875
3
[]
no_license
#include "Prof.h" /****************************/ /* class Prof : public User */ /****************************/ // constructor for professor user Prof::Prof(std::string name, std::string favoriteJoke) : User(YELLOW, name, "Favorite joke: " + favoriteJoke) { } // returns string with user type std::string Prof::getUserType() { return "Professor"; } /*****************************/ /* /class Prof : public User */ /*****************************/
Java
UTF-8
862
2.5
2
[]
no_license
package com.cheng.springbatch.xml; import java.util.Date; import org.springframework.batch.item.ItemProcessor; import org.springframework.stereotype.Component; /** * @author chengchenrui * @version Id: XMLProcessor.java, v 0.1 2017.2.28 10:37 chengchenrui Exp $$ */ @Component("xMLProcessor") public class XMLProcessor implements ItemProcessor<Goods, Goods> { public Goods process(Goods item) throws Exception { // 购入日期变更 item.setBuyDay(new Date()); // 顾客信息变更 item.setCustomer(item.getCustomer() + "顾客!"); // ISIN变更 item.setIsin(item.getIsin() + "IsIn"); // 价格变更 item.setPrice(item.getPrice() + 1000.112); // 数量变更 item.setQuantity(item.getQuantity() + 100); // 处理后的数据返回 return item; } }
Java
UTF-8
7,684
2
2
[]
no_license
package com.augmentify.DataModule.Objects.User; import android.content.Context; import android.net.Uri; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.augmentify.DataModule.Controller.Controller; import com.augmentify.DataModule.Objects.DataObject; import com.augmentify.DataModule.Objects.Meta; import com.augmentify.DataModule.SQLCache; import com.augmentify.DataModule.Settings; import com.augmentify.DataModule.Urls; import com.augmentify.Debug; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.List; /** * Created by Saurabh on 19/07/2014. */ public class Profile implements DataObject { @Expose public String gender; @Expose public String profile_picture; @Expose public User user; public static class ProfileMeta { @Expose public Meta meta; @Expose public List<Profile> objects; } void copyFields(Profile profile) { this.gender = profile.gender; this.profile_picture = profile.profile_picture; this.user = profile.user; } public static enum RESOURCE_TYPE { PROFILE, PROFILE_DETAIL, PROFILE_PRIVATE, PROFILE_PRIVATE_DETAIL } int id; Status status; String requestUrl; RESOURCE_TYPE requestType; JSONObject response; SQLCache profileCache; Context context; public Profile(Context context) { profileCache = new SQLCache(context, Urls.PATH.PROFILE); this.context = context; } @Override public void refresh() { switch (requestType) { case PROFILE: case PROFILE_PRIVATE: { ProfileMeta profileMeta = Controller.dataObjectBuilder.fromJson(response.toString(), ProfileMeta.class); copyFields(profileMeta.objects.get(0)); } break; case PROFILE_DETAIL: case PROFILE_PRIVATE_DETAIL: { copyFields(Controller.dataObjectBuilder.fromJson(response.toString(), Profile.class)); } } } public void setReadRequestParams(RESOURCE_TYPE requestType, int id) { this.id = id; this.requestType = requestType; } @Override public void read() { Uri.Builder uriBuilder = Uri.parse(Urls.SERVER) .buildUpon() .appendPath(Urls.API) .appendPath(Urls.VERSION) .appendQueryParameter(Urls.REQUEST_KEY.FORMAT, "json") .appendQueryParameter(Urls.REQUEST_KEY.USERNAME, Settings.Account.username) .appendQueryParameter(Urls.REQUEST_KEY.API_KEY, Settings.Account.apiKey); switch (requestType) { case PROFILE: { uriBuilder.appendPath(Urls.PATH.PROFILE); } break; case PROFILE_DETAIL: { uriBuilder.appendPath(Urls.PATH.PROFILE); uriBuilder.appendPath(String.valueOf(id)); } break; case PROFILE_PRIVATE: { uriBuilder.appendPath(Urls.PATH.PROFILE_PRIVATE); } break; case PROFILE_PRIVATE_DETAIL: { uriBuilder.appendPath(Urls.PATH.PROFILE_PRIVATE); uriBuilder.appendPath(String.valueOf(id)); } break; } uriBuilder.appendPath(""); requestUrl = uriBuilder.build().toString(); Log.d(Debug.TAG.NET, requestUrl); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, requestUrl, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject serverResponse) { response = serverResponse; refresh(); profileCache.set(requestUrl, response.toString()); changeStatus(Status.READ_OK); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { changeStatus(Status.ERROR); Log.d(Debug.TAG.NET, error.toString()); } }); Controller.networkRequestQueue.add(request); } public void setCreateRequestParams( String username, String password, String email, String gender, String first_name, String last_name ) { this.user = new User(context); this.user.username = username; this.user.password = password; this.user.email = email; this.user.first_name = first_name; this.user.last_name = last_name; this.gender = gender; } @Override public void create() { Uri.Builder uriBuilder = Uri.parse(Urls.SERVER) .buildUpon() .appendPath(Urls.API) .appendPath(Urls.VERSION) .appendQueryParameter(Urls.REQUEST_KEY.FORMAT, "json") .appendQueryParameter(Urls.REQUEST_KEY.MAGIC_WORD, "OpenSesame"); uriBuilder.appendPath(Urls.PATH.PROFILE_CREATE); uriBuilder.appendPath(""); requestUrl = uriBuilder.build().toString(); final Profile data = new Profile(context); data.copyFields(this); StringRequest request = new StringRequest(Request.Method.POST, requestUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(Debug.TAG.NET, "Profile Created"); changeStatus(Status.CREATE_OK); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(Debug.TAG.NET, "Error [" + error + "]"); changeStatus(Status.ERROR); } }) { @Override public byte[] getBody() throws AuthFailureError { try { return new GsonBuilder() .excludeFieldsWithoutExposeAnnotation().create() .toJson(data).getBytes(getParamsEncoding()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } @Override public String getBodyContentType() { return "application/json; charset=" + getParamsEncoding(); } }; Controller.networkRequestQueue.add(request); } @Override public void delete() { } @Override public void onStatusChange(Status status) { } @Override public void changeStatus(Status status) { if(this.status == status) { return; } this.status = status; this.onStatusChange(status); } }
Python
UTF-8
2,691
4
4
[]
no_license
# Aditya Srivastava, CS1, 10/19/16 ; system.py # This class allows multiple bodies in a given list to be drawn and move by using the Body class and its methods from cs1lib import * from body import Body from math import * class System: def __init__(self, body_list): self.body_list = body_list # body list is set to self.body_list to be used in this class # updates the position and velocity of each object in the list def update(self, timestep): # updates the position of each body in the list for each_body in range(len(self.body_list)): (ax, ay) = self.compute_acceleration(self.body_list[each_body]) # calling the values of ax and ay as tuples so they can be called at the same time self.body_list[each_body].update_velocity(ax, ay, timestep) # acceleration is set to ax and ay and timestep is used self.body_list[each_body].update_position(timestep) # calls the update position method from Body # computes the x and y components of the acceleration of the body at index n in the list def compute_acceleration(self, n): G = 6.67384e-11 # universal gravitation constant ax = 0 # acceleration in the x direction is set to 0 to begin ay = 0 # acceleration in the y direction is set to 0 to begin for each_body in range(len(self.body_list)): # if loop to make sure accleration isn't calculated for a body n on itself if self.body_list[each_body] != n: m = self.body_list[each_body].mass # m is set to mass dx = self.body_list[each_body].x - n.x # distance between the x coordinate of two bodies dy = self.body_list[each_body].y - n.y # distance between the y coordinate of two bodies r = sqrt(dx * dx + dy * dy) # radius given by the distance formula a = (G * m)/(r * r) # acceleration formula ax = ax + (a * dx) / r # adding up the values of the acceleration in the x direction ay = ay + (a * dy) / r # adding up the values of the acceleration in the x direction return (ax, ay) # returns the values ax and ay as a tuple # draws the each body that is located in the list def draw(self, cx, cy, pixels_per_meter): # for loop for drawing each body in the list for body_one in self.body_list: # draws a body by calling the draw method in Body and passing on the values of the parameters body_one.draw(cx, cy, pixels_per_meter)
Markdown
UTF-8
2,797
3.359375
3
[ "MIT" ]
permissive
--- title: FAQ path: /faq/ index: 12 --- ### Why is there a blue outline around my element? You may notice a blue outline around your reference element. The blue outline is called a focus ring; it lets keyboard users know which element on the page is currently in focus. Tippy adds an attribute to the element so that it can receive focus if it natively cannot, so that keyboard users (e.g. blind users) can access the tooltip without using a mouse. Recommended: use the `focus-visible` polyfill: https://github.com/WICG/focus-visible. This will remove the outline for mouse users but keep it visible for keyboard users. If your tooltip is **non-essential** (only acts as enhancement), then you can disable the `a11y` option: ```js tippy('div', { a11y: false, }) ``` ### I can't click things inside the tooltip To enable interactivity, set the `interactive` option to `true`. ### My tooltip is not working using `data-tippy` Make sure Tippy's scripts are placed _before_ your own scripts, at the very bottom of the page, like so: ```html <!DOCTYPE html> <html> <head> <title>My page</title> </head> <body> <button data-tippy="Created automatically">Text</button> <button data-tippy-content="Created by function">Text</button> <!-- Very end of the body --> <script src="https://unpkg.com/popper.js@1/dist/umd/popper.min.js"></script> <script src="https://unpkg.com/tippy.js@4"></script> <script> tippy('button') </script> </body> </html> ``` ### Can I use the `title` attribute? Yes. The `content` option can be a function that receives the reference element as an argument and returns a string or element. ```js tippy('button', { content(reference) { const title = reference.getAttribute('title') reference.removeAttribute('title') return title }, }) ``` The `title` attribute should be removed once you have its content so the browser's default tooltip isn't displayed along with the tippy. With the beauty of higher-order functions, you can "enhance" the base tippy function with new functionality. To add this behavior by default, you can do something like this at the very top of your scripts before any calls to `tippy()`: ```js function withTitleAttributeContent(tippy) { return (targets, options = {}) => { return tippy(targets, { ...options, content(reference) { if (options.content) { return options.content } const title = reference.getAttribute('title') reference.removeAttribute('title') return title }, }) } } window.tippy = withTitleAttributeContent(tippy) ``` ### My tooltip is hiding instantly after showing If you're using a `focus` trigger, for example on an `<input>`, make sure you also set `hideOnClick: false`.
Markdown
UTF-8
1,015
3.796875
4
[]
no_license
# Python Dev Notes ## Lists vs Tuples * Tuples are more lightweight and usually preferable when data becomes static. * The `list.append` function over-allocates space to the list (the assumption is that one append is the precursor of many appends). Therefore, it's possible to grow lists to be much larger than intended. * Not storing additional headroom by creating new tuples instead of appending has the advantage of not overallocating memory, but it may be slower if done repeatedly as the new allocation happens every time you want to grow a tuple. * Lists are larger than tuples even without `.append` as they have to keep track of a lot more information. * Python can also create tuples via resource caching - this means that tuples of size 1-20 aren't immediately garbage collected but saved for later use. The end result is that when a new tuple of the same size is needed in the future, we don't need to communicate with the operating system in order to find spare memory - it's already allocated.
Python
UTF-8
437
3.734375
4
[]
no_license
def cut_slices(target_list, a=0, b='', c=1): # 如果b未赋值 则设置为数组长度 if b == '': b = len(target_list) result_list = [] # 切片后的数组 step = 0 # 步数 for x in range(a, b): # 防止下标越界 if(x < len(target_list) and step % c == 0): result_list.append(target_list[x]) step += 1 print(result_list) target_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] cut_slices(target_list, 1, 9, 2)
Java
UTF-8
1,312
3.8125
4
[]
no_license
package playingcard; import java.util.Random; /** * * @author Marios Christodoulou */ public class Pack { PlayingCard[] cards = new PlayingCard[52]; public int counter = 0; /** * Constructs a pack of 52 cards. Sorted by suit Clubs, Diamonds, Hearts, * Spades. Sorted ascending. */ public Pack() { for (PlayingCard.Suit st : PlayingCard.Suit.values()) { for (PlayingCard.Rank rk : PlayingCard.Rank.values()) { cards[counter++] = new PlayingCard(st, rk); } } } /** * Shuffles cards in pack. */ public void shuffle() { Random random = new Random(); int n = cards.length; for (int i = 0; i < cards.length; i++) { int randomValue = i + random.nextInt(n - i); PlayingCard randomElement = cards[randomValue]; cards[randomValue] = cards[i]; cards[i] = randomElement; } } /** * @return string representation of 52 card pack. */ @Override public String toString() { String toReturn = "Deck of Cards["; for (PlayingCard c : cards) { toReturn = toReturn + " (" + c.getRank() + " of " + c.getSuit() + ")"; } return toReturn + "cards = " + cards.length + "]"; } }
Markdown
UTF-8
2,414
2.640625
3
[]
no_license
Mobile Tencent Analytics (MTA) is professional mobile App statistics and analysis tool for popular smartphone platforms and HTML5 Apps. Developers can easily embed it into statistics SDKs to monitor Apps in an all-round way, keep track of product performances in real time, and gain a precise insight into user behaviors. ### Highlights **Analysis of App operational data** Monitor and analyze basic metrics including new users, active users, and retained users to provide a comprehensive and detailed picture on the operational trend and health of your Apps. **Analysis of user behaviors and status** Combine data of different dimensions as needed to view the version and channel in real time, improving the refined operation effect and quality of your products. **User profile** Provide a complete and reliable user profile system based on 800 million QQ users to help you elaborate loyal users of your business in an all-around way. **Flexible configuration of custom events** Allow you to define statistics configurations for user behavior events and business calculation events according to business scenarios, to achieve in-depth statistics and analysis. ### Product Features **Real-time data statistics** Process data via multiple channels to achieve instant monitoring of key data efficiently. Keep track of user status based on real-time data, so as to improve product capabilities and adjust operational strategies. **On-demand combinations of data from different dimensions** Combine multi-dimensional data such as channel overview, version analysis, and user retention as needed, to help quickly pinpoint the marketing effect, improve user quality, and lay data foundations for product operation and updates. **User profile** Create a wealth of user tags for Apps in an easy manner. You can use the complete user profile system to know user behaviors and characteristics, and locate your target users based on such information. **Effect analysis across channels** Provide statistics of redirections from marketing activities, sharing links, and ads to H5 Apps, allowing you to know advertising effects in different channels and further improve operation quality. **Open statistics API** You can call the API directly to create a platform for monitoring the operational data in real-time. With this highly adaptive API, you can easily create an internal exclusive data platform based on your own needs.
Python
UTF-8
736
3.46875
3
[]
no_license
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def getDepth(self, root): if root == None: return 0 else: r = self.getDepth(root.right) l = self.getDepth(root.left) return max(r,l)+1 def isBalanced(self, root): if root == None: return True diff = self.getDepth(root.left) - self.getDepth(root.right) if diff > 1 or diff < -1: return False return self.isBalanced(root.left) and self.isBalanced(root.right)
C++
UTF-8
823
2.640625
3
[]
no_license
#include "servos.h" Servo armservo; Servo damper1; Servo damper2; void init_arm_servo() { armservo.attach(SENSOR_ARM_PIN); } void lower_arm_servo() { armservo.attach(SENSOR_ARM_PIN); armservo.write(ARM_ZERO_POSITION); //pinMode(SENSOR_ARM_PIN, INPUT); } void raise_arm_servo() { armservo.attach(SENSOR_ARM_PIN); armservo.write(ARM_RAISED_POSITION); //pinMode(SENSOR_ARM_PIN, INPUT); } void init_damper() { damper1.attach(DAMPER_SERVO_1); damper2.attach(DAMPER_SERVO_2); } void fold_damper() { damper1.write(180); damper2.write(0); } void lower_damper() { damper1.write(0); damper2.write(180); } void raise_damper() { damper1.write(90); damper2.write(90); } void deinit_damper() { pinMode(DAMPER_SERVO_1, INPUT); pinMode(DAMPER_SERVO_2, INPUT); }
Java
UTF-8
1,128
1.71875
2
[ "Apache-2.0" ]
permissive
package com.hacknife.loginsharepay.impl.login; import android.support.v7.app.AppCompatActivity; import com.hacknife.loginsharepay.impl.BaseLoginShare; import com.sina.weibo.sdk.auth.WbAuthListener; import com.tencent.mm.opensdk.modelmsg.SendAuth; import com.tencent.tauth.IUiListener; /** * author : Hacknife * e-mail : 4884280@qq.com * github : http://github.com/hacknife * project : LoginShare */ abstract class AbstractLogin extends BaseLoginShare implements WbAuthListener, IUiListener { public AbstractLogin(AppCompatActivity activity) { super(activity); } @Override public void launchWeiboLogin() { super.launchWeiboLogin(); ssoHandler.authorize(this); } @Override public void launchQQLogin() { super.launchQQLogin(); tencent.login(proxyFragment, "all", this); } @Override public void launchWechatLogin() { super.launchWechatLogin(); SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = proxyFragment.getContext().getPackageName(); iWXAPI.sendReq(req); } }
Markdown
UTF-8
1,173
2.625
3
[]
no_license
--- title: "'The Machine Stops'" format: "book" category: "f" yearReleased: "1909" author: "E.M. Forster" --- An early dystopia, in which Earth's future population, now living underground, has become slave to, and is beginning to worship, the Machine; a rebel discovers freedom above ground, but although those already living free survive, he is not spared when society collapses on the breakdown of the Machine.   George Woodcock found this the most interesting early anti-Utopia, with its "strong element of neo-Luddism". He felt it lacked immediacy, though, saying it "pays scanty attention to its social and political implications". (Woodcock 1956) For Ursula K. Le Guin this was "the first and finest" of the satirical utopias in which robots do the work and humans sit back and play (Le Guin 1982). Some short extracts were published in <em>Fifth Estate</em> #373 in 2006, where the full story was "highly recommended".   Since the advent of the Internet this story has gained in value from what may now be perceived as prescience. It won the Libertarian Futurist Society Hall of Fame Award in 2012. The tale is included in Dana's <em>AnarchoSF</em> V.1 (see bibliography).
Java
UTF-8
742
2.078125
2
[]
no_license
import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; /** * Created by lixindong on 25/7/16. */ public class RunInShell extends AnAction { @Override public void actionPerformed(AnActionEvent e) { WindowManager manager = WindowManager.getInstance(); Project project = e.getProject(); StatusBar statusBar = manager.getStatusBar(project); statusBar.setInfo("Here is the result"); ChooserDialog dialog = new ChooserDialog(project); dialog.show(); // dialog.showFileChooser(project); } }
Ruby
UTF-8
5,510
2.84375
3
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
#!/usr/bin/env ruby require 'open3' require 'curses' JQQ_VERSION = "0.0.1" FILE_Y = 0 EXPR_Y = 1 OUTPUT_Y = 2 CSI_UP = 'A' CSI_DOWN = 'B' CSI_RIGHT = 'C' CSI_LEFT = 'D' KEY_BACKSPACE = 127 KEY_CTRL_A = 1 KEY_CTRL_D = 4 KEY_CTRL_E = 5 KEY_CTRL_K = 11 KEY_CTRL_U = 21 KEY_ENTER = 10 KEY_ESCAPE = 27 KEY_LEFT_BRACKET = '[' KEY_WINDOW_RESIZE = 410 def jq(args, opts={}) cmds = [ ["jq"] + args, ["head", "-n", opts[:max_lines].to_s], ] io_read, io_write = IO.pipe statuses = Open3.pipeline(*cmds, :in=>io_read, :out=>io_write, :err=>io_write) io_write.close output = io_read.read exitstatus = statuses[0].exitstatus { :output => output, :exitstatus => exitstatus, } end def print_title(title_win, file) title_win.clear title_win.addstr("jqq: #{file}") title_win.refresh end def print_expr(expr_win, expr, expr_pos) expr_win.clear expr_win.addstr(expr) expr_win.setpos(0, expr_pos) expr_win.refresh end def print_output(output_win, expr, file, opts={}) results = jq([expr, file], :max_lines=>opts[:max_lines]) output_win.clear output_win.setpos(0, 0) output_win.addstr(results[:output]) output_win.refresh end def curses_main(argv) expr = argv[0] file = argv[1] Curses.noecho expr_win = Curses::Window.new( 1, # height Curses.cols, # width 1, # top 0 # left ) title_win = Curses::Window.new( 1, # height Curses.cols, # width 0, # top 0 # left ) output_win = Curses::Window.new( Curses.lines - 2, Curses.cols, 2, 0 ) expr_pos = expr.size print_title(title_win, file) print_expr(expr_win, expr, expr_pos) print_output(output_win, expr, file, :max_lines=>Curses.lines) expr_win.refresh escape_mode = false csi_mode = false # control sequence introducer running = true while running do should_render = false should_echo = false begin key = expr_win.getch if escape_mode if csi_mode case key when CSI_UP # TODO when CSI_DOWN # TODO when CSI_LEFT expr_pos = [0, expr_pos - 1].max should_echo = true when CSI_RIGHT expr_pos = [expr.size, expr_pos + 1].min should_echo = true end csi_mode = false escape_mode = false else # if not csi_mode if key == KEY_LEFT_BRACKET csi_mode = true elsif key == 'b' # alt-left escape_mode = false elsif key == 'f' # alt-right escape_mode = false elsif key == 127 # alt-backspace escape_mode = false else escape_mode = false end end else case key when KEY_BACKSPACE if expr_pos > 0 # remove character at expr_pos, effectively expr = expr[0...(expr_pos - 1)] + expr[expr_pos..-1] expr_pos -= 1 should_echo = true end when KEY_CTRL_A expr_pos = 0 should_echo = true when KEY_CTRL_D if expr_pos < expr.size expr = expr[0...expr_pos] + expr[(expr_pos + 1)..-1] should_echo = true end when KEY_CTRL_E expr_pos = expr.size should_echo = true when KEY_CTRL_K expr = expr[0...expr_pos] expr_pos = expr.size should_echo = true when KEY_CTRL_U expr = "" expr_pos = 0 should_echo = true when KEY_ENTER should_render = true when KEY_ESCAPE escape_mode = true when KEY_WINDOW_RESIZE should_render = true else # add character at expr_pos expr = expr[0...expr_pos] + key.chr + expr[expr_pos..-1] expr_pos += 1 should_echo = true end end if should_render print_expr(expr_win, expr, expr_pos) print_output(output_win, expr, file, :max_lines=>Curses.lines) expr_win.refresh elsif should_echo print_expr(expr_win, expr, expr_pos) expr_win.refresh end rescue Interrupt => e break end end { :expr => expr, :file => file, } end def usage $stderr.puts "Usage: jqq <expr> <file>" end def print_version $stderr.puts "jqq Version #{JQQ_VERSION}" end def missing_jq? `which jq`.strip.empty? end def print_needs_jq $stderr.puts 'jq not found in $PATH' end def preflight_check(argv) show_usage = false show_version = false show_needs_jq = false if argv.include?('--version') show_version = true elsif argv.size < 2 show_usage = true elsif missing_jq? show_needs_jq = true show_usage = true else filename = argv[-1] unless File.exist?(filename) && !File.directory?(filename) show_usage = true end end if show_needs_jq print_needs_jq exit 1 elsif show_version print_version exit 0 elsif show_usage usage exit 1 end end def print_helpful_command(expr, file) if /[ \[\]]/.match(expr) full_expr = "'%s'" % [expr] else full_expr = expr end puts "jqq #{full_expr} #{file}" end def main(argv) preflight_check(argv) Curses.init_screen begin state = curses_main(argv) ensure Curses.close_screen end print_helpful_command(state[:expr], state[:file]) end if __FILE__ == $0 main(ARGV) end
Python
UTF-8
2,380
2.71875
3
[]
no_license
# -*- coding: utf-8 -*- # @Auther : liou import math import torch from torch import nn import torch.nn.functional as F from .utils import clones def attention (query, key, value, mask = None, dropout = None) : """attention模型 输出为:softmax (q * k / d_k^0.5) * v d_k为词向量维度。 这个公式与乘性attention计算方式的唯一不同就在于使用了一个缩放因子d_k^0.5 论文中对缩放的解释: 在d_k比较小的时候,不加缩放的效果和加性attention效果差不多。 在d_k比较大的时候,不加缩放效果明显更差。 怀疑是当d_k增长的时候,内积的量级也会增长,导致softmax函数会被推向梯度较小的区域。 """ d_k = query.size (-1) scores = torch.matmul(query, key.transpose (-2, -1)) / math.sqrt(d_k) if mask is not None : # 将为0的地方替换为-1e9 scores = scores.masked_fill(mask == 0, -1e9) p_attn = F.softmax(scores, dim = -1) if dropout is not None : p_attn = dropout (p_attn) return torch.matmul(p_attn, value), p_attn class MultiHeadedAttention (nn.Module) : def __init__(self, h, d_model, dropout = 0.1): super(MultiHeadedAttention, self).__init__() # 默认八个头即h=8,序列长度为64,所以隐藏层即d_model长度为512 assert d_model % h == 0 self.d_k = d_model // h self.h = h self.linears = clones(nn.Linear (d_model, d_model), 4) self.attn = None self.dropout = nn.Dropout (p = dropout) def forward (self, query, key, value, mask = None) : if mask is not None : mask = mask.unsqueeze (1) nbatches = query.size (0) # 此处zip返回项数最少的,linears有四层而qkv只有三个,所以只返回三个值,即为qkv的linears query, key, value = [l(x).view(nbatches, -1, self.h, self.d_k).transpose (1, 2) for l, x in zip (self.linears, (query, key, value))] # 多头attention x, self.attn = attention(query, key, value, mask=mask, dropout=self.dropout) x = x.traspose (1, 2).contiguout ().view (nbatches, -1, self.h * self.d_k) return self.linears[-1](x)
C++
UTF-8
1,792
2.515625
3
[ "MIT" ]
permissive
#include "transport.h" #include <zmq.h> #include <leveldb/env.h> #include <sstream> #include <iostream> Transport::Transport(InQueue* q_in_, OutQueue* q_out_, leveldb::Logger* logger_) : packer(&buffer) , logger(logger_) , q_in(q_in_) , q_out(q_out_){ } bool Transport::recv_next(Message* message){ msgpack::unpacked result; while (unpacker.next(&result)) { message->messsage = result.get(); message->zone = std::unique_ptr<msgpack::zone>(result.zone().release()); return true; } return false; } void Transport::commit_message(){ IdMesage res(identity, std::string(buffer.data(), buffer.size())); q_out->block_push(res); buffer.clear(); } void Transport::load_message(){ IdMesage msg = q_in->block_pop(); identity = msg.first; unpacker.reserve_buffer(msg.second.size()); memcpy(unpacker.buffer(), msg.second.data(), msg.second.size()); unpacker.buffer_consumed(msg.second.size()); } leveldb::WriteOptions WriteOptions::get_leveldb_options(){ leveldb::WriteOptions result; result.sync = sync; return result; } leveldb::ReadOptions ReadOptions::get_leveldb_options(){ leveldb::ReadOptions result; result.fill_cache = fill_cache; result.verify_checksums = verify_checksums; return result; } Status::Status(const leveldb::Status &ldb_status){ if (ldb_status.ok()){ code = (int)StatusCode::OK; } else if (ldb_status.IsNotFound()){ code = (int)StatusCode::NotFound; } else{ code = (int)StatusCode::Corruption; reason = "unknown code"; } } RangeValue::RangeValue(leveldb::Iterator *it){ status = it->status(); key.assign(it->key().data(), it->key().size()); value.assign(it->value().data(), it->value().size()); }
Markdown
UTF-8
5,478
2.953125
3
[]
no_license
# Spring-Boot Camel Narayana Quickstart This quickstart uses Narayana TX manager with Spring Boot and Apache Camel on Openshift to test 2PC/XA transactions with a JMS resource (ActiveMQ) and a database (PostgreSQL). The application uses a *in-process* recovery manager and a persistent volume to store transaction logs. The application **does not support scaling**. Having two pods running can lead to inconsistencies because multiple Narayana recovery managers (using the same transaction manager id) cannot run in parallel. The `DeploymentConfig` uses a `Recreate` strategy to avoid running two instances in parallel during re-deployment. To avoid issues with network partitioning, the user must ensure that the storage provider supports *innate locking*, to prevent multiple pods in different nodes to mount the same persistent volume (`spring-boot-camel-narayana`) concurrently. ## Installation Setup a Openshift instance, login, create a project, then execute the following command to deploy the quickstart: ``` mvn clean fabric8:deploy ``` This command will deploy a PostgreSQL database, a ActiveMQ broker and a Spring-Boot application. ## Usage Once the application is deployed you can get the base service URL using the following command: ``` NARAYANA_HOST=$(oc get route spring-boot-camel-narayana -o jsonpath={.spec.host}) ``` The application exposes the following rest URLs: - GET on `http://$NARAYANA_HOST/api/`: list all messages in the `audit_log` table (ordered) - POST on `http://$NARAYANA_HOST/api/?entry=xxx`: put a message `xxx` in the `incoming` queue for processing ### Simple workflow First get a list of messages in the `audit_log` table: ``` curl -w "\n" http://$NARAYANA_HOST/api/ ``` The list should be empty at the beginning. Now you can put the first element. ``` curl -w "\n" -X POST http://$NARAYANA_HOST/api/?entry=hello # wait a bit curl -w "\n" http://$NARAYANA_HOST/api/ ``` The new list should contain two messages: `hello-1` and `hello-1-ok`. The first part of each audit log is the message sent to the queue (`hello`), the second number is the progressive number of delivery when it has been processed correctly (`1` is the first delivery attempt). The `hello-1-ok` confirms that the message has been sent to a `outgoing` queue and then logged. You can add multiple messages and see the logs. The following actions force the application in some corner cases to examine the behavior. #### Sporadic exception handling Send a message named `failOnce`: ``` curl -w "\n" -X POST http://$NARAYANA_HOST/api/?entry=failOnce # wait a bit curl -w "\n" http://$NARAYANA_HOST/api/ ``` This message produces an exception in the first delivery, so that the transaction is rolled back. A subsequent redelivery (`JMSXDeliveryCount` > 1) is processed correctly. In this case you should find **two log records** in the `audit_log` table: `failOnce-2`, `failOnce-2-ok` (the message is processed correctly at **delivery number 2**). #### Repeatable exception handling Send a message named `failForever`: ``` curl -w "\n" -X POST http://$NARAYANA_HOST/api/?entry=failForever # wait a bit curl -w "\n" http://$NARAYANA_HOST/api/ ``` This message produces an exception in all redeliveries, so that the transaction is always rolled back. You should **not** find any trace of the message in the `audit_log` table. If you check the application log, you'll find out that the message has been sent to the dead letter queue. #### Safe system crash Send a message named `killOnce`: ``` curl -w "\n" -X POST http://$NARAYANA_HOST/api/?entry=killOnce # wait a bit (the pod should be restarted) curl -w "\n" http://$NARAYANA_HOST/api/ ``` This message produces a **immediate crash** of the application in the first delivery, so that the transaction is not committed. After **the pod is restarted** by Openshift, a subsequent redelivery (`JMSXDeliveryCount` > 1) is processed correctly. In this case you should find **two log records** in the `audit_log` table: `killOnce-2`, `killOnce-2-ok` (the message is processed correctly at **delivery number 2**). #### Unsafe system crash Send a message named `killBeforeCommit`: ``` curl -w "\n" -X POST http://$NARAYANA_HOST/api/?entry=killBeforeCommit # wait a bit (the pod should be restarted) curl -w "\n" http://$NARAYANA_HOST/api/ ``` This message produces a **immediate crash after the first phase of the 2pc protocol and before the final commit**. The message **must not** be processed again, but the transaction manager was not able to send a confirmation to all resources. If you check the `audit_log` table in the database while the application is down, you'll not find any trace of the message (it will appear later). After **the pod is restarted** by Openshift, the **recovery manager will recover all pending transactions by communicatng with the participating resources** (database and JMS broker). When the recovery manager has finished processing failed transactions, you should find **two log records** in the `audit_log` table: `killBeforeCommit-1`, `killBeforeCommit-1-ok` (no redeliveries here, the message is processed correctly at **delivery number 1**). ## Credits This quickstart is based on the work of: - Christian Posta ([christian-posta/spring-boot-camel-narayana](https://github.com/christian-posta/spring-boot-camel-narayana)) - Gytis Trikleris ([gytis/spring-boot-narayana-stateful-set-example](https://github.com/gytis/spring-boot-narayana-stateful-set-example))
Java
UTF-8
1,687
4
4
[]
no_license
package dp; /** 801. Minimum Swaps To Make Sequences Increasing We have two integer sequences A and B of the same non-zero length. We are allowed to swap elements A[i] and B[i]. Note that both elements are in the same index position in their respective sequences. At the end of some number of swaps, A and B are both strictly increasing. (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.length - 1].) Given A and B, return the minimum number of swaps to make both sequences strictly increasing. It is guaranteed that the given input always makes it possible. Example: Input: A = [1,3,5,4], B = [1,2,3,7] Output: 1 Explanation: Swap A[3] and B[3]. Then the sequences are: A = [1, 3, 5, 7] and B = [1, 2, 3, 4] which are both strictly increasing. Note: A, B are arrays with the same length, and that length will be in the range [1, 1000]. A[i], B[i] are integer values in the range [0, 2000]. */ public class M801 { public int minSwap(int[] A, int[] B) { if (A.length <= 1) return 0; int len = A.length; int dp[][] = new int[len][2]; dp[0][0] = 0; // not swap dp[0][1] = 1; // swap for (int i = 1; i < len; i++) { dp[i][0] = dp[i][1] = Integer.MAX_VALUE; if (A[i] > A[i-1] && B[i] > B[i-1]) { dp[i][0] = dp[i-1][0]; dp[i][1] = dp[i-1][1] + 1; } if (A[i] > B[i-1] && B[i] > A[i-1]) { dp[i][1] = Math.min(dp[i][1], dp[i-1][0] + 1); dp[i][0] = Math.min(dp[i][0], dp[i-1][1]); } } return Math.min(dp[len-1][0], dp[len-1][1]); } }
Java
UTF-8
377
2.671875
3
[]
no_license
package com.bobsystem.structural.decorator; import com.bobsystem.structural.decorator.interfaces.IPainter; public class BluePainter extends Painter { public BluePainter() { } public BluePainter(IPainter paint) { super(paint); } @Override public void paint() { System.out.println("刷 蓝漆"); super.paint(); } }
C++
UTF-8
9,135
2.953125
3
[ "MIT" ]
permissive
#include <iostream> #include <functional> #include <numeric> #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" using namespace std; using namespace std::placeholders; using Line = vector<char>; using Lines = vector<Line>; template<typename DestinationType> auto transformAll = [](const auto& source, const auto fn){ DestinationType result; transform(source.begin(), source.end(), back_inserter(result), fn); return result; }; auto toRange = [](const auto& collection){ vector<int> range(collection.size()); iota(begin(range), end(range), 0); return range; }; auto concatenate = [](const auto& first, const auto& second){ auto result(first); result.insert(result.end(), make_move_iterator(second.begin()), make_move_iterator(second.end())); return result; }; auto concatenate3 = [](const auto& first, const auto& second, const auto& third){ return concatenate(concatenate(first, second), third); }; using Coordinate = pair<int, int>; auto accessAtCoordinates = [](const auto& board, const Coordinate& coordinate){ return board[coordinate.first][coordinate.second]; }; auto mainDiagonalCoordinates = [](const auto& board){ auto range = toRange(board); return transformAll<vector<Coordinate>>(range, [](const auto index){return make_pair(index, index);}); }; auto secondaryDiagonalCoordinates = [](const auto& board){ auto range = toRange(board); return transformAll<vector<Coordinate>>(range, [board](const auto index){return make_pair(index, board.size() - index - 1);}); }; auto columnCoordinates = [](const auto& board, const auto& columnIndex){ auto range = toRange(board); return transformAll<vector<Coordinate>>(range, [columnIndex](const auto index){return make_pair(index, columnIndex);}); }; auto lineCoordinates = [](const auto board, auto lineIndex){ auto range = toRange(board); return transformAll<vector<Coordinate>>(range, [lineIndex](const auto index){return make_pair(lineIndex, index);}); }; auto projectCoordinates = [](const auto& board, const auto& coordinates){ auto boardElementFromCoordinates = bind(accessAtCoordinates, board, _1); return transformAll<Line>(coordinates, boardElementFromCoordinates); }; class BoardResult{ private: const vector<Line> board; public: BoardResult(const vector<Line>& board) : board{board}{ }; Lines allLinesColumnsAndDiagonals() const { return concatenate3(allLines(), allColumns(), allDiagonals()); } Line mainDiagonal() const { return projectCoordinates(board, mainDiagonalCoordinates(board)); } Line secondaryDiagonal() const{ return projectCoordinates(board, secondaryDiagonalCoordinates(board)); } Line column(const int columnIndex) const { return projectCoordinates(board, columnCoordinates(board, columnIndex)); } Line line(const int lineIndex) const { return projectCoordinates(board, lineCoordinates(board, lineIndex)); } Lines allLines() const { auto range = toRange(board); return transformAll<Lines>(range, [this](auto index) { return line(index); }); } Lines allColumns() const { auto range = toRange(board); return transformAll<Lines>(range, [this](auto index) { return column(index); }); } Lines allDiagonals() const{ return {mainDiagonal(), secondaryDiagonal()}; } }; auto all_of_collection = [](const auto& collection, const auto& fn){ return all_of(collection.begin(), collection.end(), fn); }; auto any_of_collection = [](const auto& collection, const auto& fn){ return any_of(collection.begin(), collection.end(), fn); }; template<typename SourceType, typename DestinationType> auto applyAllLambdasToValue = [](const auto& fns, const auto& value){ return transformAll<DestinationType>(fns, [value](const auto& fn){ return fn(value); } ); }; auto lineFilledWith = [](const auto& line, const auto& tokenToCheck){ return all_of_collection(line, [&tokenToCheck](const auto& token){ return token == tokenToCheck;}); }; template <typename CollectionBooleanOperation, typename CollectionProvider, typename Predicate> auto booleanOperationOnProvidedCollection(CollectionBooleanOperation collectionBooleanOperation, CollectionProvider collectionProvider, Predicate predicate){ return [=](const auto& collectionProviderSeed, const auto& predicateFirstParameter){ return collectionBooleanOperation(collectionProvider(collectionProviderSeed), bind(predicate, _1, predicateFirstParameter)); }; } //auto tokenWins = booleanOperationOnProvidedCollection(any_of_collection, allLinesColumnsAndDiagonals, lineFilledWith); //auto xWins = bind(tokenWins, _1, 'X'); //auto oWins = bind(tokenWins, _1, 'O'); auto noneOf = [](const auto& collection, const auto& fn){ return none_of(collection.begin(), collection.end(), fn); }; auto isEmpty = [](const auto& token){return token == ' ';}; auto isNotEmpty= [](const auto& token){return token != ' ';}; auto fullLine = bind(all_of_collection, _1, isNotEmpty); auto full = [](const auto& board){ return all_of_collection(board, fullLine); }; //auto draw = [](auto const board){ // return full(board) && !xWins(board) && !oWins(board); //}; //auto inProgress = [](auto const board){ // return !full(board) && !xWins(board) && !oWins(board); //}; auto findInCollection = [](const auto& collection, const auto& fn){ auto result = find_if(collection.begin(), collection.end(), fn); return (result == collection.end()) ? nullopt : optional(*result); }; auto findInCollectionWithDefault = [](const auto& collection, const auto& defaultResult, const auto& fn){ auto result = findInCollection(collection, fn); return result.has_value() ? (*result) : defaultResult; }; TEST_CASE("lines"){ BoardResult boardResult{{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }}; Line expectedLine0 = {'X', 'X', 'X'}; CHECK_EQ(expectedLine0, boardResult.line(0)); Line expectedLine1 = {' ', 'O', ' '}; CHECK_EQ(expectedLine1, boardResult.line(1)); Line expectedLine2 = {' ', ' ', 'O'}; CHECK_EQ(expectedLine2, boardResult.line(2)); } TEST_CASE("all columns"){ BoardResult boardResult{{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }}; Line expectedColumn0{'X', ' ', ' '}; CHECK_EQ(expectedColumn0, boardResult.column(0)); Line expectedColumn1{'X', 'O', ' '}; CHECK_EQ(expectedColumn1, boardResult.column(1)); Line expectedColumn2{'X', ' ', 'O'}; CHECK_EQ(expectedColumn2, boardResult.column(2)); } TEST_CASE("main diagonal"){ BoardResult boardResult{{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }}; Line expectedDiagonal{'X', 'O', 'O'}; CHECK_EQ(expectedDiagonal, boardResult.mainDiagonal()); } TEST_CASE("secondary diagonal"){ BoardResult boardResult{{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }}; Line expectedDiagonal{'X', 'O', ' '}; CHECK_EQ(expectedDiagonal, boardResult.secondaryDiagonal()); } TEST_CASE("all lines, columns and diagonals"){ BoardResult boardResult{{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }}; Lines expected{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'}, {'X', ' ', ' '}, {'X', 'O', ' '}, {'X', ' ', 'O'}, {'X', 'O', 'O'}, {'X', 'O', ' '} }; auto all = boardResult.allLinesColumnsAndDiagonals(); CHECK_EQ(expected, all); } /* TEST_CASE("X wins"){ Board board { {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }; CHECK(xWins(board)); } TEST_CASE("O wins"){ Board board { {'X', 'O', 'X'}, {' ', 'O', ' '}, {' ', 'O', 'X'} }; CHECK(oWins(board)); } TEST_CASE("draw"){ Board board { {'X', 'O', 'X'}, {'O', 'O', 'X'}, {'X', 'X', 'O'} }; CHECK(draw(board)); } TEST_CASE("in progress"){ Board board { {'X', 'O', 'X'}, {'O', ' ', 'X'}, {'X', 'X', 'O'} }; CHECK(inProgress(board)); } */ TEST_CASE("Project column"){ BoardResult boardResult{{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }}; Line expected0 {'X', ' ', ' '}; CHECK_EQ(expected0, boardResult.column(0)); Line expected1 {'X', 'O', ' '}; CHECK_EQ(expected1, boardResult.column(1)); Line expected2 {'X', ' ', 'O'}; CHECK_EQ(expected2, boardResult.column(2)); } TEST_CASE("Range"){ vector<vector<char>> collection{ {'X', 'X', 'X'}, {' ', 'O', ' '}, {' ', ' ', 'O'} }; vector<int> expected {0, 1, 2}; CHECK_EQ(expected, toRange(collection)); CHECK_EQ(expected, toRange(collection[0])); }
C#
UTF-8
753
2.515625
3
[]
no_license
using System; using System.Linq; using System.Xml.Linq; namespace Adapter.Classes { class PlikConverter { public XDocument GetXML() { var xDocument = new XDocument(); var xElement = new XElement("Producenci"); var xAttributes = DaneProducenta.GetData() .Select(k => new XElement("Producent", new XAttribute("Nazwa", k.Nazwa), new XAttribute("Firma", k.Firma), new XAttribute("Ilosc", k.Ilosc))); xElement.Add(xAttributes); xDocument.Add(xElement); Console.WriteLine(xDocument); return xDocument; } } }
Markdown
UTF-8
3,205
3.015625
3
[]
no_license
--- ID: 344 post_title: 'RHCSA &#8211; Copying files from one server to another using SCP' author: sher post_excerpt: "" layout: post permalink: > https://codingbee.net/tutorials/rhcsa/rhcsa-copying-files-from-one-server-to-another-using-scp published: true post_date: 2015-04-06 00:00:00 --- <h2>Overview</h2> By the end of this article you should be able to answer the following questions: [accordion] [toggle title="Assume you are logged in as the user 'tom' on machine 'LinuxA'. Let’s say that there is a machine called 'LinuxB' and there is a user account called 'jerry' on machine 'LinuxB'. Also on LinuxB you have the file, '/tmp/testfile.txt'. Now what is the command to copy /tmp/testfile.txt from LinuxB to the tom’s home directory on LinuxA?"] [tom@LinuxA ~]$ scp jerry@LinuxB:/tmp/testfile.txt /home/tom [/toggle] [toggle title="Following on from the above scenario, What is the command to copy /home/tom/testfile.txt to jerry's home directory on LinuxB?"] [tom@LinuxA ~]$ scp /home/tom/testfile.txt jerry@LinuxB:/home/jerry/testfile.txt [/toggle] [/accordion] <hr/> What if you want to copy files from one machine to another machine. There are a few ways to do this, e.g. via ftp, nfs, cifs....etc. We will cover all these options later. But for now we'll cover the easiest file copying option, called scp, which comes as part of the ssh suite. The scp is like using the cp command, but this time you have to specify the remote machine's name, and username. For example, you are logged in as the user tom on machine LinuxA. Let's say that there is a machine called LinuxB and there is a user account called 'jerry' on machine LinuxB. Also on LinuxB you have the file, /tmp/testfile.txt. Now here's the command to copy /tmp/testfile.txt from LinuxB to the tom's home directory on LinuxA.: <pre> [tom@LinuxA ~]$ scp jerry@LinuxB:/tmp/testfile.txt /home/tom jerry@LinuxB's password: testfile.txt 100% 12 0.0KB/s 00:00 $ ls -l total 4 -rw-r--r--. 1 tom tom 12 Nov 14 13:06 testfile.txt </pre> Note, here we got prompted to enter jerry's password. However if you have set up ssh private/public keys, as in the last article, then you won't get prompted to enter the password, since scp is essentially ssh with a bit of extra syntax. Now let's say you want to copy to file back to LinuxB but this time place it in the /home/jerry directory, then you do: <pre> [tom@LinuxA ~]$ scp /home/tom/testfile.txt jerry@LinuxB:/home/jerry/testfile.txt jerry@puppetagent01's password: testfile.txt 100% 12 0.0KB/s 00:00 </pre> Now let's check this has worked: <pre> [tom@LinuxA ~]$ ssh jerry@LinuxB jerry@puppetagent01's password: [jerry@puppetagent01 ~]$ ls -l /home/jerry/ total 4 -rw-r--r--. 1 jerry jerry 12 Nov 14 13:13 testfile.txt </pre> <h2>Further reading</h2> If you are using a windows machine, and want to copy files to/from a linux machine, then you can still use scp, by firsting installing <a href="https://winscp.net/eng/download.php" rel="nofollow">winscp</a> on your windows machine.
C++
UTF-8
2,473
2.796875
3
[]
no_license
/*************************************************************************************************************** A class which are able to show stack of methods and position of executing. It will assist developers tracing the code without gdb. Author: Ireul Lin ***************************************************************************************************************/ #ifndef __NAILTRACE__ #define __NAILTRACE__ namespace nail{ class Trace { private: Trace(const Trace&); Trace& operator= (const Trace&); int m_showType; std::string m_szFile; std::string m_szFunction; int m_line; // only for print char m_header[128]; char* fillHeader() { struct timeb _tmb; ftime(&_tmb); struct tm* _ptm = localtime(&_tmb.time); memset(&m_header[0], 0, sizeof(m_header)); sprintf(&m_header[0], "%06ld %02d:%02d:%02d.%03d", pthread_self() % 1000000, _ptm->tm_hour, _ptm->tm_min, _ptm->tm_sec, _tmb.millitm ); return &m_header[0]; } public: Trace(int showType, const std::string& szFile, const std::string& szFunction) :m_showType(showType),m_szFile(szFile),m_szFunction(szFunction),m_line(0) { if(m_showType!=ON) return; printf("%s Enter function \033[0;36m%s\033[m\n", fillHeader(), m_szFunction.c_str() ); } ~Trace() { if(m_showType!=ON) return; printf("%s Leave function \033[0;36m%s\033[m\n", fillHeader(), m_szFunction.c_str() ); } void line(int line) {m_line = line;} int line() {return m_line;} void show(const char* format, ...) { if(m_showType==OFF) return; char _buff[2048]; memset(&_buff[0], 0, sizeof(_buff)); va_list args; va_start(args, format); vsprintf(&_buff[0], format, args); va_end(args); printf("%s \033[0;32;32m%s(%d)\033[m shows \"\033[1;33m%s\033[m\"\n", fillHeader(), m_szFile.c_str(), m_line, _buff ); } void error(const char* format, ...) { if(m_showType==OFF) return; char _buff[2048]; memset(&_buff[0], 0, sizeof(_buff)); va_list args; va_start(args, format); vsprintf(&_buff[0], format, args); va_end(args); printf("%s \033[0;32;32m%s(%d)\033[m error \"\033[0;32;31m%s\033[m\"\n", fillHeader(), m_szFile.c_str(), m_line, _buff ); assert(false); } void position(int line) { if(m_showType==OFF) return; printf("%s \033[0;32;32m%s(%d)\033[m is current position\n", fillHeader(), m_szFile.c_str(), line ); } }; } #endif
C#
UTF-8
3,114
2.78125
3
[]
no_license
using System; using System.Reflection; using System.Text; using System.Runtime.Serialization; namespace exception_test { class Program { static void ExceptionTest0() { try { Console.WriteLine("try: {0}", MethodBase.GetCurrentMethod().Name); ExceptionTest1(); } finally { Console.WriteLine("finally: {0}", MethodBase.GetCurrentMethod().Name); } } static void ExceptionTest1() { try { Console.WriteLine("try: {0}", MethodBase.GetCurrentMethod().Name); ExceptionTest2(); } catch (Exception ex) { Console.WriteLine("catch: {0}", MethodBase.GetCurrentMethod().Name); Console.WriteLine(ex.Message); System.Console.WriteLine(ex.StackTrace); } finally { Console.WriteLine("finally: {0}", MethodBase.GetCurrentMethod().Name); } } static void ExceptionTest2() { try { Console.WriteLine("try: {0}", MethodBase.GetCurrentMethod().Name); ExceptionTest3(); } catch (Exception ex) { throw; // will not reset the StackTrace start point //throw ex; // reset the StackTrace start point } finally { Console.WriteLine("finally: {0}", MethodBase.GetCurrentMethod().Name); } } static void ExceptionTest3() { try { Console.WriteLine("try: {0}", MethodBase.GetCurrentMethod().Name); throw (new Exception(new string("exception: " + MethodBase.GetCurrentMethod().Name))); } finally { Console.WriteLine("finally: {0}", MethodBase.GetCurrentMethod().Name); } } static void Main(string[] args) { {// Diagnostics test DiagnosticsTest.Test(); } long start_memory_use = GC.GetTotalMemory(false); ExceptionTest0(); Console.WriteLine("Hello World!"); SerializationInfo si; AClassWithAThrowMethod acwatm = new AClassWithAThrowMethod(); dynamic acwatmd = acwatm; try { acwatmd.ThrowAnException(); } catch (OutOfMemoryException ex) { Console.WriteLine("It is not a targetinvokeException, Msg: {0}", ex.Message); } catch (TargetInvocationException ex) { Console.WriteLine("It is really a targetinvokeException, Msg: {0}", ex.Message); } Console.WriteLine(GC.CollectionCount(0)); Console.WriteLine("Total memory change from start: {0}", GC.GetTotalMemory(false) - start_memory_use); } } }
Python
UTF-8
1,463
3.71875
4
[]
no_license
# import some function in modules from sys import argv from cs50 import get_string # kecheck function def key_check(text): for i in text: if str.isalpha(i): pass else: return False return True # shift function to keep track of the case def shift(char): if str.isupper(char): return ord(char) - 65 else: return ord(char) - 97 # check if two command line were entered if len(argv) == 2: # check the key and get its length if key_check(argv[1]) == True: key = argv[1] len_key = len(key) index_key = 0 # get the plaintext from the user text = get_string("plaintext: ") # cipher the plaintext print("ciphertext: ", end="") for i in text: if str.isalpha(i): # ciphering key c_key c_key = shift(key[index_key % len_key]) # print ciphered char c_char if str.isupper(i): c_char = ((ord(i) - 65) + c_key) % 26 + 65 print(chr(c_char), end="") else: c_char = ((ord(i) - 97) + c_key) % 26 + 97 print(chr(c_char), end="") index_key += 1 else: print(i, end="") print() else: print("Usage: python vigenere.py k") exit(1) else: print("Usage: python vigenere.py k") exit(1)
C++
UHC
1,127
2.890625
3
[]
no_license
/* ¥: 2020-01-06 з: DFS TIP: visited 迭 ʴ DFS */ #include <iostream> #pragma warning (disable: 4996) using namespace std; int R, C; char board[22][22] = { 0 }; //int visited[22][22] = { 0 }; int check[200] = { 0 }; int move_x[4] = { 0, 0, 1, -1 }; int move_y[4] = { 1, -1, 0, 0 }; int max_depth = 1; void dfs(int x, int y, int depth); int main() { scanf("%d %d", &R, &C); for (int i = 1; i <= R; i++) { for (int j = 1; j <= C; j++) { scanf(" %c", &board[i][j]); } } check[board[1][1]] = 1; dfs(1, 1, max_depth); printf("%d", max_depth); return 0; } void dfs(int x, int y, int depth) { //visited[x][y] = 1; for (int i = 0; i < 4; i++) { int next_x = x + move_x[i]; int next_y = y + move_y[i]; if (next_x < 1 || next_y < 1 || next_x > R || next_y > C) continue; //if (visited[next_x][next_y] == 0 && check[board[next_x][next_y]] == 0) { if (check[board[next_x][next_y]] == 0) { check[board[next_x][next_y]] = 1; if (max_depth < depth + 1) { max_depth = depth + 1; } dfs(next_x, next_y, depth + 1); check[board[next_x][next_y]] = 0; } } }
Java
UTF-8
3,148
2.375
2
[]
no_license
package uk.co.rbs.openbanking.servicedesk.services; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.*; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.json.JSONException; import uk.co.rbs.openbanking.servicedesk.services.pojo.AspspResultSet; import java.io.IOException; import java.security.*; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import static uk.co.rbs.openbanking.servicedesk.services.Config.*; public class AspspLookupService { public static String OB_OD_URL = "https://matls-api.openbankingtest.org.uk/scim/v2/OBAccountPaymentServiceProviders/"; public AspspLookupService() {} public static AspspResultSet callAspspService(String accessToken) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException, JSONException, InvalidKeySpecException { AspspResultSet resultSet = null; Header[] headers = { new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json") , new BasicHeader(HttpHeaders.ACCEPT, "application/json") , new BasicHeader("Authorization", "Bearer " + accessToken) }; ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); StringEntity entity = new UrlEncodedFormEntity(postParameters, "UTF-8"); CloseableHttpClient closeableHttpClient = MatlsConnectivityHelper. createCloseableHttpClient(TLS_VERSIONS, IDENTITY_KEYSTORE_PATH, TRUSTSTORE_PATH, CERT_ALIAS, CERT_PASSWORD); HttpResponse response = HttpsConnectionHelper.callEndPoint(closeableHttpClient, OB_OD_URL, entity, headers, RequestMethod.HTTP_GET); HttpEntity stringEntity = response.getEntity(); if (response.getStatusLine().getStatusCode()==200) { ObjectMapper mapper = new ObjectMapper(); String entityToString = EntityUtils.toString(stringEntity, "UTF-8"); //JSON from String to Object resultSet = mapper.readValue(entityToString, AspspResultSet.class); } return resultSet; } public static void main( String[] args ) { try { String accessToken = Token.getTokenResponse().getAccessToken(); System.out.println(accessToken); AspspResultSet ass = callAspspService(accessToken); ass.getResources().forEach(item->item.getAuthorisationServers().forEach(server->System.out.println(server.getCustomerFriendlyName()))); } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException | IOException | JSONException | InvalidKeySpecException e) { e.printStackTrace(); } } }
Ruby
UTF-8
4,899
2.515625
3
[ "MIT" ]
permissive
# frozen_string_literal: true class NoResponseService < Polist::Service def call; end end class BasicService < Polist::Service def call success!(a: 1) end end class ServiceWithForm < BasicService class Form < Polist::Service::Form attribute :a, :String attribute :b, :Integer attribute :c, :String end def call form.b == 2 ? success!(form.attributes) : fail!(code: :bad_input) end end class ServiceWithValidations < ServiceWithForm class Form < ServiceWithForm::Form validates :c, presence: { message: "bad c" } end def call validate! end end class ServiceWithParams < BasicService param :p1, :p2 def call success!(params: [p1, p2]) end end class FailingInnerService < BasicService def call params[:fail] ? error!("message") : success! end end class OuterService < BasicService def call FailingInnerService.call(fail: true) end end class FailingOuterService < BasicService def call FailingInnerService.call(fail: params[:inner_fail]) fail! rescue FailingInnerService::Failure error!("inner service failure") rescue Failure error!("failure") end end class ServiceWithBlock < BasicService def call success!(yield(1, 2)) end end class ServiceWichRescueBlock < BasicService def call yield rescue StandardError => error success!(error) end end RSpec.describe Polist::Service do specify "basic usage" do service = BasicService.run expect(service.success?).to eq(true) expect(service.failure?).to eq(false) expect(service.response).to eq(a: 1) end specify "no response service" do service = NoResponseService.run expect(service.success?).to eq(true) expect(service.response).to eq(nil) end describe "service with form" do specify "good input" do service = ServiceWithForm.run(a: "1", b: "2") expect(service.success?).to eq(true) expect(service.response).to eq(a: "1", b: 2, c: nil) end specify "bad input" do service = ServiceWithForm.run(a: "1", b: "3") expect(service.success?).to eq(false) expect(service.response).to eq(code: :bad_input) end end describe "service with form with validations" do specify ".run method" do service = ServiceWithValidations.run(a: "1", b: "2") expect(service.success?).to eq(false) expect(service.response).to eq(error: "bad c") end specify ".call method" do expect { ServiceWithValidations.call(a: "1", b: "2") }.to raise_error do |error| expect(error.class).to eq(ServiceWithValidations::Failure) expect(error.response).to eq(error: "bad c") end end end describe "service with params" do specify "basic params usage" do service = ServiceWithParams.run(p1: "1", p2: "2") expect(service.success?).to eq(true) expect(service.response).to eq(params: %w[1 2]) end end describe "service with inner service call" do specify do expect { OuterService.run }.to raise_error(FailingInnerService::Failure) end end describe "failing service with inner service call" do specify "inner service fails" do service = FailingOuterService.run(inner_fail: true) expect(service.success?).to eq(false) expect(service.response).to eq(error: "inner service failure") end specify "inner service doesn't fail" do service = FailingOuterService.run(inner_fail: false) expect(service.success?).to eq(false) expect(service.response).to eq(error: "failure") end end describe ".register_middleware" do let(:first_middleware) { Class.new(Polist::Service::Middleware) } let(:second_middleware) { Class.new(Polist::Service::Middleware) } before do BasicService.__polist_middlewares__.clear BasicService.register_middleware(first_middleware) BasicService.register_middleware(second_middleware) end it "stores middlewares in the service class" do expect(BasicService.__polist_middlewares__) .to contain_exactly(first_middleware, second_middleware) end it "raises error if middleware is not a subclass of Polist::Service::Middleware" do expect { BasicService.register_middleware(String) } .to raise_error(Polist::Service::MiddlewareError, "Middleware String should be a subclass of Polist::Service::Middleware") end end describe "service with yielding" do it "sums args in proc" do service = ServiceWithBlock.call { |a, b| a + b } expect(service.success?).to eq(true) expect(service.response).to eq(3) end it "runs, rescues, and returns success" do service = ServiceWichRescueBlock.run { raise StandardError, "Awesome Message" } expect(service.success?).to eq(true) expect(service.response.message).to eq("Awesome Message") end end end
JavaScript
UTF-8
7,054
3.15625
3
[]
no_license
// определяем число ли это или нет function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); // Метод isNaN пытается преобразовать переданный параметр в число. // Если параметр не может быть преобразован, возвращает true, иначе возвращает false. // isNaN("12") // false } // проверка пересеклась ли стена с другой стеной (когда тащим точку) function crossLineOnLine_1(point) { var wall = infProject.scene.array.wall; for ( var i = 0; i < point.w.length; i++ ) { for ( var i2 = 0; i2 < wall.length; i2++ ) { if(point.w[i] == wall[i2]) { continue; } if(Math.abs(point.position.y - wall[i2].userData.wall.p[0].position.y) > 0.3) continue; // проверка высоты этажа var p0 = point.w[i].userData.wall.p[0].position; var p1 = point.w[i].userData.wall.p[1].position; var p2 = wall[i2].userData.wall.p[0].position; var p3 = wall[i2].userData.wall.p[1].position; if(intersectWall_3(p0, p1, p2, p3)) { return true; } // стены пересеклись } } return false; // стены не пересеклись } // точка пересечения двух прямых 2D function crossPointTwoLine(a1, a2, b1, b2) { var t1 = DirectEquation(a1.x, a1.z, a2.x, a2.z); var t2 = DirectEquation(b1.x, b1.z, b2.x, b2.z); var point = new THREE.Vector3(); var f1 = DetMatrix2x2(t1[0], t1[1], t2[0], t2[1]); if(Math.abs(f1) < 0.0001){ return new THREE.Vector3(a2.x, 0, a2.z); } point.x = DetMatrix2x2(-t1[2], t1[1], -t2[2], t2[1]) / f1; point.z = DetMatrix2x2(t1[0], -t1[2], t2[0], -t2[2]) / f1; //if(Math.abs(f1) < 0.0001){ point = new THREE.Vector3(a1.x, 0, a1.z); console.log(77); } return point; } // точка пересечения двух прямых 2D с доп.параметром = паралельны ли линии или нет function crossPointTwoLine_2(a1, a2, b1, b2) { var t1 = DirectEquation(a1.x, a1.z, a2.x, a2.z); var t2 = DirectEquation(b1.x, b1.z, b2.x, b2.z); var f1 = DetMatrix2x2(t1[0], t1[1], t2[0], t2[1]); if(Math.abs(f1) < 0.0001) { var s1 = new THREE.Vector3().subVectors( a1, b1 ); var s2 = new THREE.Vector3().addVectors( s1.divideScalar( 2 ), b1 ); return [new THREE.Vector3(s2.x, 0, s2.z), true]; // паралельны } var point = new THREE.Vector3(); point.x = DetMatrix2x2(-t1[2], t1[1], -t2[2], t2[1]) / f1; point.z = DetMatrix2x2(t1[0], -t1[2], t2[0], -t2[2]) / f1; //if(Math.abs(f1) < 0.0001){ point = new THREE.Vector3(a1.x, 0, a1.z); console.log(77); } return [point, false]; } // точка пересечения двух прямых 2D function crossPointTwoLine_3(a1, a2, b1, b2) { var t1 = DirectEquation(a1.x, a1.z, a2.x, a2.z); var t2 = DirectEquation(b1.x, b1.z, b2.x, b2.z); var point = new THREE.Vector3(); var f1 = DetMatrix2x2(t1[0], t1[1], t2[0], t2[1]); if(Math.abs(f1) < 0.0001){ return [new THREE.Vector3(a2.x, 0, a2.z), true]; } // параллельны point.x = DetMatrix2x2(-t1[2], t1[1], -t2[2], t2[1]) / f1; point.z = DetMatrix2x2(t1[0], -t1[2], t2[0], -t2[2]) / f1; return [point, false]; } function DirectEquation(x1, y1, x2, y2) { var a = y1 - y2; var b = x2 - x1; var c = x1 * y2 - x2 * y1; return [ a, b, c ]; } function DetMatrix2x2(x1, y1, x2, y2) { return x1 * y2 - x2 * y1; } // Проверка двух отрезков на пересечение (ориентированная площадь треугольника) function CrossLine(a, b, c, d) { return intersect_1(a.x, b.x, c.x, d.x) && intersect_1(a.z, b.z, c.z, d.z) && area_1(a, b, c) * area_1(a, b, d) <= 0 && area_1(c, d, a) * area_1(c, d, b) <= 0; } function intersect_1(a, b, c, d) { if (a > b) { var res = swap(a, b); a = res[0]; b = res[1]; } if (c > d) { var res = swap(c, d); c = res[0]; d = res[1]; } return Math.max(a, c) <= Math.min(b, d); } function area_1(a, b, c) { return (b.x - a.x) * (c.z - a.z) - (b.z - a.z) * (c.x - a.x); } // меняем местами 2 значения function swap(a, b) { var c; c = a; a = b; b = c; return [a, b]; } // проекция точки(С) на прямую (A,B) function spPoint(A,B,C){ var x1=A.x, y1=A.z, x2=B.x, y2=B.z, x3=C.x, y3=C.z; var px = x2-x1, py = y2-y1, dAB = px*px + py*py; var u = ((x3 - x1) * px + (y3 - y1) * py) / dAB; var x = x1 + u * px, z = y1 + u * py; return {x:x, y:0, z:z}; } // опредяляем, надодится точка D за пределами прямой или нет (точка D пересекает прямую АВ, идущая перпендикулярна от точки С) function calScal(A,B,C) { var AB = { x : B.x - A.x, y : B.z - A.z }; var CD = { x : C.x - A.x, y : C.z - A.z }; var r1 = AB.x * CD.x + AB.y * CD.y; // скалярное произведение векторов var AB = { x : A.x - B.x, y : A.z - B.z }; var CD = { x : C.x - B.x, y : C.z - B.z }; var r2 = AB.x * CD.x + AB.y * CD.y; var cross = (r1 < 0 | r2 < 0) ? false : true; // если true , то точка D находится на отрезке AB return cross; } // расстояние от точки до прямой function lengthPointOnLine(p1, p2, M) { var urv = DirectEquation(p1.x, p1.z, p2.x, p2.z); var A = urv[0]; var B = urv[1]; var C = urv[2]; return Math.abs( (A * M.x + B * M.z + C) / Math.sqrt( (A * A) + (B * B) ) ); } //https://ru.stackoverflow.com/questions/464787/%D0%A2%D0%BE%D1%87%D0%BA%D0%B0-%D0%B2%D0%BD%D1%83%D1%82%D1%80%D0%B8-%D0%BC%D0%BD%D0%BE%D0%B3%D0%BE%D1%83%D0%B3%D0%BE%D0%BB%D1%8C%D0%BD%D0%B8%D0%BA%D0%B0 //Точка внутри многоугольника function checkPointInsideForm(point, arrP) { var p = arrP; var result = false; var j = p.length - 1; for (var i = 0; i < p.length; i++) { if ( (p[i].position.z < point.position.z && p[j].position.z >= point.position.z || p[j].position.z < point.position.z && p[i].position.z >= point.position.z) && (p[i].position.x + (point.position.z - p[i].position.z) / (p[j].position.z - p[i].position.z) * (p[j].position.x - p[i].position.x) < point.position.x) ) result = !result; j = i; } return result; } // сравнить позиционирование function comparePos(pos1, pos2, cdm) { if(!cdm) cdm = {}; var x = pos1.x - pos2.x; var y = pos1.y - pos2.y; var z = pos1.z - pos2.z; var kof = (cdm.kof) ? cdm.kof : 0.01; var equals = true; if(Math.abs(x) > kof){ equals = false; } if(Math.abs(y) > kof){ equals = false; } if(Math.abs(z) > kof){ equals = false; } return equals; }
Markdown
UTF-8
1,117
2.578125
3
[]
no_license
# Article L138-5 Les entreprises visées à l'article L. 138-1 sont tenus d'adresser à l'Agence centrale des organismes de sécurité sociale les éléments nécessaires en vue de la détermination de la progression du chiffre d'affaires réalisé au cours de chaque trimestre civil, avant le dernier jour du deuxième mois suivant la fin de chacun de ces trimestres . **Liens relatifs à cet article** **Liens**: - SPEC_APPLI: Loi n°96-1160 1996-12-27 art. 32 VIII : les dispositions du présent article s'appliquent au chiffre d'affaires réalisé à compter du 1er janvier 1997 _Modifié par_: - Loi n°98-1194 1998-12-23 art. 31 I, II 1° JORF 27 décembre 1998 - Loi n°98-1194 du 23 décembre 1998 - art. 31 () JORF 27 décembre 1998 _Abrogé par_: - Loi n°2003-1199 du 18 décembre 2003 - art. 15 () JORF 19 décembre 2003 en vigueur le 1er janvier 2004 _Cite_: - Code de la santé publique - art. L596 (M) - Code de la sécurité sociale. - art. L138-1 (M) _Cité par_: - Code de la sécurité sociale. - art. L245-6-2 (Ab) - Code de la sécurité sociale. - art. R138-1 (M)
JavaScript
UTF-8
1,670
2.90625
3
[]
no_license
/** @jsx React.DOM */ var MovieBox = React.createClass({displayName: "MovieBox", getInitialState: function() { return {data: []}; }, componentDidMount: function() { $.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); }, render: function() { return ( React.createElement("div", {className: "movieBox"}, React.createElement(MovieList, {data: this.state.data}) ) ); } }); var MovieList = React.createClass({displayName: "MovieList", render: function() { var movieNodes = this.props.data.map(function(movie) { var imagePath = "images/" + movie.imdbid + ".jpg"; return ( React.createElement(MovieCard, {name: movie.name, imagePath: imagePath} ) ); }); return ( React.createElement("div", {className: "movieList"}, movieNodes ) ); } }); var MovieCard = React.createClass({displayName: "MovieCard", render: function() { return ( React.createElement("div", {class: "movieCard"}, React.createElement("h4", {className: "movieName"}, this.props.name ), React.createElement("img", {clasName: "movieImage", src: this.props.imagePath, alt: this.props.name}) ) ) } }); console.log('react prerender'); React.render( React.createElement(MovieBox, {url: "movies.json"}), document.getElementById('content') ); console.log('react afterrender');
Java
UTF-8
4,381
2.390625
2
[]
no_license
package porsius.nl.topo.data; import android.content.Context; import android.location.Location; import android.os.Handler; import android.webkit.JavascriptInterface; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import porsius.nl.topo.create.EditMapActivity; /** * Created by linda on 01/11/14. */ public class EditMapInterface { private MMapLoc locSelected; private Context context; private MMap map; public List<MMapLoc> list; public List<MMapLoc> toDelete = new ArrayList<MMapLoc>(); private Handler handler; private int clickable = 0; /** * Instantiate the interface and set the context */ public EditMapInterface(Context c) { this(c, null, null); } public EditMapInterface(Context c, MMap map, Handler h) { this.context = c; this.map = map; this.handler = h; MapLocDatasource mapLocDatasource = new MapLocDatasource(context); mapLocDatasource.open(); if(map!=null) { list = mapLocDatasource.getAllLocs(map.getId()); } mapLocDatasource.close(); } @JavascriptInterface public int getClickable() { return clickable; } @JavascriptInterface public void setClickable(int c) { this.clickable=c; } @JavascriptInterface public void setNewButtonGray() { handler.post(new Runnable() { @Override public void run() { EditMapActivity.setNewButtonGray(); } }); } @JavascriptInterface public String getMark() { String result = ""; for(int i=0;i<list.size();i++){ double lat = list.get(i).getLat(); double lng = list.get(i).getLng(); System.out.println(" ooo "+ lat + " "+lng); if(lat!=0 && lng!=0) result = result + lat + "," + lng + "|"; } while(result.endsWith("|")) { result = result.substring(0, result.length()-1); } return result; } /** Show a toast from the web page */ @JavascriptInterface public void showToast(String toast) { Toast.makeText(context, toast, Toast.LENGTH_SHORT).show(); } @JavascriptInterface public void setLocSelected(int index) { locSelected = list.get(index); } public MMapLoc getLocSelected() { return locSelected; } @JavascriptInterface public void showName(final int index) { handler.post(new Runnable() { @Override public void run() { // This gets executed on the UI thread so it can safely modify Views EditMapActivity.setEditText(list.get(index).getName()); } }); } @JavascriptInterface public void changeLoc(int index, String latlng){ Location loc = getLocFromString(latlng); MMapLoc mloc = list.get(index); mloc.setLat(loc.getLatitude()); mloc.setLng(loc.getLongitude()); EditMapActivity.madeChanges = true; } public List<MMapLoc> getList() { return list; } public List<MMapLoc> getListToDelete() { return toDelete; } @JavascriptInterface public void addToList(String latlng) { Location loc = getLocFromString(latlng); MMapLoc mloc = new MMapLoc(); mloc.setLat(loc.getLatitude()); mloc.setLng(loc.getLongitude()); mloc.setMap_id(map.getId()); list.add(mloc); EditMapActivity.madeChanges = true; } public Location getLocFromString(String latlng) { Location loc = new Location("topo"); int start = latlng.indexOf("("); int end = latlng.indexOf(","); String lat = latlng.substring(start+1, end); int end1 = latlng.indexOf(")"); String lng = latlng.substring(end + 1, end1); loc.setLatitude(Double.valueOf(lat)); loc.setLongitude(Double.valueOf(lng)); return loc; } @JavascriptInterface public void delete(int i) { MMapLoc loc = list.get(i); if(loc!=null) toDelete.add(loc); EditMapActivity.madeChanges = true; } @JavascriptInterface public int getListSize() { return list.size(); } }
C++
UTF-8
2,134
3.0625
3
[]
no_license
#include <iostream> #include <fstream> #include <queue> #include "Maze.h" typedef std::pair<int, int> Coord; const Coord NOWHERE(-1, -1); const int dirLin[4] = { -1, 0, 1, 0 }; const int dirCol[4] = { 0, 1, 0, -1 }; void find_exit(Maze& maze, Coord source) { /* Pentru a reconstitui drumul, vom folosi o matrice de parinti. */ Coord parent[maze.get_height()][maze.get_width()]; for (unsigned int i = 0; i < maze.get_height(); ++i) { for (unsigned int j = 0; j < maze.get_width(); ++j) { parent[i][j] = NOWHERE; } } /* Vom folosi BFS pentru a determina drumul optim. Cream o coada pe care o * intializam cu prima celula. */ std::queue<Coord> q; q.push(source); parent[source.first][source.second] = source; while (!q.empty()) { Coord pos = q.front(); q.pop(); for (unsigned int dir = 0; dir < 4; ++dir) { Coord newPos(pos.first + dirLin[dir], pos.second + dirCol[dir]); /* Verificam ca nou pozitie pe care o incercam este o pozitie valida de pe * harta in care se poate muta. */ if (maze.is_walkable(newPos)) { if (maze.is_exit_point(newPos)) { parent[newPos.first][newPos.second] = pos; /* Tiparim solutia si iesim. */ do { maze.mark_solution_step(newPos); newPos = parent[newPos.first][newPos.second]; } while (newPos != source); maze.mark_solution_step(source); return; } else if (parent[newPos.first][newPos.second] == NOWHERE) { /* Nu adaugam noua pozitie in coada decat daca nu se afla deja. */ parent[newPos.first][newPos.second] = pos; q.push(newPos); } } } } } int main() { /* Citim o harta din fisierul de intrare. */ std::ifstream in("src-lab6/Labirint.txt"); Maze maze; unsigned int lineTrudy, columnTrudy; in >> maze >> lineTrudy >> columnTrudy; /* Calculam pe ea drumul din labirint. */ find_exit(maze, Coord(lineTrudy, columnTrudy)); /* Si afisam drumul final. */ std::cout << "Labirintul cu drumul marcat spre iesire este: " << std::endl << maze; return 0; }
C++
UTF-8
211
2.890625
3
[]
no_license
#include<iostream> using namespace std; int main(){ int n=6; int fact,i; fact = 1; for(i=1;i<=n;i++) { fact = fact*i; cout<<"Fact "<<fact; } cout<<"\n Final result :"<<fact; return 0; }
Java
UTF-8
514
1.882813
2
[]
no_license
package com.lzit.dao; import java.util.ArrayList; import java.util.Date; import com.lzit.entity.Cart; import com.lzit.entity.Orders; public interface OrdersDao { public ArrayList<Orders> showOrders(String username); public void insertOrders(String buydate,double totalprice,String orderstate, String username,ArrayList<Cart> list); public void updateOrderstate(int orderid,String orderstate); public ArrayList<Orders> showAllOrders(int pageno,int pagesize); public long getAllOrdersCount(); }
Java
UTF-8
571
2.828125
3
[]
no_license
package ProjectOneEngine; import java.util.Random; public class RandomPlayer implements Player{ public Move getMove(GameState state){ Random rand = new Random(); boolean done = false; PlayerID cur_player = state.getCurPlayer(); Move rand_move = null; while ( ! done ){ int bin = rand.nextInt(6); rand_move = new Move(bin, cur_player); if (GameRules.makeMove(state, rand_move) != null){ done = true; } } return rand_move; } public String getPlayName(){ return "Completely Random Player"; } }
Python
UTF-8
1,009
2.890625
3
[ "MIT" ]
permissive
import abc import numpy as np from .viewport import Viewport from .window import Window from cairo import Context from geometry import hpt class DrawContext: def __init__(self, viewport: Viewport, win: Window, ctx: Context): self.viewport = viewport self.win = win self.ctx = ctx def viewport_transform(self, p): x, y, _ = (p - self.win._ppc[0]) / self.win.size return hpt(x, 1 - y) @ self.viewport.matrix() class GraphicalObject: def __init__(self, name: str, points: np.ndarray): self._name = name self.points: np.ndarray = points self._ppc: np.ndarray = None @property def name(self) -> str: return self._name @property def center(self) -> np.ndarray: n = len(self.points[:, 0]) c = sum(self.points) return c / n @abc.abstractmethod def draw(self, ctx: DrawContext) -> None: pass def draw_verbose(self, ctx: DrawContext) -> None: self.draw(ctx)
Python
UTF-8
2,815
2.71875
3
[]
no_license
import unittest from patients_line import PatientsLine from patient import Patient class TestPatientsLine(unittest.TestCase): def test_empty_line(self): line = PatientsLine() self.assertEqual(0, line.get_plus_patients_length()) self.assertEqual(0, line.get_minus_patients_length()) self.assertEqual(0, line.get_line_length()) self.assertIsNone(line.get_next_patient()) def test_add_patients(self): line = PatientsLine() line.add_to_line(Patient("+", 2)) line.add_to_line(Patient("+", 4)) self.assertEqual(2, line.get_plus_patients_length()) self.assertEqual(0, line.get_minus_patients_length()) line.add_to_line(Patient("-", 3)) self.assertEqual(2, line.get_plus_patients_length()) self.assertEqual(1, line.get_minus_patients_length()) line.elapse_time() self.assertEqual(2, line.get_plus_patients_length()) self.assertEqual(1, line.get_minus_patients_length()) line.elapse_time() self.assertEqual(1, line.get_plus_patients_length()) self.assertEqual(1, line.get_minus_patients_length()) line.elapse_time() self.assertEqual(1, line.get_plus_patients_length()) self.assertEqual(0, line.get_minus_patients_length()) line.elapse_time() self.assertEqual(0, line.get_plus_patients_length()) self.assertEqual(0, line.get_minus_patients_length()) line.elapse_time() line.elapse_time() line.elapse_time() line.elapse_time() line.elapse_time() line.elapse_time() def test_get_patients(self): line = PatientsLine() line.add_to_line(Patient("+", 2)) line.add_to_line(Patient("-", 4)) line.add_to_line(Patient("+", 3)) line.add_to_line(Patient("-", 2)) self.assertEqual("+", line.get_next_patient().corona_test_result) self.assertEqual("+", line.get_next_patient().corona_test_result) self.assertEqual("-", line.get_next_patient().corona_test_result) self.assertEqual("-", line.get_next_patient().corona_test_result) self.assertEqual(0, line.get_line_length()) line.add_to_line(Patient("+", 2)) line.add_to_line(Patient("-", 4)) line.add_to_line(Patient("+", 3)) line.add_to_line(Patient("-", 2)) line.elapse_time() line.elapse_time() self.assertEqual("+", line.get_next_patient().corona_test_result) self.assertEqual("-", line.get_next_patient().corona_test_result) if __name__ == "__main__": unittest.main()
PHP
UTF-8
1,281
3.0625
3
[ "Apache-2.0" ]
permissive
<?php /** Copyright 2012-2013 Brainsware 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. */ namespace Sauce; /* This class adds two convenient methods to the original DateTime class: * #now and #db_format. */ class DateTime extends \DateTime { /* Returns the current time/date (NOW) as new DateTime object. * * If no format is given, the default format is used: 'Y-m-d H:i:s'. */ public static function now($format = '') { $now = new self(); return $now->format(empty($format) ? 'Y-m-d H:i:s' : $format); } /* Returns the stored time in a (default) format usable for databases. * * If format is given, the default format is used: 'Y-m-d H:i:s' */ public function db_format ($format = 'Y-m-d H:i:s') { return $this->format($format); } } ?>
Python
UTF-8
3,547
3.265625
3
[]
no_license
import pandas as pd import datetime as datetime def read_data(path): df = pd.read_csv(path) print("Reading CSV file...") df = df.drop('Date', 1) df['Date'] = [datetime.datetime.strptime(d[0:18], "%Y-%m-%d %H:%M:%S") for d in df["Rounded_Date"]] df['Day'] = [datetime.datetime.date(d) for d in df["Date"]] df['Time'] = [datetime.datetime.time(d) for d in df["Date"]] df = df.set_index(['Day','Time']) df = df.drop('Date', 1) return df def Cull_Quiet_Intervals(df, threshold): size = [] x= 0 print("Culling intervals below threshold....") new_df = df cnt = 0 removed_cnt = 0 for date, small_df in new_df.groupby(level='Day'): x += 1 if small_df.shape[0] < threshold: x -= 1 cnt +=1 removed_cnt += small_df.shape[0] new_df = new_df.drop(date, level=0) size.append(small_df.shape[0]) print("got rid of ", cnt, "intervals resulting into ", removed_cnt, "tweets removed, so you have ", x, " intervals left") print('Avg: ', sum(size)/len(size), ' min: ', min(size), ' max: ', max(size)) return new_df def avg(x): return sum(x)/len(x) def Final_DF(file_path, cull_threshold): df = read_data(file_path) df = Cull_Quiet_Intervals(df, cull_threshold) # Removes intervals below this threshold columns = ['Time', 'fear','anger', 'anticipation','trust', 'suprise', 'positive', 'negative', 'sadness','disgust','joy', 'Volume_of_tweets','Retweet','Replies','Likes', 'Close', 'Open'] final_df = pd.DataFrame(columns=columns) i = 0 for interval, new_df in df.groupby(level=0): fear = 0 anger = 0 anticipation =0 trust = 0 suprise =0 pos = 0 neg = 0 sadness = 0 disgust = 0 joy = 0 daily_volume = 0 likes= 0 retweets= 0 replies= 0 i = i + 1 for index, row in new_df.iterrows(): daily_volume += 1 pos += row['positive'] neg += row['negative'] likes += row['Likes'] retweets += row['Retweet'] replies += row['Replies'] fear += row['fear'] anger += row['anger'] anticipation += row['anticipation'] trust += row['trust'] suprise += row['surprise'] sadness += row['sadness'] disgust += row['disgust'] joy += row['joy'] rows = {'Time': interval, 'positive': pos / daily_volume, 'negative': neg / daily_volume, 'fear': fear / daily_volume, 'anger': anger / daily_volume, 'anticipation': anticipation / daily_volume, 'trust': trust / daily_volume, 'suprise': suprise / daily_volume, 'sadness': sadness / daily_volume, 'disgust': disgust / daily_volume, 'joy': joy / daily_volume, 'Volume_of_tweets': daily_volume, 'Retweet': retweets/ daily_volume, 'Replies': replies /daily_volume, 'Likes': likes/daily_volume, 'Close': avg(new_df['close_price']), 'Open': avg(new_df['open_price'])} final_df = final_df.append(rows, ignore_index=True) final_df.to_csv('/Users/gabriel/PycharmProjects/Finance/Data/5B- grouped final results no ML/FB_1d_final_results_no_ML.csv') path = '/Users/gabriel/PycharmProjects/Finance/Data/4B-Ungrouped non-ML sentiment/FB_1d_no_ML.csv' Final_DF(path, 0)
C++
UTF-8
12,681
2.984375
3
[]
no_license
/** * Title: Market * Author: Tonia Sanzo * Date: 6/9/21 * * Game manages the game entities (npcs, rugs, etc.) */ #include "PCH.h" #include "Game.h" #include "ThreadSafeRNG.h" // Constructor Game::Game() { sdl = nullptr; mLoading = true; mInitSuccess = true; mCurrLoadingFrame = 0; } // Loads the game objects and renders the loading screen while they are initializing bool Game::start(SDLManager* aSDL) { srand(static_cast<unsigned>(time(0))); // Success status of this function bool success = true; // Save the SDLManager sdl = aSDL; if (!sdl) { // cout << "Game::start(SDLManager* aSDL) was passed a nullptr argument.\n"; success = false; } else { // Determine the ratio to scale the background assets by float wRatio = static_cast<float>(SDLManager::mWindowWidth) / static_cast<float>(BACKGROUND_WIDTH); float hRatio = static_cast<float>(SDLManager::mWindowHeight) / static_cast<float>(BACKGROUND_HEIGHT); float backgroundScale = (wRatio > hRatio) ? (wRatio) : (hRatio); if (!initLoadingScreen(backgroundScale)) { // cout << "Game::start(SDLManager* aSDL) call to initLoadingScreen(..) failed.\n"; success = false; } else { std::thread initThread(&Game::init, this, backgroundScale); // Game running flag bool quit = false; // Event handler SDL_Event e; // Timing variables const uint16_t FPS = 60; const uint16_t frameDelay = 1000 / FPS; Uint32 fStart; uint16_t fTime; Uint32 pTime = SDL_GetTicks(); Uint32 cTime = pTime; while (mLoading && !quit) { fStart = SDL_GetTicks(); // Exit if the user quits while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { quit = true; mLoading = false; } } // Determine the amount of time in seconds since the last time update was called cTime = SDL_GetTicks(); pTime = cTime; // Draw the game world to the screen mRendererMutex.lock(); SDL_SetRenderDrawColor(sdl->getRenderer(), 0xD3, 0xD3, 0xD3, 0xFF); SDL_RenderClear(sdl->getRenderer()); mLoadingBackgroundTexture.render(0, 0, &mLoadingFrames[mCurrLoadingFrame]); SDL_RenderPresent(sdl->getRenderer()); mRendererMutex.unlock(); // This measures how long this iteration of the loop took fTime = SDL_GetTicks() - fStart; // This keeps us from displaying more frames than 60 if (frameDelay > fTime) { SDL_Delay(frameDelay - fTime); } } initThread.join(); if (quit || !mInitSuccess) { success = false; } } } return success; } // Initialize the game world void Game::init(const float& aBackgroundScale) { if (!mWorld.init()) { // cout << "Failed to initialize the World!\n"; mInitSuccess = false; } else { // Load the rugs shared resources mRugTexture.initTexture(sdl->getRenderer()); if (!mRugTexture.loadFromFile("assets/rug.png")) { // cout << "Failed to load rug sprite sheet!\n"; mInitSuccess = false; } else { mRugTexture.updateScale(RUG_SCALE); // Set the rug's frames dimensions for (uint16_t row = 0; row < RUG_FRAME_ROWS; ++row) { for (uint16_t col = 0; col < RUG_FRAME_COLS; ++col) { mRugFrames[(row * RUG_FRAME_COLS) + col].x = col * RUG_FRAME_WIDTH; mRugFrames[(row * RUG_FRAME_COLS) + col].y = row * RUG_FRAME_HEIGHT; mRugFrames[(row * RUG_FRAME_COLS) + col].w = RUG_FRAME_WIDTH; mRugFrames[(row * RUG_FRAME_COLS) + col].h = RUG_FRAME_HEIGHT; } } // Create 1 unique rugs for (uint16_t i = 0; i < ENTITY_COUNT; ++i) { rugs.push_back(new Rug()); rugs[i]->init(&mRugTexture, mRugFrames, mWorld); } // Load the NPCs shared resources mNPCTexture.initTexture(sdl->getRenderer()); if (!mNPCTexture.loadFromFile("assets/npc.png")) { // cout << "Failed to load rug sprite sheet!\n"; mInitSuccess = false; } else { mNPCTexture.updateScale(NPC_SCALE); // Set the npc's frames dimensions for (uint16_t row = 0; row < NPC_FRAME_ROWS; ++row) { for (uint16_t col = 0; col < NPC_FRAME_COLS; ++col) { mNPCFrames[(row * NPC_FRAME_COLS) + col].x = col * NPC_FRAME_WIDTH; mNPCFrames[(row * NPC_FRAME_COLS) + col].y = row * NPC_FRAME_HEIGHT; mNPCFrames[(row * NPC_FRAME_COLS) + col].w = NPC_FRAME_WIDTH; mNPCFrames[(row * NPC_FRAME_COLS) + col].h = NPC_FRAME_HEIGHT; } } // Create unique NPCs for (uint16_t i = 0; i < ENTITY_COUNT; ++i) { npcs.push_back(new NPC()); npcs[i]->init(&mNPCTexture, mNPCFrames, &mWorld); } // Load the background and scale it to fit the screen mBackgroundTexture.initTexture(sdl->getRenderer()); if (!mBackgroundTexture.loadFromFile("assets/bckgrnd.png")) { // cout << "Failed to load the background texture!\n"; mInitSuccess = false; } else { mBackgroundTexture.updateScale(aBackgroundScale); // Seed the thread safe random number with a random number Seed_ThreadSafeRNG(rand() % 333); // Order the world partitions in different threads vector<thread> localThreads; // warm up the game so it starts smoothly { update(1.f); update(1.f); this_thread::sleep_for(std::chrono::milliseconds(250)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); mCurrLoadingFrame = 0; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); mCurrLoadingFrame = 0; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(100)); ++mCurrLoadingFrame; this_thread::sleep_for(std::chrono::milliseconds(300)); } } } } } mLoading = false; } /** * Loads the loading screen assets * @param aBackgroundScale - Ratio to scale the background assets * @return {bool} True if we successfully load the assets, otherwise false. */ bool Game::initLoadingScreen(const float& aBackgroundScale) { bool success = true; // Load the loading screen background and scale it to fit the screen mLoadingBackgroundTexture.initTexture(sdl->getRenderer()); if (!mLoadingBackgroundTexture.loadFromFile("assets/loading_bckgrnd.png")) { // cout << "Failed to load the loading screen background texture!\n"; success = false; } else { mLoadingBackgroundTexture.updateScale(aBackgroundScale); // Set the blood frame dimensions for (uint16_t row = 0; row < LOAD_FRAME_ROWS; ++row) { for (uint16_t col = 0; col < LOAD_FRAME_COLS; ++col) { mLoadingFrames[(row * LOAD_FRAME_COLS) + col].x = col * BACKGROUND_WIDTH; mLoadingFrames[(row * LOAD_FRAME_COLS) + col].y = row * BACKGROUND_HEIGHT; mLoadingFrames[(row * LOAD_FRAME_COLS) + col].w = BACKGROUND_WIDTH; mLoadingFrames[(row * LOAD_FRAME_COLS) + col].h = BACKGROUND_HEIGHT; } } } return success; } // Handle's user events bool Game::handleEvent(SDL_Event& e) { if (e.type == SDL_QUIT) { return true; } // If someone pressed a key if (e.type == SDL_KEYDOWN && e.key.repeat == 0) { switch (e.key.keysym.sym) { case SDLK_ESCAPE: return true; break; default: // cout << "Unhandled Key!\n"; break; } } return false; } // Update the game world void Game::update(const float& dt) { for (uint16_t i = 0; i < ENTITY_COUNT; ++i) { threads.push_back(thread(&NPC::update, npcs[i], dt, Rand_ThreadSafeRNG(), Rand_ThreadSafeRNG())); threads.push_back(thread(&Rug::update, rugs[i], dt)); } // Order each world parition in seperate threads threads.push_back(thread(&World::orderWorld, &mWorld, EWorldPartition::LEFT)); threads.push_back(thread(&World::orderWorld, &mWorld, EWorldPartition::CENTER)); threads.push_back(thread(&World::orderWorld, &mWorld, EWorldPartition::RIGHT)); for (thread& thread : threads) { thread.join(); } threads.clear(); } // Render the game world void Game::render() { mBackgroundTexture.render(0, 0); for (Rug* rug : rugs) { rug->renderFull(); } // Render each world parition in seperate threads threads.push_back(thread(&World::render, &mWorld, EWorldPartition::LEFT)); threads.push_back(thread(&World::render, &mWorld, EWorldPartition::CENTER)); threads.push_back(thread(&World::render, &mWorld, EWorldPartition::RIGHT)); for (thread& thread : threads) { thread.join(); } threads.clear(); } // Deallocate the game world void Game::close() { // Delete rugs mRugTexture.free(); for (auto rug : rugs) { if (rug) { delete rug; rug = nullptr; } } rugs.clear(); // Delete npcs mNPCTexture.free(); for (auto npc : npcs) { if (npc) { delete npc; npc = nullptr; } } npcs.clear(); // If sdl is a valid pointer change it to a nullptr, no need to explicitly delete the // sdl pointer because it's managed by the SDLManager if (sdl) { sdl = nullptr; } }
Shell
UTF-8
3,103
3.546875
4
[]
no_license
alias dm=docker-machine; dmenv() { eval $(docker-machine env $1); } dms() { _machine_data="$(docker-machine ls --format='{{.Name}} {{.URL}} {{.Active}}')" _ssh_machine=(${_machine_data}) # cheating to get first name from list _manager_url=$(docker info --format="{{range .Swarm.RemoteManagers}} {{.Addr}} {{end}}" | head -n 1 | sed -n 's/^[^0-1]*\([^:]*\).*$/\1/p') if [ -z "${_manager_url}" ] then _manager_url=$(docker-machine ssh ${_ssh_machine} "docker info --format='{{range .Swarm.RemoteManagers}} {{.Addr}} {{end}}'" | head -n 1 | sed -n 's/^[^0-1]*\([^:]*\).*$/\1/p') fi printf "%s %s %s\n" "${_machine_data}" | awk -v u=${_manager_url} 'BEGIN {a="-u"} $2 ~ "(^|[^0-9])" u "([^0-9]|$)" {m=$1} $3=="*" {a=$1} END {print a " " m}' } dsps() { declare -a _machine_data IFS=' ' read -a _machine_data <<<"$(dsmachines) " _current=${_machine_data[0]} _manager=${_machine_data[1]} _stack_name=$1 if [ "${_current}" == "${_manager}" ] then docker stack ps ${_stack_name} --filter "desired-state=running" --format "table {{.Name}}\t{{.Node}}\t{{.CurrentState}}\t{{.Ports}}" else docker-machine ssh "${_manager}" "docker stack ps ${_stack_name} --filter 'desired-state=running' --format 'table {{.Name}}\t{{.Node}}\t{{.CurrentState}}\t{{.Ports}}'" fi } ds() { _command="$1" if [ $# -eq 3 ] then _task_name=$3 declare -a _machine_data IFS=' ' read -a _machine_data <<<"$(dsmachines) " _current=${_machine_data[0]} _manager=${_machine_data[1]} if [ "${_current}" == "${_manager}" ] then _stack_vm=$(docker stack ps $2 --filter "name=$_task_name" --filter "desired-state=running" --format "{{.Node}}" 2>/dev/null) else _stack_vm=$(docker-machine ssh "${_manager}" "docker stack ps $2 --filter 'name=$_task_name' --filter 'desired-state=running' --format '{{.Node}}'" 2>/dev/null) fi if [ -z "${_stack_vm}" ] then echo "No task found with name ${_task_name} in stack $2" >&2 return fi if [ "${_current}" != "${_stack_vm}" ] then dmenv "${_stack_vm}" fi else _current="" _stack_vm="" _task_name=$2 fi _task_id=$(docker ps --filter "name=$_task_name" --format "{{.ID}}" 2>/dev/null) if [ "${_task_id}" ] then case "${_command}" in "bash" ) docker exec -it ${_task_id} bash ;; "logs" ) docker logs --tail all --follow ${_task_id} ;; * ) echo "ds: ${_command} is not a valid argument." >&2 ;; esac else echo "No task found with name ${_task_name} on this machine" >&2 return fi if [ "${_current}" != "${_stack_vm}" ] then dmenv ${_current} fi } db() { OPTIND=1 cache=--no-cache push="" while getopts ":v:pc" opt do case "${opt}" in "v" ) version="${OPTARG}" ;; "p" ) push="y" ;; "c" ) cache="" ;; "?" ) echo "Invalid option: ${OPTARG}" >&2 exit 1 ;; ":" ) echo "Invalid option: ${OPTARG} is missing an argument" >&2 exit 1 esac done shift $(($OPTIND - 1)) if [ "${version}" ] then tag="$(basename $(pwd)):${version}" else tag="$1" fi tag="landisdesign/${tag}" docker build ${cache} -t=${tag} . if [ "${push}" ] then docker push ${tag} fi }
Python
UTF-8
3,790
2.65625
3
[]
no_license
""" Tools to estimate the uncertainty of the COSMOS shear estimates """ import numpy as np import sys sys.path.append('../shear/') from read_shear_catalog import read_shear_catalog sys.path.append('../shear/param_estimation/') from tools import bootstrap_resample def bootstrap_catalog(catalog_file, N_bootstraps, dtheta, RAmin = None, DECmin = None, NRA = None, NDEC = None): """ Estimate shear uncertainty using a bootstrap resampling of shear data in the catalog. Parameters ---------- catalog_file : file of COSMOS shear catalog N_bootstraps : number of resamplings to use dtheta : pixel size in arcmin Other Parameters ---------------- If these are unspecified, they will be determined from the data RAmin : minimum of RA bins (degrees). NRA : number of RA bins DECmin : minimum of DEC bins (degrees) NDEC : number of DEC bins Returns ------- (Ngal, dgamma2) Ngal : array[int], shape = (NRA, NDEC) number of galaxies in each shear bin dgamma2 : array[float], shape = (NRA, NDEC) estimated squared shear error in each shear bin """ RA, DEC, gamma1, gamma2 = read_shear_catalog(catalog_file, ('Ra', 'Dec', 'e1iso_rot4_gr_snCal', 'e2iso_rot4_gr_snCal'), None) gamma = gamma1 - 1j*gamma2 if RAmin is None: RAmin = RA.min() if DECmin is None: DECmin = DEC.min() if NRA is None: NRA = int(np.ceil((RA.max() - RAmin + 1E-8) * 60. / dtheta)) if NDEC is None: NDEC = int(np.ceil((DEC.max() - DECmin + 1E-8) * 60. / dtheta)) return bootstrap_resample(gamma, RA, DEC, RAmin, dtheta/60., NRA, DECmin, dtheta/60., NDEC, N_bootstraps) if __name__ == '__main__': import pylab from params import BRIGHT_CAT_NPZ, FAINT_CAT_NPZ from time import time np.random.seed(0) N_bootstraps = 100 pixel_scale = 4 t0 = time() gamma_mean, Ngal, d2gamma, sigma = bootstrap_catalog( BRIGHT_CAT_NPZ, N_bootstraps, pixel_scale) print "time: %.2g sec" % (time()-t0) Ngal = Ngal.reshape(Ngal.size) d2gamma = d2gamma.reshape(d2gamma.size) pylab.figure() #plot noise versus number of galaxies pylab.subplot(211, yscale='log') x = np.linspace(2, max(Ngal), 100) y = sigma**2 / x pylab.plot(Ngal, d2gamma, '.k') pylab.plot(x,y,'-b') pylab.ylim(0.0001, 0.1) pylab.xlabel(r'${\rm n_{gal}/\mathrm{pixel}}$') pylab.ylabel(r'${\rm \sigma^2_\gamma}$') pylab.title("Results for %i bootstrap resamples (%i' pixels)" % (N_bootstraps, pixel_scale)) #plot sigma_int histogram pylab.subplot(212) sigma2 = Ngal * d2gamma sigma2 = sigma2[np.where(sigma2 > 0.05)] sigma = np.sqrt(sigma2) mu = sigma.mean() s2 = ((sigma - mu)**2).mean() s = np.sqrt(s2) xrange = np.linspace(mu - 5 * s, mu + 5 * s, 100) yrange = (2*np.pi*s2)**-0.5 * np.exp( -0.5 * (xrange-mu)**2 / s2 ) pylab.hist(sigma, 50, normed=True, histtype='stepfilled', alpha=0.5) pylab.plot(xrange, yrange, '-k') pylab.xlabel(r'${\rm \sigma_{int}}$') pylab.ylabel(r'${\rm dN/d\sigma_{int}}$') pylab.text(0.05, 0.95, r'$\mathrm{mean\ \sigma_{int}\ =\ %.2f \pm %.2f}$' % (mu, s), ha='left', va='top', transform = pylab.gca().transAxes, fontsize=16) pylab.savefig('fig/fig01_sigma_calc.pdf') pylab.show()
Java
UTF-8
1,028
1.8125
2
[]
no_license
/** * This class was generated by the VisualAge for Java Access Bean SmartGuide. * Warning: Modifications will be lost when this part is regenerated. */ package com.hps.july.persistence; public interface LeaseMRCntPriorAccessBeanData { public java.lang.Short getPriority() throws java.rmi.RemoteException, javax.ejb.CreateException, javax.ejb.FinderException, javax.naming.NamingException; public void setPriority( java.lang.Short newValue ); public com.hps.july.persistence.LeaseDocumentKey getContract1Key() throws java.rmi.RemoteException, javax.ejb.CreateException, javax.ejb.FinderException, javax.naming.NamingException; public com.hps.july.persistence.LeaseDocumentKey getContract2Key() throws java.rmi.RemoteException, javax.ejb.CreateException, javax.ejb.FinderException, javax.naming.NamingException; public com.hps.july.persistence.LeaseDocumentKey getReglamentKey() throws java.rmi.RemoteException, javax.ejb.CreateException, javax.ejb.FinderException, javax.naming.NamingException; }
Markdown
UTF-8
1,389
3.421875
3
[ "BSD-3-Clause" ]
permissive
--- title: databank.clip --- # `databank.clip` ^^(+databank)^^ {== Clip all time series in databank to a new range ==} ## Syntax outputDatabank = databank.clip(inputDatabank, newStart, newEnd) #### Input Arguments __`inputDatabank`__ [ struct | Dictionary ] > > Input databank whose time series (of the matching frequency) will be > clipped to a new range defined by `newStart` and `newEnd`. > __`newStart`__ [ Dater | `-Inf` ] > > A new start date to which all time series of the matching frequency will > be clipped; `-Inf` means the start date will not be altered. > __`newEnd`__ [ Dater | `Inf` ] > > A new end date to which all time series of the matching frequency will be > clipped; `Inf` means the end date will not be altered. > ## Output Arguments __`outputDatabank`__ [ struct | Dictionary ] - > > Output databank in which all time series (of the matching frequency) are > clipped to the new range. > ## Description ## Example Create a databank with time series of different frequencies. Clip the date range of all quarterly series.so that they all start in 2019Q1. ```matlab d = struct(); d.x1 = Series(qq(2015,1):qq(2030,4), @rand); d.x2 = Series(qq(2010,1):qq(2025,4), @rand); d.x3 = Series(mm(2012,01):qq(2025,12), @rand); d.x4 = Series(mm(2019,01):qq(2022,08), @rand); d.x5 = Series(1:100, @rand); d = databank.clip(d, qq(2019,1), Inf) ```
Ruby
UTF-8
465
3.796875
4
[]
no_license
string = "hello world" length = string.length i = 0 # j = 0 first_word = [] # while i < length do (my code) # while string[j] != ' ' # first_word << string[j] # j+=1 # end # i+=1 # end # Others code until string[i] == ' ' first_word << string[i] i += 1 end # first_word.each do |x| # puts "this letter is: " + x.class.to_s # end puts "please give me a number" number = gets new_number = 9 + number.to_i puts new_number
PHP
UTF-8
649
2.546875
3
[ "MIT" ]
permissive
<?php namespace InetStudio\BannersPackage\Groups\Events\Back; use Illuminate\Queue\SerializesModels; use InetStudio\BannersPackage\Groups\Contracts\Models\GroupModelContract; use InetStudio\BannersPackage\Groups\Contracts\Events\Back\ModifyItemEventContract; /** * Class ModifyItemEvent. */ class ModifyItemEvent implements ModifyItemEventContract { use SerializesModels; /** * @var GroupModelContract */ public $item; /** * ModifyItemEvent constructor. * * @param GroupModelContract $item */ public function __construct(GroupModelContract $item) { $this->item = $item; } }
Swift
UTF-8
3,385
3.328125
3
[ "ECL-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
// // Occupancy.swift // bm-persona // // Created by Shawn Huang on 4/17/20. // Copyright © 2020 RJ Pimentel. All rights reserved. // import UIKit enum OccupancyStatus { case high case medium case low func badge() -> TagView { let badge = TagView() badge.translatesAutoresizingMaskIntoConstraints = false badge.widthAnchor.constraint(equalToConstant: 50).isActive = true switch self { case OccupancyStatus.high: badge.text = "High" badge.backgroundColor = Color.highOccupancyTag case OccupancyStatus.medium: badge.text = "Medium" badge.backgroundColor = Color.medOccupancyTag case OccupancyStatus.low: badge.text = "Low" badge.backgroundColor = Color.lowOccupancyTag } return badge } } // Object containing occupancy data for a location based on day of week and hour of day. class Occupancy { // dictionary mapping day of week and hour of day to a percent occupancy var dailyOccupancy: [DayOfWeek: [Int: Int]] // percent occupancy for the current time var liveOccupancy: Int? // ranges for what percentage constitutes each status (high, medium, low) static let statusBounds: [OccupancyStatus: ClosedRange<Int>] = [OccupancyStatus.high: 70...100, OccupancyStatus.medium: 30...69, OccupancyStatus.low: 0...29] init(dailyOccupancy: [DayOfWeek: [Int: Int]], live: Int?) { self.dailyOccupancy = dailyOccupancy self.liveOccupancy = live } // get a percent occupancy for the current date, with live data taking priority func getCurrentOccupancyPercent() -> Int? { if let live = liveOccupancy { return live } return getHistoricOccupancyPercent(date: Date()) } // get a percent occupancy based on a date object (current day and time) func getHistoricOccupancyPercent(date: Date) -> Int? { let day = DayOfWeek.weekday(date) let hour = Calendar.current.component(.hour, from: date) if let forDay = dailyOccupancy[day] { return forDay[hour] ?? nil } return nil } // get a status (high, medium, low) for the current date, with live data taking priority func getCurrentOccupancyStatus() -> OccupancyStatus? { return occupancyStatusFrom(percent: getCurrentOccupancyPercent()) } // get a status (high, medium, low) based on a date object func getHistoricOccupancyStatus(date: Date) -> OccupancyStatus? { return occupancyStatusFrom(percent: getHistoricOccupancyPercent(date: date)) } private func occupancyStatusFrom(percent: Int?) -> OccupancyStatus? { if percent == nil { return nil } if Occupancy.statusBounds[OccupancyStatus.high]!.contains(percent!) { return OccupancyStatus.high } else if Occupancy.statusBounds[OccupancyStatus.medium]!.contains(percent!) { return OccupancyStatus.medium } else if Occupancy.statusBounds[OccupancyStatus.low]!.contains(percent!) { return OccupancyStatus.low } else { return nil } } // get occupancy dictionary for one day of the week func occupancy(for day: DayOfWeek) -> [Int: Int]? { return dailyOccupancy[day] } }
Python
UTF-8
658
3.796875
4
[]
no_license
"""rank=[1,2,3,4,5,6,7,8,9,10,11,12,13] suite=["h","s","d","c"] cards=list(zip(rank,suite)) #populate the card list card=[] for ranks in rank: cards=cards+[(ranks,suite[0]),(ranks,suite[1]),(ranks.suite[2])] print(cards) """ class card(): suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def __init__(self,rank=0,suite=2): self.rank=rank self.suite=suite def __str__(self): return f"the rankis {card.rank_names[self.rank]} and the suite is {card.suite_name[self.suite]}" ace_of_spades=cards(1,3) print(ace_of_spades)
Java
UTF-8
2,069
1.992188
2
[]
no_license
package com.timss.ptw.bean; import com.yudean.itc.annotation.UUIDGen; import com.yudean.itc.annotation.UUIDGen.GenerationType; import com.yudean.mvc.bean.ItcMvcBean; /** * ' * * @title: 标准操作票操作项bean * @description: {desc} * @company: gdyd * @className: SptoInfo.java * @author: gucw * @createDate: 2015年7月9日 * @updateUser: * @version: 1.0 */ public class PtoOperItem extends ItcMvcBean { /** * */ private static final long serialVersionUID = 8771815817638353987L; @UUIDGen(requireType = GenerationType.REQUIRED_NULL) private String id; private String ptoId; private Integer showOrder; private String content; private String hasOper; private String operTime; private String remarks; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPtoId() { return ptoId; } public void setPtoId(String ptoId) { this.ptoId = ptoId; } public String getHasOper() { return hasOper; } public void setHasOper(String hasOper) { this.hasOper = hasOper; } public String getOperTime() { return operTime; } public void setOperTime(String operTime) { this.operTime = operTime; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public Integer getShowOrder() { return showOrder; } public void setShowOrder(Integer showOrder) { this.showOrder = showOrder; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "PtoOperItem [id=" + id + ", ptoId=" + ptoId + ", showOrder=" + showOrder + ", content=" + content + ", hasOper=" + hasOper + ", operTime=" + operTime + ", remarks=" + remarks + "]"; } }
Python
UTF-8
723
2.515625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Created on Fri May 22 11:55:42 2020 @author: Reuben """ import unittest from npsolve import utils class Test_Util_Containers(unittest.TestCase): def test_get_dict(self): d = utils.get_dict('test') self.assertTrue(isinstance(d, dict)) self.assertTrue(d['a'] is None) def test_get_list(self): d = utils.get_list('test') self.assertTrue(isinstance(d, list)) def test_get_set(self): d = utils.get_set('test') self.assertTrue(isinstance(d, set)) def test_get_list_containert(self): d = utils.get_list_container('test') lst = d['a'] self.assertTrue(isinstance(lst, list))
C++
UTF-8
2,857
3.21875
3
[]
no_license
#include <vector> /** * This function splits the input sequence or set into one or more equivalence classes and * returns the vector of labels - 0-based class indexes for each element. * predicate(a,b) returns true if the two sequence elements certainly belong to the same class. * * The algorithm is described in "Introduction to Algorithms" * by Cormen, Leiserson and Rivest, the chapter "Data structures for disjoint sets" */ template<typename _Tp, class _EqPredicate> int partition( const vector<_Tp>& _vec, vector<int>& labels, _EqPredicate predicate=_EqPredicate()) { int i, j, N = (int)_vec.size(); const _Tp* vec = &_vec[0]; const int PARENT=0; const int RANK=1; vector<int> _nodes(N*2); int (*nodes)[2] = (int(*)[2])&_nodes[0]; // The first O(N) pass: create N single-vertex trees for(i = 0; i < N; i++) { nodes[i][PARENT]=-1; nodes[i][RANK] = 0; } // The main O(N^2) pass: merge connected components for( i = 0; i < N; i++ ) { int root = i; // find root while( nodes[root][PARENT] >= 0 ) root = nodes[root][PARENT]; for( j = 0; j < N; j++ ) { if( i == j || !predicate(vec[i], vec[j])) continue; int root2 = j; while( nodes[root2][PARENT] >= 0 ) root2 = nodes[root2][PARENT]; if( root2 != root ) { // unite both trees int rank = nodes[root][RANK], rank2 = nodes[root2][RANK]; if( rank > rank2 ) nodes[root2][PARENT] = root; else { nodes[root][PARENT] = root2; nodes[root2][RANK] += rank == rank2; root = root2; } assert( nodes[root][PARENT] < 0 ); int k = j, parent; // compress the path from node2 to root while( (parent = nodes[k][PARENT]) >= 0 ) { nodes[k][PARENT] = root; k = parent; } // compress the path from node to root k = i; while( (parent = nodes[k][PARENT]) >= 0 ) { nodes[k][PARENT] = root; k = parent; } } } } // Final O(N) pass: enumerate classes labels.resize(N); int nclasses = 0; for( i = 0; i < N; i++ ) { int root = i; while( nodes[root][PARENT] >= 0 ) root = nodes[root][PARENT]; // re-use the rank as the class label if( nodes[root][RANK] >= 0 ) nodes[root][RANK] = ~nclasses++; labels[i] = ~nodes[root][RANK]; } return nclasses; }
C
UTF-8
6,805
2.875
3
[]
no_license
/* * Para compilar: mpicc stringWord_OMPI.c -o stringWord_OMPI -Wall * Para rodar: mpirun -np 10 stringWord_OMPI ../input/shakespe.txt * No cluster: time mpirun -np 10 -machinefile machinefile.xmen stringWord_OMPI ../input/shakespe.txt */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <mpi.h> #define FOLGA 10 /* Estrutura usada para armazenar resultados parciais */ typedef struct { int contS; int contW; double tS; double tW; } PartialResult; /* Protótipos das funções */ char *strRev(char *); int chkPal(char *, double *); void strUpper(char *); int main(int argc, char *argv[]) { int curr_rank, num_procs, rc, dest=1, tag, block_size; int contW_total = 0, contS_total = 0; int i, namelen; char processor_name[MPI_MAX_PROCESSOR_NAME]; char *message, *message2, *endPToken, *endWToken; char *pch; FILE *fpin; long lSize; MPI_Status status; double t_aux, t_totalS=0.0, t_totalW=0.0; int count = 4; int lengths[4] = {1, 1, 1, 1}; MPI_Datatype prDatatype; PartialResult pr; /* Inicializa e sincroniza MPI para o processo atual */ rc = MPI_Init(&argc, &argv); if (rc != MPI_SUCCESS) { printf("Problema ao iniciar processo MPI.\n"); return -1; } /* Definição da struct PartialResult */ MPI_Aint offsets[4] = {0, sizeof(int), sizeof(int) + sizeof(int), sizeof(int) + sizeof(int) + sizeof(double)}; MPI_Datatype types[4] = {MPI_INT, MPI_INT, MPI_DOUBLE, MPI_DOUBLE}; MPI_Type_struct(count, lengths, offsets, types, &prDatatype); MPI_Type_commit(&prDatatype); /* Pega id do processo atual */ MPI_Comm_rank(MPI_COMM_WORLD, &curr_rank); /* Pega o número de processos do grupo */ MPI_Comm_size(MPI_COMM_WORLD, &num_procs); /* Pega o nome do nó que está executando o processo */ MPI_Get_processor_name(processor_name, &namelen); //printf("Nome do processador: %s | rank: %d\n", processor_name, curr_rank); if (curr_rank == 0) { /* Abre o arquivo que será processado */ if ((fpin = fopen(argv[1], "r")) == NULL) { printf("Problema no arquivo.\n"); MPI_Finalize(); return -1; } /* Obtém o tamanho aproximado do arquivo em bytes */ fseek(fpin, 0, SEEK_END); lSize = ftell(fpin); rewind(fpin); /* Inicializa os blocos que serão divididos entre os nós */ if (num_procs == 1) { MPI_Finalize(); return -1; } else if (num_procs == 2) { /* Dada a imprecisão de lSize, coloca-se uma folga de 10 bytes */ block_size = lSize + FOLGA; } else block_size = lSize / (num_procs-1) + FOLGA; printf("Nro de processos: %d\nTam. total do arquivo: %ld\n" "Tam. bloco: %d\n", num_procs, lSize, block_size); /* Aloca memória para o bloco que será lido */ pch = (char *) malloc(block_size * sizeof(char)); while (!feof(fpin)) { /* Faz leitura sequencial de blocos com tamanho definido acima */ fread(pch, 1, block_size, fpin); /* Envia o tamanho do bloco que será processado para o nó * correspondente */ tag = dest; MPI_Send(&block_size, 1, MPI_INT, dest, tag, MPI_COMM_WORLD); /* Envia o bloco lido acima */ tag = dest+1; MPI_Send(pch, block_size, MPI_CHAR, dest, tag, MPI_COMM_WORLD); dest++; } /* Faz chamada Recieve para todos os subprocessos de forma bloqueante */ for (i=1; i<num_procs; i++) { tag = 2; MPI_Recv(&pr, 1, prDatatype, i, i+tag, MPI_COMM_WORLD, &status); /* Incrementa resultados parciais */ contS_total += pr.contS; contW_total += pr.contW; t_totalS += pr.tS; t_totalW += pr.tW; } /* Exibe resultado dos cálculos */ printf("Quantidade de palindromos de palavras: %d\n" "Quantidade de palindromos de frases: %d\n" "Tempo para calculo dos palindromos: \n\t" "-> palavras: %lf\n\t" "-> frases: %lf\n", contW_total, contS_total, t_totalW, t_totalS); } else { /* Recebe do processo root, o tamanho do bloco */ tag = curr_rank; MPI_Recv(&block_size, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status); /* Aloca memória de acordo com o tamanho definido acima */ pch = (char *) malloc(block_size * sizeof(char)); /* Recebe do processo root, o bloco com tamanho já definido */ tag = curr_rank+1; MPI_Recv(pch, block_size, MPI_CHAR, 0, tag, MPI_COMM_WORLD, &status); /* Inicializa variáveis que armazenam os resultados parciais */ pr.contS = pr.contW = 0; pr.tS = pr.tW = 0.0; /* Início do parsing e chamadas da função que irá verificar se é * palindromo. A função strtok_r foi usada para evitar que se perca * a referencia do ultimo token encontrado. Esse problema aparece * em chamadas aninhadas de strtok() */ message = strtok_r(pch, ".\t\n\r", &endPToken); while (message != NULL) { /* chkPal é chamado para calcular o palindromo do token message. * Retorna o tempo gasto para o cálculo na variável t_aux */ if (chkPal(message, &t_aux)) { (pr.contS)++; pr.tS += t_aux; } /* Chamada aninhada de strtok_r para calcular palindromo de * palavra */ message2 = strtok_r(message, " ,/?'\";:|^-!$#@`~*&%)(+=_}{][\\", &endWToken); while (message2 != NULL) { /* chkPal é chamado para calcular o palindromo do token message. * Retorna o tempo gasto para o cálculo na variável t_aux */ if (chkPal(message2, &t_aux)) { (pr.contW)++; pr.tW += t_aux; } message2 = strtok_r(NULL, " ,/?'\";:|^-!$#@`~*&%)(+=_}{][\\", &endWToken); } message = strtok_r(NULL, ".\t\n\r", &endPToken); } /* Envia o resultado parcial para o processo root */ tag = 2; MPI_Send(&pr, 1, prDatatype, 0, tag+curr_rank, MPI_COMM_WORLD); free(pch); } /* Finaliza e libera memória do processo MPI */ MPI_Finalize(); return 0; } /* Reverte string */ char *strRev(char *str) { char *p1, *p2; if (! str || ! *str) return str; for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) { *p1 ^= *p2; *p2 ^= *p1; *p1 ^= *p2; } return str; } /* Função que verifica palindromos */ int chkPal(char *str, double *t) { char aux[1000]; double t1, t2; /* Registra a marca de tempo t1 antes de iniciar os cálculos */ t1 = MPI_Wtime(); if (strlen(str) > 1) { strUpper(str); strcpy(aux,str); strRev(aux); if (strcmp(str,aux) == 0) { /* Registra a marca de tempo t2 depois de terminar os cálculos */ t2 = MPI_Wtime(); *t = t2 - t1; return 1; } else { /* Registra a marca de tempo t2 depois de terminar os cálculos */ t2 = MPI_Wtime(); *t = t2 - t1; return 0; } } else { /* Registra a marca de tempo t2 depois de terminar os cálculos */ t2 = MPI_Wtime(); *t = t2 - t1; return 0; } } /* Transforma string para apenas letras maiusculas */ void strUpper(char *str) { int i; for (i=0;i<strlen(str);i++) str[i] = toupper(str[i]); }
C#
UTF-8
15,433
2.5625
3
[]
no_license
using System.Collections.Generic; using SecureDataCleanerLibrary; using SecureDataCleanerLibrary.Models; using SecureDataCleanerLibrary.Models.Enums; using Xunit; namespace SecureDataCleanerLibraryTests { public class HttpHandlerTests { [Fact] public void HttpHandler_Process_BookingcomHttpResult_ClearSecureData() { // Arrange var bookingcomHttpResult = new HttpResult { Url = "http://test.com/users/max/info?pass=123456", RequestBody = "http://test.com?user=max&pass=123456", ResponseBody = "http://test.com?user=max&pass=123456" }; var httpHandler = new HttpHandler(); var dataLocationQuery = new HashSet<string> { SecureDataLocation.UrlQuery }; var dataLocationRest = new HashSet<string> { SecureDataLocation.UrlRest }; var secureKeyUser = "user"; var locationsInfo1 = new Dictionary<PropertyType, HashSet<string>>(); locationsInfo1.Add(PropertyType.RequestBody, dataLocationQuery); locationsInfo1.Add(PropertyType.ResponseBody, dataLocationQuery); var secureDataInfo1 = new SecureDataInfo { SecureKey = secureKeyUser, LocationsInfo = locationsInfo1 }; var secureKeyPass = "pass"; var locationsInfo2 = new Dictionary<PropertyType, HashSet<string>>(); locationsInfo2.Add(PropertyType.Url, dataLocationQuery); locationsInfo2.Add(PropertyType.RequestBody, dataLocationQuery); locationsInfo2.Add(PropertyType.ResponseBody, dataLocationQuery); var secureDataInfo2 = new SecureDataInfo { SecureKey = secureKeyPass, LocationsInfo = locationsInfo2 }; var secureKey3 = "users"; var locationsInfo3 = new Dictionary<PropertyType, HashSet<string>>(); locationsInfo3.Add(PropertyType.Url, dataLocationRest); var secureDataInfo3 = new SecureDataInfo { SecureKey = secureKey3, LocationsInfo = locationsInfo3 }; var secureDataInfoList = new List<SecureDataInfo>(); secureDataInfoList.Add(secureDataInfo1); secureDataInfoList.Add(secureDataInfo2); secureDataInfoList.Add(secureDataInfo3); // Act httpHandler.Process(bookingcomHttpResult.Url, bookingcomHttpResult.RequestBody, bookingcomHttpResult.ResponseBody, secureDataInfoList); // Assert Assert.Equal("http://test.com/users/XXX/info?pass=XXXXXX", httpHandler.CurrentLog.Url); Assert.Equal("http://test.com?user=XXX&pass=XXXXXX", httpHandler.CurrentLog.RequestBody); Assert.Equal("http://test.com?user=XXX&pass=XXXXXX", httpHandler.CurrentLog.ResponseBody); } [Fact] public void HttpHandler_Process_YandexHttpResult_ClearSecureData() { // Arrange var yandexHttpResult = new HttpResult { Url = "http://test.com?user=max&pass=123456", RequestBody = "<auth><user>max</user><pass>123456</pass></auth>", ResponseBody = "<auth user=\"max\" pass=\"123456\"/>" }; var httpHandler = new HttpHandler(); var dataLocationQuery = new HashSet<string> { SecureDataLocation.UrlQuery }; var dataLocationAttribute = new HashSet<string> { SecureDataLocation.XmlAttribute }; var dataLocationElement = new HashSet<string> { SecureDataLocation.XmlElementValue }; var secureKeyUser = "user"; var locationsInfo = new Dictionary<PropertyType, HashSet<string>> { { PropertyType.Url, dataLocationQuery }, { PropertyType.RequestBody, dataLocationElement }, { PropertyType.ResponseBody, dataLocationAttribute } }; var secureDataInfo1 = new SecureDataInfo { SecureKey = secureKeyUser, LocationsInfo = locationsInfo }; var secureKeyPass = "pass"; var secureDataInfo2 = new SecureDataInfo { SecureKey = secureKeyPass, LocationsInfo = locationsInfo }; var secureDataInfoList = new List<SecureDataInfo> { secureDataInfo1, secureDataInfo2 }; // Act httpHandler.Process(yandexHttpResult.Url, yandexHttpResult.RequestBody, yandexHttpResult.ResponseBody, secureDataInfoList); // Assert Assert.Equal("http://test.com?user=XXX&pass=XXXXXX", httpHandler.CurrentLog.Url); Assert.Equal("<auth><user>XXX</user><pass>XXXXXX</pass></auth>", httpHandler.CurrentLog.RequestBody); Assert.Equal("<auth user=\"XXX\" pass=\"XXXXXX\" />", httpHandler.CurrentLog.ResponseBody); } [Fact] public void HttpHandler_Process_OstrovokHttpResult_ClearSecureData() { // Arrange var ostrovokHttpResult = new HttpResult { Url = "http://test.com/users/max/info", RequestBody = "{user:\"max\",pass:\"123456\"}", ResponseBody = "{user:{value:\"max\"},pass:{value:\"123456\"}}" }; var httpHandler = new HttpHandler(); var dataLocationRest = new HashSet<string> { SecureDataLocation.UrlRest }; var dataLocationAttribute = new HashSet<string> { SecureDataLocation.JsonAttribute }; var dataLocationElement = new HashSet<string> { SecureDataLocation.JsonElementValue }; var secureKeyUsers = "users"; var locationsInfo1 = new Dictionary<PropertyType, HashSet<string>>(); locationsInfo1.Add( PropertyType.Url, dataLocationRest ); var secureDataInfo1 = new SecureDataInfo { SecureKey = secureKeyUsers, LocationsInfo = locationsInfo1 }; var secureKeyPass = "pass"; var locationsInfo2 = new Dictionary<PropertyType, HashSet<string>> { { PropertyType.RequestBody, dataLocationElement }, { PropertyType.ResponseBody, dataLocationAttribute } }; var secureDataInfo2 = new SecureDataInfo { SecureKey = secureKeyPass, LocationsInfo = locationsInfo2 }; var secureKeyUser = "user"; var secureDataInfo3 = new SecureDataInfo { SecureKey = secureKeyUser, LocationsInfo = locationsInfo2 }; var secureDataInfoList = new List<SecureDataInfo> { secureDataInfo1, secureDataInfo2, secureDataInfo3 }; // Act httpHandler.Process(ostrovokHttpResult.Url, ostrovokHttpResult.RequestBody, ostrovokHttpResult.ResponseBody, secureDataInfoList); // Assert Assert.Equal("http://test.com/users/XXX/info", httpHandler.CurrentLog.Url); Assert.Equal("{\"user\":\"XXX\",\"pass\":\"XXXXXX\"}", httpHandler.CurrentLog.RequestBody); Assert.Equal("{\"user\":{\"value\":\"XXX\"},\"pass\":{\"value\":\"XXXXXX\"}}", httpHandler.CurrentLog.ResponseBody); } [Fact] public void HttpHandler_Process_AgodaHttpResult_ClearSecureData() { // Arrange var agodaHttpResult = new HttpResult { Url = "http://test.com?user=max&pass=123456", RequestBody = @" <auth> <user>max</user> <pass>123456</pass> </auth>", ResponseBody = "<auth user='max' pass='123456'/>" }; var httpHandler = new HttpHandler(); var dataLocationQuery = new HashSet<string> { SecureDataLocation.UrlQuery }; var dataLocationAttribute = new HashSet<string> { SecureDataLocation.XmlAttribute }; var dataLocationElement = new HashSet<string> { SecureDataLocation.XmlElementValue }; var secureKeyUser = "user"; var locationsInfo = new Dictionary<PropertyType, HashSet<string>> { { PropertyType.Url, dataLocationQuery }, { PropertyType.RequestBody, dataLocationElement }, { PropertyType.ResponseBody, dataLocationAttribute } }; var secureDataInfo1 = new SecureDataInfo { SecureKey = secureKeyUser, LocationsInfo = locationsInfo }; var secureKeyPass = "pass"; var secureDataInfo2 = new SecureDataInfo { SecureKey = secureKeyPass, LocationsInfo = locationsInfo }; var secureDataInfoList = new List<SecureDataInfo>(); secureDataInfoList.Add(secureDataInfo1); secureDataInfoList.Add(secureDataInfo2); // Act httpHandler.Process(agodaHttpResult.Url, agodaHttpResult.RequestBody, agodaHttpResult.ResponseBody, secureDataInfoList); // Assert Assert.Equal("http://test.com?user=XXX&pass=XXXXXX", httpHandler.CurrentLog.Url); Assert.Equal("<auth><user>XXX</user><pass>XXXXXX</pass></auth>", httpHandler.CurrentLog.RequestBody); Assert.Equal("<auth user=\"XXX\" pass=\"XXXXXX\" />", httpHandler.CurrentLog.ResponseBody); } [Fact] public void HttpHandler_Process_GoogleHttpResult_ClearSecureData() { // Arrange var googleHttpResult = new HttpResult { Url = "http://test.com?user=max&pass=123456", RequestBody = @" <auth user=""max""> <pass>123456</pass> </auth>", ResponseBody = @" <auth pass=""123456""> <user>max</user> </auth>" }; var httpHandler = new HttpHandler(); var dataLocationQuery = new HashSet<string> { SecureDataLocation.UrlQuery }; var dataLocationAttribute = new HashSet<string> { SecureDataLocation.XmlAttribute }; var dataLocationElement = new HashSet<string> { SecureDataLocation.XmlElementValue }; var secureKeyUser = "user"; var locationsInfo1 = new Dictionary<PropertyType, HashSet<string>> { { PropertyType.Url, dataLocationQuery }, { PropertyType.RequestBody, dataLocationAttribute }, { PropertyType.ResponseBody, dataLocationElement } }; var secureDataInfo1 = new SecureDataInfo { SecureKey = secureKeyUser, LocationsInfo = locationsInfo1 }; var secureKeyPass = "pass"; var locationsInfo2 = new Dictionary<PropertyType, HashSet<string>> { { PropertyType.Url, dataLocationQuery }, { PropertyType.RequestBody, dataLocationElement }, { PropertyType.ResponseBody, dataLocationAttribute } }; var secureDataInfo2 = new SecureDataInfo { SecureKey = secureKeyPass, LocationsInfo = locationsInfo2 }; var secureDataInfoList = new List<SecureDataInfo> { secureDataInfo1, secureDataInfo2 }; // Act httpHandler.Process(googleHttpResult.Url, googleHttpResult.RequestBody, googleHttpResult.ResponseBody, secureDataInfoList); // Assert Assert.Equal("http://test.com?user=XXX&pass=XXXXXX", httpHandler.CurrentLog.Url); Assert.Equal("<auth user=\"XXX\"><pass>XXXXXX</pass></auth>", httpHandler.CurrentLog.RequestBody); Assert.Equal("<auth pass=\"XXXXXX\"><user>XXX</user></auth>", httpHandler.CurrentLog.ResponseBody); } [Fact] public void HttpHandler_Process_ExpediaHttpResult_ClearSecureData() { // Arrange var expediaHttpResult = new HttpResult { Url = "http://test.com/users/max/info", RequestBody = @" { user: 'max', pass: '123456' }", ResponseBody = @" { user: { value: 'max' }, pass: { value: '123456' } }" }; var httpHandler = new HttpHandler(); var dataLocationRest = new HashSet<string> { SecureDataLocation.UrlRest }; var dataLocationAttribute = new HashSet<string> { SecureDataLocation.JsonAttribute }; var dataLocationElement = new HashSet<string> { SecureDataLocation.JsonElementValue }; var secureKeyUsers = "users"; var locationsInfo1 = new Dictionary<PropertyType, HashSet<string>> { { PropertyType.Url, dataLocationRest }, }; var secureDataInfo1 = new SecureDataInfo { SecureKey = secureKeyUsers, LocationsInfo = locationsInfo1 }; var secureKeyPass = "pass"; var locationsInfo2 = new Dictionary<PropertyType, HashSet<string>> { { PropertyType.Url, dataLocationRest }, { PropertyType.RequestBody, dataLocationElement }, { PropertyType.ResponseBody, dataLocationAttribute } }; var secureDataInfo2 = new SecureDataInfo { SecureKey = secureKeyPass, LocationsInfo = locationsInfo2 }; var secureKeyUser = "user"; var secureDataInfo3 = new SecureDataInfo { SecureKey = secureKeyUser, LocationsInfo = locationsInfo2 }; var secureDataInfoList = new List<SecureDataInfo> { secureDataInfo1, secureDataInfo2, secureDataInfo3 }; // Act httpHandler.Process(expediaHttpResult.Url, expediaHttpResult.RequestBody, expediaHttpResult.ResponseBody, secureDataInfoList); // Assert Assert.Equal("http://test.com/users/XXX/info", httpHandler.CurrentLog.Url); Assert.Equal("{\"user\":\"XXX\",\"pass\":\"XXXXXX\"}", httpHandler.CurrentLog.RequestBody); Assert.Equal("{\"user\":{\"value\":\"XXX\"},\"pass\":{\"value\":\"XXXXXX\"}}", httpHandler.CurrentLog.ResponseBody); } } }
Java
UTF-8
350
1.804688
2
[ "MIT" ]
permissive
package com.wyt.labinformationmanagementsystem.model.db; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.Accessors; @Data @ToString @NoArgsConstructor @Accessors(chain = true) public class Admin { private Integer admId; private String admUsername; private String admPassword; }
Java
UTF-8
2,397
2.21875
2
[]
no_license
package com.gradezilla.dao.entity; // Generated Oct 6, 2015 7:42:06 PM by Hibernate Tools 3.2.2.GA import java.util.HashSet; import java.util.Set; import javax.persistence.*; /** * Role generated by hbm2java */ @Entity @Table(name="Role" ,schema="dbo" ,catalog="SchoolApp" ) public class Role implements java.io.Serializable { private int roleId; private String roleName; private String roleDescription; private Set<UserRole> userRoles = new HashSet<UserRole>(0); private Set<UserRole> userRoles_1 = new HashSet<UserRole>(0); public Role() { } public Role(int roleId, String roleName, String roleDescription) { this.roleId = roleId; this.roleName = roleName; this.roleDescription = roleDescription; } public Role(int roleId, String roleName, String roleDescription, Set<UserRole> userRoles, Set<UserRole> userRoles_1) { this.roleId = roleId; this.roleName = roleName; this.roleDescription = roleDescription; this.userRoles = userRoles; this.userRoles_1 = userRoles_1; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="roleId", unique=true, nullable=false) public int getRoleId() { return this.roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } @Column(name="roleName", nullable=false, length=50) public String getRoleName() { return this.roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } @Column(name="roleDescription", nullable=false, length=50) public String getRoleDescription() { return this.roleDescription; } public void setRoleDescription(String roleDescription) { this.roleDescription = roleDescription; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="role") public Set<UserRole> getUserRoles() { return this.userRoles; } public void setUserRoles(Set<UserRole> userRoles) { this.userRoles = userRoles; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="role") public Set<UserRole> getUserRoles_1() { return this.userRoles_1; } public void setUserRoles_1(Set<UserRole> userRoles_1) { this.userRoles_1 = userRoles_1; } }
Markdown
UTF-8
2,206
4.0625
4
[]
no_license
# two-sum-ii-input-array-is-sorted [https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) ``` Given an array of integers that is already sorted in ascending order, 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. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Example: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. ``` # thinking 这个和[[Easy]2sum](https://github.com/xuwenzhi/leetcode/blob/master/array/2sum.md)一个味道,解决方案如果不考虑排序其实是一样的,不过那既然已经排序了,解决方案肯定会和**2 pointer**有关了. # solution (ruby) ```ruby // O(logN) Runtime O(1) Space # @param {Integer[]} numbers # @param {Integer} target # @return {Integer[]} def two_sum(numbers, target) low = 0; high = numbers.length - 1; while (low < high) if (numbers[low] + numbers[high] == target) return [low + 1, high + 1] elsif (numbers[low] + numbers[high] < target) low = low + 1 else high = high - 1 end end end ``` # solution (c++) ```c++ // O(logN) Runtime O(1) Space class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int low=0, high = numbers.size()-1; while (low < high) { int mid = low + (high - low) / 2; int sum = numbers[low] + numbers[high]; if (sum == target) { return {low+1, high+1}; } else if(sum < target) { low ++; } else { high --; } } return {}; } }; //Runtime: 8 ms, faster than 99.20% of C++ online submissions for Two Sum II - Input array is sorted. //Memory Usage: 9.6 MB, less than 37.56% of C++ online submissions for Two Sum II - Input array is sorted. ```
C++
UTF-8
596
3.140625
3
[]
no_license
#pragma once #include <chrono> class Timer final { private: Timer() : delta_time_ms(0.0f) { Initialize(); }; ~Timer() = default; public: static Timer* Get() { static Timer instance; return &instance; } const bool Initialize() { previous_time = std::chrono::high_resolution_clock::now(); return true; } const float GetDeltaTimeMs() { return static_cast<float>(delta_time_ms); } const float GetDeltaTimeSec() { return static_cast<float>(delta_time_ms * 0.001f); } void Update(); private: double delta_time_ms; std::chrono::high_resolution_clock::time_point previous_time; };
Java
UTF-8
5,998
1.664063
2
[]
no_license
package com.ailk.openbilling.persistence.imsxdr.entity; import javax.persistence.Entity; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessType; import com.ailk.easyframe.web.common.annotation.Sdl; import com.ailk.easyframe.sdl.sdlbuffer.CsdlStructObject; import com.ailk.easyframe.sdl.sdlbuffer.MemberTypeInfo; import javax.xml.bind.annotation.XmlTransient; import com.google.gson.annotations.Expose; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import com.ailk.easyframe.web.common.dal.IComplexEntity; import java.util.List; import jef.codegen.support.NotModified; /** * This class is generated automatically by Asiainfo-Linkage EasyFrame. * */ @NotModified @Entity @XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder={"productId","priceId","ratingItemId","ratingValue","validDateTime","expireDateTime"}) @Sdl(module="MXdr") public class SAddupResUsingVal extends CsdlStructObject implements IComplexEntity{ public final static String COL_PRODUCT_ID = "PRODUCT_ID"; public final static String COL_PRICE_ID = "PRICE_ID"; public final static String COL_RATING_ITEM_ID = "RATING_ITEM_ID"; public final static String COL_RATING_VALUE = "RATING_VALUE"; public final static String COL_VALID_DATE_TIME = "VALID_DATE_TIME"; public final static String COL_EXPIRE_DATE_TIME = "EXPIRE_DATE_TIME"; public final static int IDX_PRODUCT_ID = 0; public final static int IDX_PRICE_ID = 1; public final static int IDX_RATING_ITEM_ID = 2; public final static int IDX_RATING_VALUE = 3; public final static int IDX_VALID_DATE_TIME = 4; public final static int IDX_EXPIRE_DATE_TIME = 5; /** * */ @XmlElement(name="productId") @Sdl private long productId; /** * */ @XmlElement(name="priceId") @Sdl private int priceId; /** * */ @XmlElement(name="ratingItemId") @Sdl private long ratingItemId; /** * */ @XmlElement(name="ratingValue") @Sdl private long ratingValue; /** * */ @XmlElement(name="validDateTime") @Sdl private long validDateTime; /** * */ @XmlElement(name="expireDateTime") @Sdl private long expireDateTime; public void setProductId(long obj){ this.productId = obj; onFieldSet(0, obj); } public long getProductId(){ return productId; } public void setPriceId(int obj){ this.priceId = obj; onFieldSet(1, obj); } public int getPriceId(){ return priceId; } public void setRatingItemId(long obj){ this.ratingItemId = obj; onFieldSet(2, obj); } public long getRatingItemId(){ return ratingItemId; } public void setRatingValue(long obj){ this.ratingValue = obj; onFieldSet(3, obj); } public long getRatingValue(){ return ratingValue; } public void setValidDateTime(long obj){ this.validDateTime = obj; onFieldSet(4, obj); } public long getValidDateTime(){ return validDateTime; } public void setExpireDateTime(long obj){ this.expireDateTime = obj; onFieldSet(5, obj); } public long getExpireDateTime(){ return expireDateTime; } public List<MemberTypeInfo> getMemberInfoList(){ return memberTypeInfoList; } public SAddupResUsingVal(){ m_llMarkers = new long[1]; // used marker m_llUsedMarkers = new long[1]; // used marker fieldNum = 6; markerNum = 1; } /** * 创建copy方法 */ public SAddupResUsingVal(SAddupResUsingVal arg0){ copy(arg0); } public void copy(final SAddupResUsingVal rhs){ if (rhs == null)return; this.m_llMarker = rhs.m_llMarker; this.m_llUsedMarker = rhs.m_llUsedMarker; this.fieldNum = rhs.fieldNum; this.markerNum = rhs.markerNum; for (int i = 0; i < markerNum; i++) { m_llMarkers[i] = rhs.m_llMarkers[i]; m_llUsedMarkers[i] = rhs.m_llUsedMarkers[i]; } productId = rhs.productId; priceId = rhs.priceId; ratingItemId = rhs.ratingItemId; ratingValue = rhs.ratingValue; validDateTime = rhs.validDateTime; expireDateTime = rhs.expireDateTime; } public boolean equals(final Object rhs0){ if (rhs0 == null)return false; SAddupResUsingVal rhs=(SAddupResUsingVal)rhs0; if(!ObjectUtils.equals(productId, rhs.productId)) return false; if(!ObjectUtils.equals(priceId, rhs.priceId)) return false; if(!ObjectUtils.equals(ratingItemId, rhs.ratingItemId)) return false; if(!ObjectUtils.equals(ratingValue, rhs.ratingValue)) return false; if(!ObjectUtils.equals(validDateTime, rhs.validDateTime)) return false; if(!ObjectUtils.equals(expireDateTime, rhs.expireDateTime)) return false; return true; } public int hashCode(){ return new HashCodeBuilder() .append(productId) .append(priceId) .append(ratingItemId) .append(ratingValue) .append(validDateTime) .append(expireDateTime) .toHashCode(); } protected static java.util.List<MemberTypeInfo> memberTypeInfoList = new java.util.ArrayList<MemberTypeInfo>(6); public static final long BITS_ALL_MARKER = 0x20L; public static final long BITS_NOT_NULL_MARKER = 0x0L; public static final String SZ_TYPE_NAME = "com.ailk.openbilling.persistence.imsxdr.entity.SAddupResUsingVal"; @XmlTransient @Expose(deserialize = false, serialize = false) protected long m_llMarker = 0l; // null marker @XmlTransient @Expose(deserialize = false, serialize = false) protected long m_llUsedMarker = 0l; // used marker static{ memberTypeInfoList.add(MemberTypeInfo.get(SAddupResUsingVal.class, "PRODUCT_ID", 0, long.class)); memberTypeInfoList.add(MemberTypeInfo.get(SAddupResUsingVal.class, "PRICE_ID", 1, int.class)); memberTypeInfoList.add(MemberTypeInfo.get(SAddupResUsingVal.class, "RATING_ITEM_ID", 2, long.class)); memberTypeInfoList.add(MemberTypeInfo.get(SAddupResUsingVal.class, "RATING_VALUE", 3, long.class)); memberTypeInfoList.add(MemberTypeInfo.get(SAddupResUsingVal.class, "VALID_DATE_TIME", 4, long.class)); memberTypeInfoList.add(MemberTypeInfo.get(SAddupResUsingVal.class, "EXPIRE_DATE_TIME", 5, long.class)); } }
C#
UTF-8
1,226
2.75
3
[]
no_license
using System.Collections.Generic; using System.Linq; using ColorSoft.Web.Data; using ColorSoft.Web.Data.Models; namespace ColorSoft.Web.Queries.Users { public class GetUserByUsernameQuery : IGetUserByUsernameQuery { private readonly IDatabaseProvider _connection; public GetUserByUsernameQuery(IDatabaseProvider connection) { _connection = connection; } #region IGetUserByUsernameQuery Members public User Execute(string userName, bool includeRoles = false) { User user = _connection.Db().Users.FindAllByUserName(userName).FirstOrDefault(); if(user != null && includeRoles) { IEnumerable<UserRole> usersRoles = _connection.Db().UsersRoles.FindAllByUserId(user.Id); if(usersRoles.Any()) { IEnumerable<Role> roles = _connection.Db().Roles.FindAllById(usersRoles.Select(ur => ur.RoleId)); if(roles.Any()) { user.Roles = roles.Select(r => r.Name).ToList(); } } } return user; } #endregion } }
Python
UTF-8
964
3.25
3
[]
no_license
begin_y = 25.8 end_y = 6 begin_x = 14.1 end_x = 22.8 def convert_coord(degree, convert): #converted = degree + ((convert * 16.67) / 1000) converted = (convert * 16.67) / 1000 return converted converted_begin_y = convert_coord(17, begin_y) converted_end_y = convert_coord(17, end_y) converted_begin_x = convert_coord(47, begin_x) converted_end_x = convert_coord(47, end_x) length = converted_begin_y - converted_end_y width = converted_end_x - converted_begin_x def distance_convert(length): converted = length * 1.85 return converted converted_length = distance_convert(length) section_length = converted_length / 694 converted_width = distance_convert(width) print("x1 y1 {} {}" .format(converted_begin_x, converted_begin_y)) print("x2 y2 {} {}" .format(converted_end_x, converted_end_y)) print(converted_begin_y) print(converted_end_y) print(length) print(width) print(converted_length) print(section_length) print(converted_width)
C#
UTF-8
728
2.890625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Timer : MonoBehaviour { public double initialTime; private double restTime { get; set; } // Start is called before the first frame update void Start() { restTime = initialTime; } void initialize() { } // Update is called once per frame void Update() { restTime -= Time.deltaTime; //Debug.Log("timer: " + restTime + " seconds"); } public void increase(float seconds) { restTime += seconds; } public void decrease(float seconds) { restTime -= seconds; } public double RestTime { get { return restTime; } } }
PHP
UTF-8
5,565
2.546875
3
[]
no_license
<?php namespace Krixon\SamlClient\Login; use Krixon\SamlClient\Exception\InvalidRelayState; use Krixon\SamlClient\Protocol\Binding; use Krixon\SamlClient\Protocol\Instant; use Krixon\SamlClient\Protocol\NameIdPolicy; use Krixon\SamlClient\Protocol\RequestedAuthnContext; use Krixon\SamlClient\Protocol\RequestId; use Krixon\SamlClient\Document\SamlDocument; use Krixon\SamlClient\Protocol\Signature; use Krixon\SamlClient\ServiceProvider; use Psr\Http\Message\UriInterface; class Request { private $id; private $uri; private $binding; private $parameters; private $relayState; private $document; private $signature; public function __construct( RequestId $id, UriInterface $uri, Instant $issueInstant, Binding $binding, ServiceProvider $serviceProvider = null, Signature $signature = null, bool $forceAuthn = false, bool $passive = false, RequestedAuthnContext $authnContext = null, NameIdPolicy $nameIdPolicy = null, string $relayState = null, array $parameters = [] ) { // @see https://www.oasis-open.org/committees/download.php/56780/sstc-saml-bindings-errata-2.0-wd-06-diff.pdf // Section 3.4.3 if ($binding->isHttpRedirect() && strlen($relayState) > 80) { throw InvalidRelayState::tooLong(); } $this->uri = $uri; $this->id = $id; $this->binding = $binding; $this->signature = $signature; $this->parameters = $parameters; $this->relayState = $relayState; $document = SamlDocument::create('samlp:AuthnRequest'); $root = $document->root(); $root->setAttribute('Version', '2.0'); $root->setAttribute('ID', $this->id->toString()); $root->setAttribute('IssueInstant', $issueInstant->toString()); $root->setAttribute('Destination', $uri->__toString()); if ($serviceProvider) { $serviceProvider->applyToLoginRequest($document, $root); } if ($forceAuthn) { $root->setAttribute('ForceAuthn', 'true'); } if ($passive) { $root->setAttribute('IsPassive', 'true'); } // Signature must not be embedded for HTTP-Redirect binding. // Instead the final encoded payload will be signed and the signature provided via a URL parameter. if ($signature && !$binding->isHttpRedirect()) { $signature->appendTo($document, $root); } if ($nameIdPolicy) { $nameIdPolicy->appendTo($document, $root); } if ($authnContext) { $authnContext->appendTo($document, $root); } $this->document = $document; } public function toDocument() : SamlDocument { return $this->document; } public function signature() : ?Signature { return $this->signature; } public function id() : RequestId { return $this->id; } /** * The endpoint to which the request should be made. */ public function uri() : UriInterface { return $this->uri; } /** * The protocol binding to use for this request. */ public function binding() : Binding { return $this->binding; } /** * The RelayState token is an opaque reference to state information maintained at the SP. * * The use of this mechanism in an initial request places requirements on the selection and use of the binding * subsequently used to convey the response. Namely, if a SAML request message is accompanied by RelayState data, * then the SAML responder MUST return its SAML protocol response using a binding that also supports a RelayState * mechanism, and it MUST place the exact RelayState data it received with the request into the corresponding * RelayState parameter in the response. * * Some bindings that define a "RelayState" mechanism do not provide for end to end origin * authentication or integrity protection of the RelayState value. Most such bindings are defined in * conjunction with HTTP, and RelayState is often involved in the preservation of HTTP resource state that * may involve the use of HTTP redirects, or embedding of RelayState information in HTTP responses, * HTML content, etc. In such cases, implementations need to beware of Cross-Site Scripting (XSS) and * other attack vectors (e.g., Cross-Site Request Forgery, CSRF) that are common to such scenarios. * * Section 3.1.1 https://www.oasis-open.org/committees/download.php/56780/sstc-saml-bindings-errata-2.0-wd-06-diff.pdf * * There is also another, de facto standard use for RelayState when using IdP-initiated log on. In that case, * there is no incoming request from the SP, so there can be no state to be relayed back. Instead, the RelayState * is used by the IDP to signal to the SP what URL the SP should redirect to after successful sign on. That * is not part of the SAML2 standard, but is supported but this library. * * @return string|null */ public function relayState() : ?string { return $this->relayState; } public function hasRelayState() : bool { return null !== $this->relayState; } /** * Additional parameters to be included in the HTTP request. */ public function parameters() : array { return $this->parameters; } }
Python
UTF-8
848
3.3125
3
[]
no_license
import sys import math def get_arg(arg: str, operations: list) -> int: if arg.startswith("$"): return calc_cell(int(arg[1:]), operations) else: return int(arg) def calc_cell(i: int, operations: list) -> int: operation_name, arg1, arg2 = operations[i] if operation_name == "VALUE": return int(get_arg(arg1, operations)) else: arg1, arg2 = get_arg(arg1, operations), get_arg(arg2, operations) if operation_name == "ADD": value = arg1 + arg2 elif operation_name == "SUB": value = arg1 - arg2 elif operation_name == "MULT": value = arg1 * arg2 operations[i] = ("VALUE", str(value), "_") return value n = int(input()) operations = [input().split() for _ in range(n)] for i in range(n): print(calc_cell(i, operations))
Python
UTF-8
374
3.0625
3
[]
no_license
from math import gcd # 유클리드 호제법도 좋지만 간결하게 풀기 위해 math.gcd from itertools import combinations # 손으로 구해본 후 조합을 이용해서 풀어야겠다고 판단 TC = int(input()) for _ in range(TC): sm = 0 arr = [int(x) for x in input().split()] for a,b in combinations(arr[1:],2): sm += gcd(a,b) print(sm)
C++
UTF-8
2,100
2.640625
3
[]
no_license
#include "FirstIncludes.h" #include <stdlib.h> #include <memory> #include <string> #include <iostream> #include <fstream> #include <vector> #include <map> #include "MemoryDebug.h" using namespace std; #include "BasicTypes.h" #include "OSservices.h" #include "Str.h" using namespace KKU; #include "SipperCruise.h" using namespace SipperHardware; SipperCruise::SipperCruise (): cruiseName (), shipName (), description (), dateStart (osGetLocalDateTime ().Date ()), dateEnd (osGetLocalDateTime ().Date ()), location (), objective (), principal (), researchOrg () { } SipperCruise::~SipperCruise () { } SipperCruiseList::SipperCruiseList (bool _owner): KKQueue<SipperCruise> (_owner) { } SipperCruiseList::~SipperCruiseList () { } // If there are any errors in '_cruiseName' will return description of error otherwise will return a empty string. KKStr SipperCruise::ValidateCruiseName (const KKStr& _cruiseName) { if (_cruiseName.Empty ()) return "Cruise Name can not be left blank!"; if (_cruiseName.Len () > 10) return "Cruise Name can not be longer than 10 characters."; KKStr invalidChars = ""; for (int32 x = 0; x < _cruiseName.Len (); x++) { char c = toupper (_cruiseName[x]); if ((c >= 'A') && (c <= 'Z')) continue; if ((c >= '0') && (c <= '9')) continue; if (c == '_') continue; if (invalidChars.Len () > 0) invalidChars << ", "; invalidChars.Append (c); } if (invalidChars.Len () > 0) return KKStr ("Invalid Characters[") + invalidChars + "]"; return ""; } /* ValidateCruiseName*/ class SipperCruiseList::CruiseNameComparator { public: bool operator() (SipperCruisePtr left, SipperCruisePtr right ) { return (left->CruiseName ().CompareIgnoreCase (right->CruiseName ()) < 0); } }; /* CruiseNameComparator */ void SipperCruiseList::SortByCruiseName () { CruiseNameComparator comparator; sort (begin (), end (), comparator); }
JavaScript
UTF-8
542
2.71875
3
[]
no_license
function getMinIndex(list, rest, comp) { let minInd = rest for (let i = rest + 1; i < list.length; ++i) { if (comp(list[i], list[minInd]) < 0) { //if (list[i] < list[minInd]) { // string compare minInd = i } } return minInd } function selSort(list, comp) { let copy = [...list] let lsize = copy.length for (let i = 0; i < lsize; ++i) { let minit = getMinIndex(copy, i, comp) // swapNode(list, i, minit) ;[copy[i], copy[minit]] = [copy[minit], copy[i]] } return copy } export default selSort
C++
UTF-8
757
3.28125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int a[10]; void quicksort(int left,int right); int main(int argc,char *argv[]) { srand(time(NULL)); cout<<argv[1]<<endl; cout<<"随机生成数字为:"; for(int &i:a) { i = rand()%100; cout<<i<<" "; } cout<<endl; quicksort(0,9); cout<<"排完序后数字为:"; for(int i: a) cout<<i<<" "; cout<<endl; return 0; } void quicksort(int left,int right) { int i,j,temp; if(left > right) return ; i = left; j = right; temp = a[left]; while(i != j) { while(a[j] >= temp && i<j) j--; while(a[i] <= temp && i<j) i++; if(i<j) { int t; t = a[j]; a[j] = a[i]; a[i] = t; } } a[left] = a[i]; a[i] = temp; quicksort(left,i-1); quicksort(i+1,right); }
Java
UTF-8
561
2.203125
2
[]
no_license
// djm pooled, from above public float getMetric() { switch(m_count) { case 0: assert (false); return 0.0f; case 1: return 0.0f; case 2: return MathUtils.distance(m_v1.w, m_v2.w); case 3: case3.set(m_v2.w).subLocal(m_v1.w); case33.set(m_v3.w).subLocal(m_v1.w); // return Vec2.cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); return Vec2.cross(case3, case33); default: assert (false); return 0.0f; } }
TypeScript
UTF-8
361
2.828125
3
[]
no_license
import { Pergunta } from './pergunta'; /** * Representa o Jogo com perguntas respondidas, * nome do jogador e pontos conquistados */ export class Jogo { public id: string; public player_name: string; public score = 0; public questions: Pergunta[] = []; constructor(nomeJogador: string) { this.player_name = nomeJogador; } }
Java
UTF-8
1,532
4.21875
4
[]
no_license
package array; /** * 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 * * 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 输入: [7,1,5,3,6,4] 输出: 5 解释: * 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, * 因为卖出价格需要大于买入价格。 * * 输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 * * 注意你不能在买入股票前卖出股票。 * * @author RunyuanLiang * */ public class MaxProfit1 { public static void main(String[] args) { MaxProfit1 maxProfit1 = new MaxProfit1(); int[] prices = { 7, 1, 5, 3, 6, 4 }; System.out.println(maxProfit1.maxProfit2(prices)); } public int maxProfit1(int[] prices) { int max = 0; for (int i = 0; i < prices.length; i++) { for (int j = prices.length - 1; j > i; j--) { if (prices[j] - prices[i] > 0 && prices[j] - prices[i] > max) { max = prices[j] - prices[i]; } } } return max; } public int maxProfit2(int[] prices) { if (0 == prices.length || null == prices) return 0; int minPrece = prices[0]; int maxProfit = 0; for (int i = 1; i < prices.length; i++) { maxProfit = Math.max(maxProfit, prices[i] - minPrece); minPrece = Math.min(minPrece, prices[i]); } return maxProfit; } }
Python
UTF-8
321
3.21875
3
[]
no_license
import serial, time arduino = serial.Serial('COM4', 9600, timeout=.1) time.sleep(2) #give the connection a second to settle arduino.write(str(3)) while True: data = arduino.readline() if data: print data.rstrip('\n') #strip out the new lines for now # (better to do .read() in the long run for this reason
JavaScript
UTF-8
6,640
2.625
3
[]
no_license
import React, { Component } from 'react'; import styled, { keyframes } from "styled-components"; import Loading from './Loading'; import Loading2 from './Loading2' class AI extends Component { constructor(){ super() this.state = { listen: false, visable: true, pageOne: true, showLoader: true } } changeState () { this.setState({ listen: !this.state.listen }) } handleStop(){ this.setState({ visable: false }, () => this.loadMessage()) } loadMessage(){ setTimeout(() => { this.setState({ pageOne: false }, () => this.displayPreMessage()) }, 2000) } displayMessage(){ setTimeout(()=> { this.setState({ showLoader: false }) }, 2600) var i = 0; var txt = `I have an idea for a 4D printer that is capable of printing an actual life form.`; /* The text */ var speed = 25; /* The speed/duration of the effect in milliseconds */ console.log(txt); function typeWriters() { if (i < txt.length) { document.getElementById('message').innerHTML += txt.charAt(i); i++; setTimeout(typeWriters, speed); } } typeWriters() console.log('done') } displayPreMessage(){ setTimeout(() => {this.displayMessage()}, 4000) const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; const dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] const now = new Date() let date = now.getDate() let day = dayNames[now.getDay()] let month = monthNames[now.getMonth()] let year = now.getFullYear() var i = 0; var txt = `On ${day} ${month} ${date}rd , Austin Pegues shared an idea with Jacob Yang.`; /* The text */ var speed = 25; /* The speed/duration of the effect in milliseconds */ console.log(txt); function typeWriter() { if (i < txt.length) { document.getElementById('pre-message').innerHTML += txt.charAt(i); i++; setTimeout(typeWriter, speed); } } typeWriter() } render() { return ( <Container> <Header> <Logo> STEVIE </Logo> <Greeting> Hello, Austin </Greeting> </Header> <Content> {this.state.pageOne ? <Instructions > <Text out={this.state.visable}>What can I help you with, Austin?</Text> {this.state.listen ? <Loading vis = {this.state.visable}/> : <div style ={{height: '19px'}}></div>} {!this.state.listen ? <ListenButton onClick={_ => this.changeState()} out = {this.state.visable}> Listen </ListenButton> : <StopListenButton onClick={_ => this.handleStop()} out={this.state.visable}> Stop Listening </StopListenButton> } </Instructions> : <PageTwo> <Loading2 load = {this.state.showLoader}/> <PreMessage> <div id = 'pre-message'></div> </PreMessage> <MessageBackground> <Message> <div id = 'message'></div> </Message> </MessageBackground> </PageTwo> } </Content> </Container> ); } } export default AI; // var margin = this.state.listen ? `magrin-top: 80px` : `margin-top: 40px` // let A = { // marginBottom: '40px', // transition: 'margin-bottom 80px', // transitionDuration: '.5s', // transitionTimingFunction: 'linear-forwards' // } // let B = { // marginBottom: '80px', // transition: 'margin-bottom 40px', // transitionDuration: '.5s', // transitionTimingFunction: 'linear-forwards' // } const fc = ` display: flex; flex-direction: column justify-content: center align-items: center` const Container = styled.section` background: #fafafa; height: 100vh; width: 100%; z-index: 0; ` const Header = styled.div` position: relative; background: #2A93D5; display: flex; justify-content: space-between height: 44px; box-shadow: 0 2px 4px -1px rgba(0,0,0,.2), 0 4px 5px 0 rgba(0,0,0,.14), 0 1px 10px 0 rgba(0,0,0,.12); padding: 10px; z-index: 2; ` const Logo = styled.div` display: flex justify-content: center align-items: center color: #ffffff border: 3px solid white; font-size: 30px; letter-spacing: 2px; padding-left: 5px margin-left: 10px padding-right: 5px; ` const Greeting = styled.div` display: flex justify-content: center align-items: center color: #ffffff margin-right: 10px font-size: 17px ` const Content = styled.section` height: calc(100% - 67px); width: 100% z-index: 1 ${fc} ` const Instructions = styled.div` box-sizing: border-box; padding: 80px 30px display: flex flex-direction: column align-items: center justify-content: space-around height: 400px width: 700px background-color: #ffffff z-index: 2 box-shadow: 0 2px 4px -1px rgba(0,0,0,.2), 0 4px 5px 0 rgba(0,0,0,.14), 0 1px 10px 0 rgba(0,0,0,.12); ` const PageTwo = Instructions.extend` padding: 50px 30px jusify-content: space-between; ` const fadeout = keyframes` from { opacity: 1; } to { opacity: 0; } ` const fadein = keyframes` to { opacity: 1; } ` const Text = styled.div` font-size: 20px color: #6D6D6D display: inline visibility: ${props => props.out ? 'visible' : 'hidden'} animation: ${props => props.out ? null : fadeout} .7s ease-out; transition: visibility .7s ease-out; ` const ListenButton = styled.button` background-color: #2A93D5 font-size: 16px height: 50px width: 23% color: #ffffff; transition: background-color 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms,box-shadow 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms; line-height: 1.4em; border-radius: 2px; cursor: pointer; visibility: ${props => props.out ? 'visible' : 'hidden'} animation: ${props => props.out ? null : fadeout} .7s ease-out; transition: visibility .7s ease-out; &:hover { background-color: #2788C5 } ` const StopListenButton = ListenButton.extend` background-color: #E23039 !important ` const MessageBackground = styled.div` box-sizing: border-box; opacity: 0; width: 500px; height: 207px; border: 2px solid #F1F1F1; animation: ${fadein} 1s ease-in 1 forwards; animation-delay: 2.5s; display: flex; padding: 0px 20px 18px 20px; ` const PreMessage = styled.div` font-size: 18px; color: #6D6D6D; ` const Message = styled.div` display: flex; justify-content: center; align-items: center; text-align: center; color: #6D6D6D; font-size: 16px; `
Java
UTF-8
2,746
1.835938
2
[]
no_license
package com.chd.hrp.hpm.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; import org.springframework.dao.DataAccessException; import com.chd.base.SqlMapper; import com.chd.hrp.hpm.entity.AphiEmpBonusAudit; /** * * @Title. * @Description. * @Copyright: Copyright (c) 2015-2-14 下午9:54:34 * @Company: 杭州亦童科技有限公司 * @Author: LiuYingDuo * @email: bell@s-chd.com * @Version: 1.0 */ public interface AphiEmpBonusAuditMapper extends SqlMapper { /** * */ public int addEmpBonusAudit(Map<String, Object> entityMap) throws DataAccessException; /** * */ public List<AphiEmpBonusAudit> queryEmpBonusAudit(Map<String, Object> entityMap, RowBounds rowBounds) throws DataAccessException; /** * */ public AphiEmpBonusAudit queryEmpBonusAuditByCode(Map<String, Object> entityMap) throws DataAccessException; /** * */ public int deleteEmpBonusAudit(Map<String, Object> entityMap) throws DataAccessException; /** * */ public int deleteEmpBonusAuditById(String id) throws DataAccessException; /** * */ public int updateEmpBonusAudit(Map<String, Object> entityMap) throws DataAccessException; /** * */ public int updateEmpBonusAuditData(Map<String, Object> entityMap) throws DataAccessException; /** * */ public List<AphiEmpBonusAudit> queryEmpBonusAudit(Map<String, Object> entityMap) throws DataAccessException; /** * */ public List<AphiEmpBonusAudit> queryEmpBonusAuditData(Map<String, Object> entityMap) throws DataAccessException; //发放到工资表 public List<Map<String,Object>> queryEmpBonusDataForWagePay(Map<String, Object> entityMap) throws DataAccessException; //根据年、月、wage_code 删除工资发放表中的数据 public int deleteAccWagePayByYearMonth(Map<String, Object> entityMap) throws DataAccessException; //根据数据 public int addEmpBonusDataForWagePay(@Param("sql") String sql,@Param("sqlValue") String sqlValue,@Param("addList2") List<Map<String, Object>> entityMap) throws DataAccessException; public void updateBatchWage(@Param("sqlWage") String sqlWage,@Param("addList") List<Map<String, Object>> addList) throws DataAccessException; public Map<String, Object> queryWagePay(Map<String, Object> entityMap) throws DataAccessException; public void updateBatchWagePay(Map<String, Object> addMapWagePay) throws DataAccessException; public int updateBatchWagePayList(List<Map<String, Object>> updateList) throws DataAccessException; public void updateBatchWage(@Param("addList") List<Map<String, Object>> addList); //public int updateWageItem(Map<String, Object> addWageMap) throws DataAccessException; }
Java
UTF-8
2,185
2.875
3
[]
no_license
package edu.ohiou.dynamic; import java.util.HashSet; import java.util.Random; import java.util.Set; import javax.swing.JPanel; import javax.swing.tree.DefaultMutableTreeNode; import edu.ohiou.mfgresearch.labimp.spacesearch.BlindSearcher; import edu.ohiou.mfgresearch.labimp.spacesearch.DefaultSpaceState; import edu.ohiou.mfgresearch.labimp.spacesearch.Searchable; import edu.ohiou.mfgresearch.labimp.spacesearch.SpaceSearcher; public class SpaceSearcherEx2 extends DefaultSpaceState { int counter = 0; int value; static int total = 0; static int MAX = 10; static int MIN = 5; public SpaceSearcherEx2() { // TODO Auto-generated constructor stub node = new DefaultMutableTreeNode(this); total++; counter = total; init(); value = setValue(); } @Override public Set<Searchable> makeNewStates() { // TODO Auto-generated method stub Set<Searchable> states = new HashSet<Searchable>(); states.add(new SpaceSearcherEx2()); states.add(new SpaceSearcherEx2()); return states; } private int setValue () { Random random = new Random(); // return random.nextInt(MAX - MIN) + MIN; return counter + 5; } @Override public int[] setSearchTypes() { int [] searchTypes = {SpaceSearcher.BREADTH_FIRST}; // TODO Auto-generated method stub return searchTypes; } public boolean canBeGoal() { return value == 10; } public boolean isBetterThan(Searchable inState) { return false; } public void init () { panel = new Example2Panel (); } public String toString() { return "Space Searcher Example-" + counter + "-" + value; } @Override public boolean equals(Searchable s) { SpaceSearcherEx2 sse2 = (SpaceSearcherEx2) s; // TODO Auto-generated method stub return value == sse2.value; } public int hashCode() { return new Integer(value).hashCode(); } public static void main(String[] args) { // TODO Auto-generated method stub SpaceSearcherEx2 ss = new SpaceSearcherEx2(); SpaceSearcherEx2 gs = new SpaceSearcherEx2(); gs.value += 3; BlindSearcher bs = new BlindSearcher (ss, gs); bs.setApplet(); bs.display("Showing Mandvi space search"); } class Example2Panel extends JPanel { } }
C#
UTF-8
2,988
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _19110430_NguyenVanPhu_Day01 { public partial class AddStudentForm : Form { public AddStudentForm() { InitializeComponent(); } private void AddStudentForm_Load(object sender, EventArgs e) { } private void Cancel_Click(object sender, EventArgs e) { Close(); } private void Add_Click(object sender, EventArgs e) { Student student = new Student(); int id = Convert.ToInt32(StudentID.Text); string fname = FirstName.Text; string lname = LastName.Text; DateTime bdate = BirthDate.Value; string phone = Phone.Text; string address = Address.Text; string gender = "Male"; if(radioButtonFemale.Checked) { gender = "Female"; } MemoryStream pic = new MemoryStream(); int born_year = BirthDate.Value.Year; int this_year = DateTime.Now.Year; if(((this_year-born_year)<10)||((this_year-born_year)>100)) { MessageBox.Show("The student Age must be between 10 and 100 year", "Invalid Birth Date", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (verif()) { PictureBoxStudent.Image.Save(pic, PictureBoxStudent.Image.RawFormat); if(student.InsertStudent(id,fname,lname,bdate,gender,phone,address,pic)) { MessageBox.Show("New Student Added", "Add Student", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Error", "Add Student", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Empty Fields", "Add Student", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } bool verif() { if ((FirstName.Text.Trim() == "") || (LastName.Text.Trim() == "") || (Address.Text.Trim() == "") || (Phone.Text.Trim() == "") || (PictureBoxStudent.Image == null)) { return false; } else { return true; } } private void UploadImage_Click(object sender, EventArgs e) { OpenFileDialog opf = new OpenFileDialog(); opf.Filter = "Select Image(*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif"; if((opf.ShowDialog()==DialogResult.OK)) { PictureBoxStudent.Image = Image.FromFile(opf.FileName); } } } }
Markdown
UTF-8
1,463
3.953125
4
[]
no_license
# Parsing boolean options in Python ## Introduction Python has the module argparse to parse command line options. I had some difficulty figuring out how to parse boolean options. I hope this page helps others like me who also want to parse boolean options. ## The Code ``` #!/usr/bin/env python import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='Example code to parse boolean options') parser.add_argument('--publish', action='store_false', required=False, help='Publish something') parser.add_argument('--update', action='store_true', required=False, help='Update something') args = parser.parse_args() print('Update: %s' % (args.update)) print('Publish: %s' % (args.publish)) ``` ## Explanation The key to parsing boolean options is use `action='store_true' or action='store_false'`. If the action is `store_true`, and the option is not specified on the command line, the variable will be `False`. If the option is specified, it will be `True`. For `action=store_false`, the opposite is true. If the option is specified on command line, the variable will be `False`. ## Sample Output Without specifying any options: ``` $ ./parsebool.py Update: False Publish: True ``` The update flag is false while the publish flag is true. When we specify the options, the update flag is true and the publish flag is false. ``` $ ./parsebool.py --update --publish Update: True Publish: False ```
Java
UTF-8
342
2.796875
3
[]
no_license
package main.java.Leetcode.DP.Easy; public class NumArray { int dp[]; public NumArray(int[] nums) { dp = new int[nums.length + 1]; dp[0] = 0; for (int i = 1; i <= nums.length; i++) dp[i] = dp[i-1] + nums[i-1]; } public int sumRange(int i, int j) { return dp[j+1] - dp[i]; } }
Markdown
UTF-8
2,959
3.03125
3
[]
no_license
## 欧拉降幂 #### $a^b\equiv \begin{cases} a^{b\%\phi(p)}~~~~~~~~~~~gcd(a,p)=1\\ a^b~~~~~~~~~~~~~~~~~~~gcd(a,p)\neq1,b<\phi(p)\\ a^{b\%\phi(p)+\phi(p)}~~~~gcd(a,p)\neq1,b\geq\phi(p) \end{cases}~~~~~~~(mod~p)$ ## 逆元递推 #### $inv[i] = (p - p / i) * inv[p \%i]\%p,inv[1] = 1$ p 为奇质数 ## lucas定理 #### $C_{n}^m\%p = (C_{n/p}^{m/p}\%p) * (C_{n\%p}^{m\%p}\%p)\%p$ ## 费马小定理 #### $a^{p-1} \equiv 1\;(mod\;p)$ 可以用于快速幂求逆元:$a * a^{p-2} \equiv 1\;(mod\;p)$ ## 欧拉函数 #### $\varphi(x) = x\prod_{i=1}^n(1-\frac{1}{p_i})$ $p_i$ 为质因子 ## 杜教筛 求:$\sum_{i=1}^nf(i)$ 已知:$h = f*g$ ,设 $S(n)=\sum_{i=1}^nf(i)$ #### $g(1)S(n)=\sum_{i=1}^n (f*g)(i) - \sum_{d=2}^ng(d) \cdot S(\left \lfloor \frac{n}{d} \right \rfloor )$ ## 狄利克雷卷积与莫比乌斯反演相关 #### $\forall a,b,c \in \mathbb{Z},\left \lfloor \frac{a}{bc} \right \rfloor = \left \lfloor \frac{\left \lfloor \frac{a}{b} \right \rfloor}{c} \right \rfloor$ 求 $\sum_{i=1}^{n} \left \lfloor \frac{n}{i} \right \rfloor$ ```cpp // [l, r) for (int l = 1, r; l <= n; l = r) { r = n / (n / l) + 1; res += (r - l) * (n / l); } ``` #### $f*g = \sum_{d|n}f(d)g(\frac{n}{d})$ ### 常用积极函数与卷积 #### $\varepsilon (n) = [n=1]$ #### $1(n) = 1$ #### $id(n) = n$ #### $\mu(n) = \left\{\begin{matrix} & 1 & n=1\\ & 0 & n含有平方因子\\ & (-1)^k & k 为 n的本质不同质因子数\\\end{matrix}\right.$ #### $d(n) = \sum_{d|n}1$ #### $\sigma(n) = \sum_{d|n}d$ #### $\varphi(n) =\sum_{i=1}^n[gcd(i,n) = 1] $ #### $ \varepsilon = \mu * 1 \Leftrightarrow \varepsilon(n) = \sum_{d|n}\mu(d)$ #### $d = 1 * 1 \Leftrightarrow d(n) = \sum_{d|n}1$ #### $\sigma = id * 1 \Leftrightarrow \sigma(n) = \sum_{d|n}d$ #### $\varphi = \mu * id \Leftrightarrow \varphi(n) = \sum_{d|n}d \cdot \mu(\frac{n}{d})$ #### $id = \varphi * 1 \Leftrightarrow n = \sum_{d|n} \varphi(\frac{n}{d})$ #### $[gcd(i, j) = 1] \Leftrightarrow \sum_{d|gcd(i,j)}\mu(d)$ **莫比乌斯反演** #### $f(n) = \sum_{d|n}g(d) \Rightarrow g(n) = \sum_{d|n} \mu(d) f(\frac{n}{d})$ **常用公式** #### $((id \cdot f)*id)(n) = n\sum_{d|n}f(d)$ 卷一个 $id$ 让 $id$ 变常数 #### $\sum_{i=1}^n i = \frac{n(n+1)}{2}$ ## 二项式反演 #### $f(n) = \sum_{i=0}^nC_n^ig(i)$ #### $g(n) = \sum_{i=0}^n(-1)^{n-i}C_n^if(i)$ ## 类欧几里得算法 定义: #### $f(a, b, c, n) = \sum_{i=0}^n \left \lfloor \frac{ai+b}{c} \right \rfloor$ #### $g(a, b, c, n) = \sum_{i=0}^n i \left \lfloor \frac{ai+b}{c} \right \rfloor$ #### $h(a, b, c, n) = \sum_{i=0}^n \left \lfloor \frac{ai+b}{c} \right \rfloor ^ 2$ #### $m = \left \lfloor \frac{ai+b}{c} \right \rfloor$ 可得: #### $f(a,b,c,n) = nm - f(c, c - b - 1, a, m - 1)$ #### $g(a,b,c,n) = \frac{1}{2}[n(n+1)m-f(c,c-b-1,a,m-1)-h(c,c-b-1,a,m-1)]$ #### $h(a,b,c,n) = nm(m+1) - 2g(c,c-b-1,a,m-1)-2f(c,c-b-1,a,m-1)-f(a,b,c,n)$ 边界是 a = 0,返回0
Swift
UTF-8
1,262
2.90625
3
[]
no_license
// // ActivityViewModel.swift // Alpha // // Created by Garrett Head on 12/9/20. // Copyright © 2020 Garrett Head. All rights reserved. // import Foundation import UIKit class ActivityViewModel { var name : String var color : UIColor var icon : UIImage var progress : Double var remaining : Double var unit : String? var target : Double? init(activity: Activity, withUnit unit: Unit, target: UserTarget) { self.name = activity.name self.color = activity.color self.icon = activity.icon self.unit = unit.symbol if let handler = activity.getHandler(withIdentifier: activity.progressIdentifier), let targetValue = target.value { let unitConverter = UnitConverter() let target = unitConverter.convert(value: targetValue, toUnit: unit, fromUnit: handler.unit) let total = unitConverter.convert(value: handler.total, toUnit: unit, fromUnit: handler.unit) let remaining = target - total self.target = target self.progress = total self.remaining = remaining } else { self.target = 0.0 self.progress = 0.0 self.remaining = 0.0 } } }
C#
UTF-8
7,586
3.6875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; namespace _11ArrayManipulator_myV { class Program { static void Main(string[] args) { List<int> integersList = Console.ReadLine().Split().Select(int.Parse).ToList(); string commands = Console.ReadLine(); while (commands != "end") { string[] tokens = commands.Split().ToArray(); string action = tokens[0]; if (action == "exchange") { int index = int.Parse(tokens[1]); if (index < 0 || index >= integersList.Count) { Console.WriteLine("Invalid index"); } else { List<int> listToPrint = new List<int>(); if (index != integersList.Count - 1) { for (int i = index + 1; i < integersList.Count; i++) { listToPrint.Add(integersList[i]); } for (int i = 0; i < index + 1; i++) { listToPrint.Add(integersList[i]); } integersList = listToPrint; } } } else if (action == "max") { if (tokens[1] == "even") { int maxEven = int.MinValue; int maxEvenIndex = -1; for (int i = 0; i < integersList.Count; i++) { if (integersList[i] % 2 == 0 && integersList[i] >= maxEven) { maxEven = integersList[i]; maxEvenIndex = i; } } if (maxEvenIndex != -1) { Console.WriteLine(maxEvenIndex); } else { Console.WriteLine("No matches"); } } else if (tokens[1] == "odd") { int maxOdd = int.MinValue; int maxOddIndex = -1; for (int i = 0; i < integersList.Count; i++) { if (integersList[i] % 2 != 0 && integersList[i] >= maxOdd) { maxOdd = integersList[i]; maxOddIndex = i; } } if (maxOddIndex != -1) { Console.WriteLine(maxOddIndex); } else { Console.WriteLine("No matches"); } } } else if (action == "min") { if (tokens[1] == "even") { int minEven = int.MaxValue; int minEvenIndex = -1; for (int i = 0; i < integersList.Count; i++) { if (integersList[i] % 2 == 0 && integersList[i] <= minEven) { minEven = integersList[i]; minEvenIndex = i; } } if (minEvenIndex != -1) { Console.WriteLine(minEvenIndex); } else { Console.WriteLine("No matches"); } } else if (tokens[1] == "odd") { int minOdd = int.MaxValue; int minOddIndex = -1; for (int i = 0; i < integersList.Count; i++) { if (integersList[i] % 2 != 0 && integersList[i] <= minOdd) { minOdd = integersList[i]; minOddIndex = i; } } if (minOddIndex != -1) { Console.WriteLine(minOddIndex); } else { Console.WriteLine("No matches"); } } } else if (action == "first") { int countOfElements = int.Parse(tokens[1]); if (countOfElements > integersList.Count) { Console.WriteLine("Invalid count"); } else { Console.Write("["); if (tokens[2] == "even") { var listToPrint = integersList.Where(x => x % 2 == 0).Take(countOfElements).ToList(); Console.Write(string.Join(", ", listToPrint)); } else if (tokens[2] == "odd") { var listToPrint = integersList.Where(x => x % 2 != 0).Take(countOfElements).ToList(); Console.Write(string.Join(", ", listToPrint)); } Console.Write("]"); Console.WriteLine(); } } else if (action == "last") { int countOfElements = int.Parse(tokens[1]); if (countOfElements > integersList.Count) { Console.WriteLine("Invalid count"); } else { Console.Write("["); if (tokens[2] == "even") { var listToPrint = integersList.Where(x => x % 2 == 0).Reverse().Take(countOfElements).Reverse().ToList(); Console.Write(string.Join(", ", listToPrint)); } else if (tokens[2] == "odd") { var listToPrint = integersList.Where(x => x % 2 != 0).Reverse().Take(countOfElements).Reverse().ToList(); Console.Write(string.Join(", ", listToPrint)); } Console.Write("]"); Console.WriteLine(); } } commands = Console.ReadLine(); } Console.Write("["); Console.Write(string.Join(", ", integersList)); Console.Write("]"); Console.WriteLine(); } } }
Python
UTF-8
680
4.40625
4
[]
no_license
#This is a program that determines what grade you get fom an exam mark. loop = True CUT_A = 90 CUT_B = 70 CUT_C = 50 #This code ask for their mark mark = int(input("Enter your exam mark ")) if mark <=100 and mark >=0: loop = False #This code sets a boundary of the possible exam mark. while loop == True: mark = int(input("Enter a valid exam mark ")) if mark <=100 and mark >=0: loop = False #This code sets determines which grade they'll get. if mark >CUT_A: print("You have got an A") elif mark >CUT_B: print("You have got a B") elif mark >CUT_C: print("You have got a C") elif mark <CUT_C: print("You have failed") else: print("Fail")