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
C++
UTF-8
1,143
2.890625
3
[]
no_license
#pragma once #include "Component.hpp" #include "ResourceHolder.hpp" #include "ResourceIdentifiers.hpp" #include <vector> #include <string> #include <memory> #include <functional> namespace GUI { class Button final : public Component { public: using Callback = std::function<void()>; enum class Type { Normal, Selected, Pressed, ButtonCount }; public: explicit Button(const FontHolder& fonts, const TextureHolder& textures); void setCallback(Callback callback) { mCallback = std::move(callback); } void setText(const std::string_view text); void setToggle(bool flag) { mIsToggle = flag; } virtual bool isSelectable() const override { return true; } virtual void select() override; virtual void deselect() override; virtual void activate() override; virtual void deactivate() override; virtual void handleEvent(const sf::Event& event) override {} private: virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override; void changeTexture(Type buttonType); private: Callback mCallback; sf::Sprite mSprite; sf::Text mText; bool mIsToggle{ false }; }; }
Python
UTF-8
4,600
2.859375
3
[]
no_license
import unittest from unittest.mock import MagicMock, patch from weather.weather import Weather import urllib.request as urllib import json import boto3 from boto3.dynamodb.conditions import Key class FakeResponse(): def read(self): pass class TestWeather(unittest.TestCase): def test_set_status_success(self): with patch('urllib.request.urlopen') as urlopen_mock, patch('urllib.request.Request') as urlrequest_mock: weather = Weather("fake_url") urlrequest_mock.return_value = {"foo": "bar"} mock_response = urlopen_mock.return_value mock_response.read.return_value = bytearray( '{"foo": "bar"}', 'utf-8') weather.set_status() self.assertEqual(weather.status, { "foo": "bar" }) def test_set_status_failure(self): with patch('urllib.request.urlopen') as urlopen_mock, patch('urllib.request.Request') as urlrequest_mock: weather = Weather("fake_url") urlrequest_mock.return_value = "fail" mock_response = urlopen_mock.return_value mock_response.read.return_value = "fail" weather.set_status() self.assertEqual(weather.status, {"Error": "Unavailable"}) def test_get_status_success(self): weather = Weather("fake_url") status_msg = "Success" weather.status = status_msg result = weather.get_status() self.assertEqual(result, status_msg) def test_save_to_dynamo_success(self): weather = Weather("fake_url") weather.table.put_item = MagicMock() expected_data = { "overnight": { "inches": "5", "centimeters": "12.70" }, "twentyFourHour": { "inches": "8", "centimeters": "20.32" }, "timestamp": "2019-12-18T12:00:00.000Z", "resort": "Keystone" } weather.get_data_to_save = MagicMock(return_value=expected_data) weather.save_to_dynamo(expected_data) weather.get_data_to_save.assert_not_called() weather.table.put_item.assert_called_with(expected_data) def test_get_data_to_save_makes_request_and_returns_formatted_data(self): weather = Weather("mountainweatherreport.net") fake_response = FakeResponse() mock_response_data = bytearray(''' { "SnowReportSections": [{ "Depth": { "Inches": "5", "Centimeters": "12.70" }, "Description":"Overnight <br> Snowfall" }, { "Depth": { "Inches": "8", "Centimeters": "20.32" }, "Description":"24 Hours<br/>Snowfall" }] }''', 'utf-8') expected_value = json.loads(mock_response_data) fake_response.read = MagicMock(return_value=mock_response_data) urllib.urlopen = MagicMock(return_value=fake_response) urllib.Request = MagicMock(return_value="fake request") result = weather.get_data_to_save() urllib.Request.assert_called_with("mountainweatherreport.net") urllib.urlopen.assert_called_with("fake request") self.assertEqual(result, expected_value) def test_save_weather_report_success(self): weather = Weather("mountainweatherreport.net") weather.get_data_to_save = MagicMock(return_value="Woohoo") weather.transform_api_data = MagicMock(return_value="Woohoo2") weather.save_to_dynamo = MagicMock() weather.save_weather_report() weather.get_data_to_save.assert_called() weather.transform_api_data.assert_called_with("Woohoo") weather.save_to_dynamo.assert_called_with("Woohoo2") def test_get_weather_data_calls_into_dynamo(self): weather = Weather("something") weather.resort_name = "test" mock_data = { "Items": [{ "snow": "a bunch", "timestamp": "2019-12-18T00:00:00.000Z", "resort": "test" }] } weather.table.query = MagicMock(return_value=mock_data) actual_data = weather.get_weather_data() weather.table.query.assert_called_with( KeyConditionExpression=Key("resort").eq("test"), ScanIndexForward=False, Limit=1 ) self.assertEqual(actual_data, mock_data["Items"][0])
C#
UTF-8
1,051
2.609375
3
[ "MIT" ]
permissive
//----------------------------------------------------------------------- // <copyright file="NoOpCommand.cs" company="AllocateThis!"> // Copyright (c) AllocateThis! Studio's. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Net.Sockets; using MudDesigner.Engine.Core; using MudDesigner.Engine.Mobs; namespace MudDesigner.Engine.Commands { /// <summary> /// This command performs nothing. It is used when the engine needs to continue a current state but perform no commands /// </summary> public class NoOpCommand : ICommand { /// <summary> /// Executes the command. /// </summary> /// <param name="player">The player who sent the command.</param> public void Execute(IPlayer player) { // We are doing nothing on purpose. // This is a No operation command, aka do nothing. // good for silently changing states or modes. } } }
JavaScript
UTF-8
58,334
2.84375
3
[]
no_license
/* remedy-rest-api.js 6/19/18 andrew@hicox.com <Andrew Hicox> this is an object-oriented javascript library for talking to BMC Remedy ARS REST Webservices. */ /* DO-TO (6/19/18 @ 1648) * support for sending attachments * ARFormEntry class to model a set of fields from a form also 'Status History', Diary fields, Associations, yadda yadda * ARFormEntryList class to model a result set (query output) * pushFields emulation * legit npm release */ /* NODE STUFF this section contains stuff to set up the node.js XHR emulation API just comment this stuff out if you want to use it in a browser. */ 'use strict'; var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; // include the XHR emulation API process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // trust shady SSL certs /* noiceObjectCore this is a simple object class that defines my favorite constructor model. everything inherits from it 'cause I rollz like that. */ class noiceObjectCore { /* constructor({args}, {defaults}) {args} is an object reference modelling user-specified arguments to the constructor every enumerable attribute will be copied into the resulting object. {defaults} is an object reference modelling class-default attributes, every enumberable attribute eill be copied into the resulting object, however {args} overrides attributes found here NOTE: attribute names prefixed with the underscore char (_) are created as non-enumerable attributes (meaning they are present but Object.keys won't see them and JSON.stringify won't either). Generally speaking, these are "internal" attributes and you'd create getter and setter methods for them NOTE ALSO: as a convention, each class should define _version and _className class defaults. */ constructor (args, defaults, callback){ // every noiceObjectCore descendant class should override these on {defaults} let classDefaults = { _version: 1, _className: 'noiceObjectCore' }; // helper function to spawn the attributes function createAttribute(self, key, val){ Object.defineProperty(self, key, { value: val, writable: true, enumerable: (! (/^_/.test(key))), configurable: true }); } // pull in defaults, then args [classDefaults, defaults, args].forEach(function(attributeSet){ if ((attributeSet === null) || (attributeSet === undefined) || (typeof(attributeSet) != 'object')){ return(false); } Object.keys(attributeSet).forEach(function(k){ createAttribute(this, k, attributeSet[k]); }, this); }, this); } } // end noiceObjectCore class /* noiceCoreUtility this adds a few utility functions to noiceObjectCore */ class noiceCoreUtility extends noiceObjectCore { /* isNull(value) return true if the given value is one of the myriad ways to say "this thing doesn't carry a value" */ isNull(val){ return( (typeof(val) === 'undefined') || (val === null) || (val === undefined) || (val == "null") || (/^\s*$/.test(val)) ); } /* isNotNull(value) return the inverse of isNull() */ isNotNull(val){ return(! this.isNull(val)); } /* hasAttribute(attributeName) return true if this has <attributeName> and the value of that attribute is not null */ hasAttribute(attributeName){ return(this.hasOwnProperty(attributeName) && this.isNotNull(this[attributeName])); } /* epochTimestamp(bool) return the unix epoch in seconds unless bool is true, then return miliseconds */ epochTimestamp(bool){ if (bool === true){ return(new Date().getTime()); }else{ return(Math.round(new Date().getTime() / 1000)); } } /* toEpoch(string, bool) <string> contains the string to attempt to convert into an epoch integer <bool> (default true), if false returns course value (seconds), if true fine (milliseconds) */ toEpoch(date, fine){ if (fine !== false){ fine = true; } try { return(fine?Date.parse(date):(Date.parse(date)/1000)); }catch(e){ throw(`[toEpoch]: failed to parse timestamp: ${e}`); } } /* fromEpoch(integer, type) <integer> is the epoch timestamp (course values will be backfilled to fine) <type> is an enum: date | time | dateTime returns an ARS/REST compatible ISO 8601 date / time / dateTime string */ fromEpoch(epoch, type){ // sort out the epoch format if (this.isNull(epoch)){ throw(`[fromEpoch]: given epoch value is not valid`); } try { epoch = parseInt(epoch.toString(), 10); /* NOTE LOOSE END (6/21/18 @ 1732) this could probably bite ya ... */ if (epoch <= 9999999999){ epoch = (epoch * 1000);} }catch(e){ throw(`[fromEpoch]: failed integer conversion of given epoch time: ${e}`); } // ya rly function pad(number) { if (number < 10) { return '0' + number; } return number; } // convert it switch(type){ case 'date': try { let myDate = new Date(epoch); return(`${myDate.getUTCFullYear()}-${pad(myDate.getUTCMonth() + 1)}-${pad(myDate.getUTCDate())}`) }catch(e){ throw(`[fromEpoch]: failed time conversion: ${e}`); } break; case 'time': try { let myDate = new Date(epoch); return(`${pad(myDate.getUTCHours())}:${pad(myDate.getUTCMinutes())}:${pad(myDate.getUTCSeconds())}`) }catch(e){ throw(`[fromEpoch]: failed time conversion: ${e}`); } break; case 'dateTime': try { return(new Date(epoch).toISOString()); }catch(e){ throw(`[fromEpoch]: failed dateTime conversion: ${e}`); } break; default: throw('[fromEpoch]: invalid date type specified'); } } /* NOTE: we might want to have some currency manipulation helpers here */ } // end noiceCoreUtility class /* ARSRestException this is an object model representing an exception received from the ARS REST Service. objects of the ARSRestException class have the form: { httpStatus: <http status code> httpResponseHeaders: { <headerName>: <headerValue> } thrownByFunction: (optional) name of ARSRestAPI function that threw it thrownByFunctionArgs: (optional) a copy of the args sent to <thrownByFunction> (if speficied) arsErrorList: [ { messageType: ok | error | warning | fatal | bad status | non-ars, messageText: main error message ($ERRMSG$) messageAppendedText: addtional error message ($ERRAPPENDMSG$) messageNumber: error number (integer / $ERRNO$) }, ... ] } since the AR Server may return an arbirtrary number of error objects in a REST exception, these attribute accessors return data from the FIRST error in the list: *.message (returns *.messageText of first entry in arsErrorList unless separately) *.messageType (returns *.messageType of first entry in arsErrorList unless empty then 'non-ars') *.messageText *.messageAppendedText *.messageNumber */ class ARSRestException extends noiceCoreUtility { /* constructor({ xhr: (optional) if specfied, extract arsErrorList, httpStatus and httpResponseHeaders message: (optional) if specified, return this on *.message rather than the first entry in arsErrorList messageType: (optional) if specified, return this on *.messageType rather than the first entry in arsErrorList thrownByFunction: (optional) name of function that threw the error thrownByFunctionArgs: (optional) copy of args sent to function that threw the error }) */ constructor(args){ // set it up super(args, { _version: 1, _className: 'ARSRestException', _lastResort: [], _message: '', _messageType: '', httpResponseHeaders: {}, arsErrorList: [] }); this.time = this.epochTimestamp(true); // if we've got an xhr, parse it out if (this.hasAttribute('xhr')){ // try to get the httpStatus try { this.httpStatus = this.xhr.status; }catch (e){ this.httpStatus = 0; this._lastResort.push(`[httpStatus]: cannot find ${e}`); } // try to get the httpResponseHeaders try { this.xhr.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(function(line){ line = line.replace(/[\r\n]+/, ''); let tmp = line.split(/:\s+/,2); this.httpResponseHeaders[tmp[0]] = tmp[1]; }, this); }catch (e){ this._lastResort.push(`[httpResponseHeaders]: failed to parse ${e}`); } // try to parse out ars errors if (this.isNotNull(this.xhr.responseText)){ try { this.arsErrorList = JSON.parse(this.xhr.responseText) }catch (e){ this._lastResort.push(`[arsErrorList]: failed to parse ${e}`); this.messageType = 'non-ars'; } }else{ this.messageType = 'non-ars'; this._message += '(error object not returned from ARServer)'; } } // end handling xhr } /* getter and setter for 'message' return this.message if it's set otherwise the first messageText from arsErrorList, or an error stating why not */ set message(v){ this._message = v; } get message(){ if (this.hasAttribute('_message')){ return(this._message); }else { try { return(this.arsErrorList[0].messageText); }catch (e){ return('no error messsage available (not set, cannot be parsed from xhr)'); } } } /* getter and setter for 'messageType' return this.message if it's set otherwise the first messageText from arsErrorList, or an error stating why not */ set messageType(v){ this._messageType = v; } get messageType(){ if (this.hasAttribute('_messageType')){ return(this._messageType); }else { try { return(this.arsErrorList[0].messageType); }catch (e){ return('no messageType available (not set, cannot be parsed from xhr)'); } } } /* getters for arsErrorList properties all default to the first entry in arsErrorList or false */ get messageText(){ try { return(this.arsErrorList[0].messageText); }catch (e){ return(false); } } get messageAppendedText(){ try { return(this.arsErrorList[0].messageAppendedText); }catch (e){ return(false); } } get messageNumber(){ try { return(this.arsErrorList[0].messageNumber); }catch (e){ return(false); } } /* return a legit Error object */ get error(){ return(new Error(this.message)); } /* return a nice string */ toString(){ return(`[http/${this.httpStatus} ${this.messageType} (${this.messageNumber})]: ${this.message} / ${this.messageAppendedText}`); } } // end ARSRestException class /* ARSRestDispatcher this extends noiceCoreUtility to provide utility functions for dispatching REST calls via the XHR api. This class should provide an abstract interface for accessing XHR from either node or in a browser. */ class ARSRestDispatcher extends noiceCoreUtility { /* constructor({ endpoint: <url> method: GET | POST | PUT | DELETE , headers: { header:value ...}, content: { object will be JSON.strigified before transmit } expectHtmlStatus: <integer> (receiving this = reolve, else reject promise) }) */ constructor (args){ // set it up super(args, { _version: 1, _className: 'ARSRestDispatcher', timeout: 0, debug: false, encodeContent: true }); // required arguments ['endpoint', 'method', 'expectHtmlStatus'].forEach(function(k){ if (! this.hasAttribute(k)){ throw(`[ARSRestDispatcher (constructor)]: ${k} is a required argument`); } }, this); // handle multiple expectHtmlStatus values this.myOKStatuses = []; if ((typeof(this.expectHtmlStatus) == 'number') || (typeof(this.expectHtmlStatus) == 'string')) { this.myOKStatuses.push(this.expectHtmlStatus); }else{ this.myOKStatuses = this.expectHtmlStatus; } // REMOVE ME if (this.debug){ console.log(`[ARSRestDispatcher (endpoint)]: ${this.endpoint}`); } } /* go() this creates the xhr in question, sends it and returns a rejected or resolved promise rejected promises are mangled into ARSRestException objects. resolved promises just return the xhr and your caller can do what they need to do */ go(){ let self = this; return(new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); if (self.timeout > 0){ xhr.timeout = self.timeout; } if (self.hasAttribute('responseType')){ xhr.responseType = self.responseType; } // success callback xhr.addEventListener("load", function(){ if (self.myOKStatuses.indexOf(this.status) >= 0){ self.end = self.epochTimestamp(true); resolve(this); }else{ self.end = self.epochTimestamp(true); reject(new ARSRestException({'xhr': this, 'event': 'load'})); } }); // error callback xhr.addEventListener("error", function(){ self.end = self.epochTimestamp(true); reject(new ARSRestException({ 'xhr': this, 'event': 'error', message: 'ARSRestDispatcher recieved "error" event (probably a timeout)' })); }); // abort callback xhr.addEventListener("abort", function(){ self.end = self.epochTimestamp(true); reject(new ARSRestException({ 'xhr': this, 'event': 'abort', message: 'ARSRestDispatcher recieved "abort" event (probably user cancel or network issue)' })); }); // open it up xhr.open(self.method, self.endpoint); // set request headers let keepTruckin = true; if ((self.hasOwnProperty('headers')) && (typeof(self.headers) === 'object')){ try { Object.keys(self.headers).forEach(function(k){ xhr.setRequestHeader(k, self.headers[k]); }); }catch(e){ keepTruckin = false; reject(new ARSRestException({ messageType: 'non-ars', message: `failed to set request headers: ${e}` })); } } // encode the content if we have it if (self.hasAttribute('content') && keepTruckin){ let encoded = ''; if (self.encodeContent){ try { encoded = JSON.stringify(self.content); }catch(e){ keepTruckin = false; reject(new ARSRestException({ messageType: 'non-ars', message: `failed to encode content with JSON.stringify: ${e}` })); } }else{ encoded = self.content; } if (keepTruckin){ if (self.debug){ self.start = self.epochTimestamp(true); } xhr.send(encoded); } }else if (keepTruckin){ if (self.debug){ self.start = self.epochTimestamp(true); } xhr.send(); } })); } } // end ARSRestDispatcher class /* RemedyRestAPI class this is the main user-facing class. */ class RemedyRestAPI extends noiceCoreUtility { /* constructor({ protocol: http | https (default https) server: <hostname> port: <portNumber> (optionally specify a nonstandard port number) user: <userId> password: <password> }) everything is optional, but if you wanna call *.authenticate, you've got to set at least server, user & pass either here, before you call *.authenticate or on the args to *.authenticate */ constructor (args){ super(args, { _version: 1, _className: 'RemedyRestAPI', debug: false, protocol: 'https', timeout: (60 * 1000 * 2), // <-- default 2 minute timeout }); // sort out the protocol and default ports switch (this.protocol){ case 'https': if (! this.hasAttribute('port')){ this.port = 443; } break; case 'http': if (! this.hasAttribute('port')){ this.port = 80; } break; default: throw(new ARSRestException({ messageType: 'non-ars', message: `unsupported protocol: ${this.protocol}` })); } } /* authenticate({args}) all args optional if already set on the object protocol: http | https (default https) server: <hostname> port: <portNumber> (optionally specify a nonstandard port number) user: <userId> password: <password> this function returns a reference to self so one can chain it inline with the constructor: let api = await new Remedy(testServer).authenticate().catch(function(e){ // authenticate failed, deal with it here }); */ authenticate(p){ let self = this; return(new Promise(function(resolve, reject){ // check args let inputValid = true; ['protocol', 'server','user','password'].forEach(function(a){ if ((typeof(p) !== 'undefined') && p.hasOwnProperty(a) && self.isNotNull(p[a])){ self[a] = p[a]; } if (inputValid && (! self.hasAttribute(a))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'authenticate', thrownByFunctionArgs: (typeof(p) !== 'undefined')?p:{} })); } }); if (inputValid){ new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/jwt/login`, method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded", "Cache-Control": "no-cache" }, expectHtmlStatus: 200, timeout: self.timeout, content: `username=${self.user}&password=${self.password}`, encodeContent: false }).go().then(function(xhr){ // handle success self.token = xhr.responseText; resolve(self); }).catch(function(e){ // handle error e.thrownByFunction = 'authenticate'; e.thrownByFunctionArgs = (typeof(p) !== 'undefined')?p:{} reject(e); }); } })); } /* isAuthenticated return true if we have an api session token, else false */ get isAuthenticated(){ return(this.hasAttribute('token')); } /* logout() destroy the session token on the server */ logout(){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; if (self.debug){ console.log('[logout] call on object that is not authenticated. nothing to do.'); } resolve(true); } // check args if (inputValid){ ['protocol', 'server'].forEach(function(a){ if (inputValid && (! self.hasAttribute(a))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'logout' })); } }); } // do the dirtay deed dirt cheap ... if (inputValid){ new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/jwt/logout`, method: 'POST', headers: { "Authorization": `AR-JWT ${self.token}`, "Cache-Control": "no-cache", "Content-Type": "application/x-www-form-urlencoded" }, expectHtmlStatus: 204, timeout: self.timeout }).go().then(function(xhr){ // handle success delete(self.token); resolve(true); }).catch(function(e){ // handle error e.thrownByFunction = 'logout'; reject(e); }); } })); } /* query({ schema: <form name> fields: [array, of, fieldnames, to, get, values, for] -- note add something for assoc stuff later QBE: <QBE string> offset: <return data from this row number -- for paging> limit: <max number of rows to return> sort: <see the docs. but basically <field>.asc or <field>.desc comma separated }) */ query(p){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `operation requires authentication and api handle is not authenticated`, thrownByFunction: 'query' })); } // arguments are required if (inputValid && (typeof(p) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required inputs missing: given argument is not an object ${typeof(p)}`, thrownByFunction: 'query' })); } // check args ['schema', 'fields', 'QBE'].forEach(function(a){ if (inputValid && ((! p.hasOwnProperty(a)) || self.isNull(p[a]))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'query', thrownByFunctionArgs: p })); } }); // fields has to be an object too if (inputValid && (typeof(p.fields) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: 'fields' is not an object (${typeof(p.fields)})`, thrownByFunction: 'query', thrownByFunctionArgs: p })); } // default value for fetchAttachments if ((! p.hasOwnProperty('fetchAttachments')) || (p.fetchAttachments !== true)){ p.fetchAttachments = false; } if (inputValid){ /* 11/1/2018 -- apparently the field list has to be url encoded as well */ let getList = []; p.fields.forEach(function(field){ getList.push(encodeURIComponent(field)); }); // get the endpoint together let url = `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/arsys/v1/entry/${encodeURIComponent(p.schema)}/?q=${encodeURIComponent(p.QBE)}&fields=values(${getList.join(",")})`; ['offset', 'limit', 'sort'].forEach(function(a){ if ((p.hasOwnProperty(a)) && (self.isNotNull(p[a]))){ url += `&${a}=${encodeURIComponent(p[a])}`; } }); new ARSRestDispatcher({ endpoint: url, method: 'GET', headers: { "Authorization": `AR-JWT ${self.token}`, "Content-Type": "application/x-www-form-urlencoded", "Cache-Control": "no-cache" }, expectHtmlStatus: 200, timeout: self.timeout }).go().then(function(xhr){ // handle success /* LOOSE END 6/19/18 @ 1505 we should be blessing the result into an ARResultList object but of course first we need to write that class */ try { let resp = JSON.parse(xhr.responseText); let promiseKeeper = []; // handle getting attachments (if enabled) if (p.fetchAttachments){ resp.entries.forEach(function(row){ // figure out the entry id we're dealin' with for the getAttachment call if (row.hasOwnProperty('_links') && row._links.hasOwnProperty('self') && row._links.self[0].hasOwnProperty('href')){ let parse = row._links.self[0].href.split('/'); let ticket = parse[(parse.length -1)]; // find attachment fields if there are any Object.keys(row.values).forEach(function(field){ if ((typeof(row.values[field]) == 'object') && row.values[field].hasOwnProperty('name') && row.values[field].hasOwnProperty('sizeBytes')){ if (self.debug){ console.log(`fetching attachment from record: ${ticket} and field: ${field} with size: ${row.values[field].sizeBytes} and filename: ${row.values[field].name}`); } promiseKeeper.push( self.getAttachment({ schema: p.schema, ticket: ticket, fieldName: field }).then(function(data){ row.values[field].data = data; }) ); } }); }else{ if (self.debug){ console.log("[query]: can't parse entryId from self link to get attachment");} } }); // end itterating fields on rows looking for attachments to fetch if (promiseKeeper.length > 0){ Promise.all(promiseKeeper).then(function(p){ resolve(resp); }).catch(function(e){ // e should already be blessed into ARSRestException reject(e); }); } }else{ resolve(resp); } }catch (e){ reject(new ARSRestException({ messageType: 'non-ars', message: `failed to parse server response (JSON.parse): ${e}`, thrownByFunction: 'query', thrownByFunctionArgs: p })); } }).catch(function(e){ // handle error e.thrownByFunction = 'query'; e.thrownByFunctionArgs = p; reject(e); }); } })); } /* getTicket({ schema: <form name> ticket: <ticket number> fields: [array, of, fieldnames, to, get, values, for] -- note add something for assoc stuff later fetchAttachments: true | false (default false). if true, fetch the binary data for attachments and include in .data }) */ getTicket(p){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `operation requires authentication and api handle is not authenticated`, thrownByFunction: 'getTicket' })); } // arguments are required if (inputValid && (typeof(p) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required inputs missing: given argument is not an object ${typeof(p)}`, thrownByFunction: 'getTicket' })); } // check args ['schema', 'fields', 'ticket'].forEach(function(a){ if (! (inputValid && p.hasOwnProperty(a) && self.isNotNull(p[a]))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'getTicket', thrownByFunctionArgs: p })); } }); // default value for fetchAttachments if ((! p.hasOwnProperty('fetchAttachments')) || (p.fetchAttachments !== true)){ p.fetchAttachments = false; } // fields has to be an object too if (inputValid && (typeof(p.fields) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: 'fields' is not an object (${typeof(p.fields)})`, thrownByFunction: 'getTicket', thrownByFunctionArgs: p })); } // do it. do it. do it 'till ya satisfied if (inputValid){ let fieldTmp = []; p.fields.forEach(function(fieldName){ fieldTmp.push(encodeURIComponent(fieldName)); }); new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/arsys/v1/entry/${encodeURIComponent(p.schema)}/${p.ticket}/?fields=values(${fieldTmp.join(",")})`, method: 'GET', headers: { "Authorization": `AR-JWT ${self.token}`, "Content-Type": "application/x-www-form-urlencoded", "Cache-Control": "no-cache" }, expectHtmlStatus: 200, timeout: self.timeout }).go().then(function(xhr){ // handle success /* LOOSE END 6/19/18 @ 1505 we should be blessing the result into an ARResultList object but of course first we need to write that class */ try { let resp = JSON.parse(xhr.responseText); let promiseKeeper = []; // handle getting attachments (if enabled) if (p.fetchAttachments){ Object.keys(resp.values).forEach(function(field){ if ((typeof(resp.values[field]) == 'object') && resp.values[field].hasOwnProperty('name') && resp.values[field].hasOwnProperty('sizeBytes')){ if (self.debug){ console.log(`fetching attachment from field: ${field} with size: ${resp.values[field].sizeBytes} and filename: ${resp.values[field].name}`); } promiseKeeper.push( self.getAttachment({ schema: p.schema, ticket: p.ticket, fieldName: field }).then(function(data){ resp.values[field].data = data; }) ); } }); Promise.all(promiseKeeper).then(function(p){ resolve(resp); }).catch(function(e){ // e should already be blessed into ARSRestException reject(e); }) // don't need to look for attachments to fetch }else{ resolve(JSON.parse(xhr.responseText)); } }catch (e){ reject(new ARSRestException({ messageType: 'non-ars', message: `failed to parse server response (JSON.parse): ${e}`, thrownByFunction: 'getTicket', thrownByFunctionArgs: p })); } }).catch(function(e){ // handle error e.thrownByFunction = 'getTicket'; e.thrownByFunctionArgs = p; reject(e); }); } })); } /* getAttachment({ schema: <form name> ticket: <ticket number> fieldName: <attachment field name> }) */ getAttachment(p){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `operation requires authentication and api handle is not authenticated`, thrownByFunction: 'getAttachment' })); } // arguments are required if (inputValid && (typeof(p) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required inputs missing: given argument is not an object ${typeof(p)}`, thrownByFunction: 'getAttachment' })); } // check args ['schema', 'ticket', 'fieldName'].forEach(function(a){ if (! (inputValid && p.hasOwnProperty(a) && self.isNotNull(p[a]))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'getAttachment', thrownByFunctionArgs: p })); } }); // do it. do it. do it 'till ya satisfied if (inputValid){ new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/arsys/v1/entry/${encodeURIComponent(p.schema)}/${p.ticket}/attach/${encodeURIComponent(p.fieldName)}`, method: 'GET', headers: { "Authorization": `AR-JWT ${self.token}`, //"Content-Type": "application/x-www-form-urlencoded", //"Cache-Control": "no-cache" }, expectHtmlStatus: 200, timeout: self.timeout, responseType: 'arrayBuffer' }).go().then(function(xhr){ // handle success /* LOOSE END 6/25/18 @ 1645 my first thought was to make some kinda object model to represent an attachment (something like {name: <>, size: <>, data: <>}) however, upon reflection, I think it's best that this function returns the raw binary data in an array buffer. you need to have data from the ticket to tell you how big it is and what it's name is anyhow. so we can either pass the user contextless binary (like we're doing), or we can do an extra fetch and get the meta-data for the attachment from the ticket. OR ... we can add a getAttachments option to getTicket and query. If you specify it, we just do the extra fetch to get the binary data inside the original response. you can call it yourself if you want to or just do it inside the original call automatically, which is like a 90% use case probably */ resolve(xhr.responseText); }).catch(function(e){ // handle error e.thrownByFunction = 'getAttachment'; e.thrownByFunctionArgs = p; reject(e); }); } })); } /* createTicket({ schema: <formName>, fields: {fieldName:fieldValue ...}, }); */ createTicket(p){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `operation requires authentication and api handle is not authenticated`, thrownByFunction: 'createTicket' })); } // arguments are required if (inputValid && (typeof(p) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required inputs missing: given argument is not an object ${typeof(p)}`, thrownByFunction: 'createTicket' })); } // check args ['schema', 'fields'].forEach(function(a){ if (inputValid && ((! p.hasOwnProperty(a)) || self.isNull(p[a]))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'createTicket', thrownByFunctionArgs: p })); } }); // fields has to be an object too if (inputValid && (typeof(p.fields) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: 'fields' is not an object (${typeof(p.fields)})`, thrownByFunction: 'createTicket', thrownByFunctionArgs: p })); } /* LEFT OFF HERE - 6/26/18 @ 1054 next step is to hack sending attachments onto createTicket and mergeData to do that, ARSRestDispatcher needs to know how to send multipart/form-data requests as described here: https://docs.bmc.com/docs/ars1805/entry-formname-804716411.html#id-/entry/{formName}-Createanentrywithattachments just doing this in node by brute-force formatting everything up and sending it is definitely possible, HOWEVER our goal with this library is to do everything on the legit XHR api interface so we can just drop the whole shebang into a browser verbatim. That being the case, what we actually need to do is to extend the XHR shim library for node to support the new(ish) FormData API as described here: https://developer.mozilla.org/en-US/docs/Web/API/FormData also of interest: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS once we've got the XMLHttpRequest node emulation library supporting the FormData API, then we can code up ARSRestDispatcher to send multipart/form-data and we can send values to attachment fields in the library. for now, it supports retrieving attachments but not sending them. */ // woohah! i gochu-all-incheck! if (inputValid){ new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/arsys/v1/entry/${encodeURIComponent(p.schema)}`, method: 'POST', headers: { "Authorization": `AR-JWT ${self.token}`, "Content-Type": "application/json", "Cache-Control": "no-cache" }, content: {values:p.fields}, expectHtmlStatus: 201, timeout: self.timeout }).go().then(function(xhr){ // handle success /* LOOSE END 6/19/18 @ 1555 we should be blessing the result into an ARRecordId object but of course first we need to write that class for now it's: { url:<url>, entryId: <entryId>} */ try { let strang = xhr.getResponseHeader('location'); let parse = strang.split('/'); let ticket = parse[(parse.length -1)]; resolve({ url: strang, entryId: ticket }); }catch (e){ reject(new ARSRestException({ messageType: 'non-ars', message: `failed to parse server response for record identification (create successful?): ${e}`, thrownByFunction: 'createTicket', thrownByFunctionArgs: p })); } }).catch(function(e){ // handle error e.thrownByFunction = 'createTicket'; e.thrownByFunctionArgs = p; reject(e); }); } })); } /* modifyTicket({ schema: <formName>, ticket: <entryId>. fields: {fieldName:fieldValue ...}, }); */ modifyTicket(p){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `operation requires authentication and api handle is not authenticated`, thrownByFunction: 'modifyTicket' })); } // arguments are required if (inputValid && (typeof(p) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required inputs missing: given argument is not an object ${typeof(p)}`, thrownByFunction: 'modifyTicket' })); } // check args ['schema', 'fields', 'ticket'].forEach(function(a){ if (inputValid && ((! p.hasOwnProperty(a)) || self.isNull(p[a]))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'modifyTicket', thrownByFunctionArgs: p })); } }); // fields has to be an object too if (inputValid && (typeof(p.fields) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: 'fields' is not an object (${typeof(p.fields)})`, thrownByFunction: 'modifyTicket', thrownByFunctionArgs: p })); } // been smoove since days of underoos ... if (inputValid){ new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/arsys/v1/entry/${encodeURIComponent(p.schema)}/${p.ticket}`, method: 'PUT', headers: { "Authorization": `AR-JWT ${self.token}`, "Content-Type": "application/json", "Cache-Control": "no-cache" }, content: {values:p.fields}, expectHtmlStatus: 204, timeout: self.timeout }).go().then(function(xhr){ // handle success resolve(true); }).catch(function(e){ // handle error e.thrownByFunction = 'modifyTicket'; e.thrownByFunctionArgs = p; reject(e); }); } })); } /* deleteTicket({ schema: <formName>, ticket: <entryID> }) */ deleteTicket(p){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `operation requires authentication and api handle is not authenticated`, thrownByFunction: 'deleteTicket' })); } // arguments are required if (inputValid && (typeof(p) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required inputs missing: given argument is not an object ${typeof(p)}`, thrownByFunction: 'deleteTicket' })); } // check args ['schema', 'ticket'].forEach(function(a){ if (inputValid && ((! p.hasOwnProperty(a)) || self.isNull(p[a]))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'deleteTicket', thrownByFunctionArgs: p })); } }); // now here's the real dukey, meanin' whose really the 'ish if (inputValid){ new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/arsys/v1/entry/${encodeURIComponent(p.schema)}/${p.ticket}`, method: 'DELETE', headers: { "Authorization": `AR-JWT ${self.token}`, "Content-Type": "application/json", "Cache-Control": "no-cache" }, expectHtmlStatus: 204, timeout: self.timeout }).go().then(function(xhr){ // handle success resolve(p.ticket); }).catch(function(e){ // handle error e.thrownByFunction = 'deleteTicket'; e.thrownByFunctionArgs = p; reject(e); }); } })); } /* mergeData({ schema: <formName> fields: {fieldOne:valueOne, fieldTwo:valueTwo ...} QBE: <qualification> (optional) handleDuplicateEntryId: error | create | overwrite | merge | alwaysCreate (default error) ignorePatterns: <bool> (default false) ignoreRequired: <bool> (default false) workflowEnabled: <bool> (default true) associationsEnabled: <bool> (default true) multimatchOption: error | useFirstMatching (default error) }) */ mergeData(p){ let self = this; return(new Promise(function(resolve, reject){ // input validation let inputValid = true; // if we're not authenticated, don't bother if (! self.isAuthenticated){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `operation requires authentication and api handle is not authenticated`, thrownByFunction: 'mergeData' })); } // arguments are required if (inputValid && (typeof(p) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required inputs missing: given argument is not an object ${typeof(p)}`, thrownByFunction: 'mergeData' })); } // check args ['schema', 'fields'].forEach(function(a){ if (inputValid && ((! p.hasOwnProperty(a)) || self.isNull(p[a]))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: ${a}`, thrownByFunction: 'mergeData', thrownByFunctionArgs: p })); } }); // fields has to be an object too if (inputValid && (typeof(p.fields) !== 'object')){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `required argument missing: 'fields' is not an object (${typeof(p.fields)})`, thrownByFunction: 'mergeData', thrownByFunctionArgs: p })); } // validate handleDuplicateEntryId let mergeTypeDecoder = { error: "DUP_ERROR", create: "DUP_NEW_ID", overwrite: "DUP_OVERWRITE", merge: "DUP_MERGE", alwaysCreate: "GEN_NEW_ID" }; if ((! p.hasOwnProperty('handleDuplicateEntryId')) || (self.isNull(p.handleDuplicateEntryId))){ p.handleDuplicateEntryId = "error"; } if (inputValid && (! mergeTypeDecoder.hasOwnProperty(p.handleDuplicateEntryId))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `invalid value (handleDuplicateEntryId): ${p.handleDuplicateEntryId}`, thrownByFunction: 'mergeData', thrownByFunctionArgs: p })); } // validate multimatchOption let multimatchOptionDecoder = { error: 0, useFirstMatching: 1 }; if ((! p.hasOwnProperty('multimatchOption')) || (self.isNull(p.multimatchOption))){ p.multimatchOption = "error"; } if (inputValid && (! multimatchOptionDecoder.hasOwnProperty(p.multimatchOption))){ inputValid = false; reject(new ARSRestException({ messageType: 'non-ars', message: `invalid value (multimatchOption): ${p.multimatchOption}`, thrownByFunction: 'mergeData', thrownByFunctionArgs: p })); } // handle default boolean options if (! ((p.hasOwnProperty('ignorePatterns') && (p.ignorePatterns === true )))){ p.ignorePatterns = false; } if (! ((p.hasOwnProperty('ignoreRequired') && (p.ignoreRequired === true)))){ p.ignoreRequired = false; } if (! ((p.hasOwnProperty('workflowEnabled') && (p.workflowEnabled === false)))){ p.ignoreRequired = true; } if (! ((p.hasOwnProperty('associationsEnabled') && (p.associationsEnabled === false)))){ p.associationsEnabled = true; } // shedonealreadydonehadherses if (inputValid){ let body = { values: p.fields, mergeOptions: { mergeType: mergeTypeDecoder[p.handleDuplicateEntryId], multimatchOption: multimatchOptionDecoder[p.multimatchOption], ignorePatterns: p.ignorePatterns, ignoreRequired: p.ignoreRequired, workflowEnabled: p.workflowEnabled, associationsEnabled: p.associationsEnabled } }; if (p.hasOwnProperty('QBE') && (self.isNotNull(p.QBE))){ body.qualification = p.QBE; } new ARSRestDispatcher({ endpoint: `${self.protocol}://${self.server}:${self.port}${(self.hasAttribute('proxyPath'))?self.proxyPath:''}/api/arsys/v1/mergeEntry/${encodeURIComponent(p.schema)}`, method: 'POST', headers: { "Authorization": `AR-JWT ${self.token}`, "Content-Type": "application/json", "Cache-Control": "no-cache" }, expectHtmlStatus: [201, 204], content: body, timeout: self.timeout }).go().then(function(xhr){ // handle success /* LOOSE END 6/19/18 @ 1634 we should be blessing the result into an ARRecordId object but of course first we need to write that class for now it's: { url:<url>, entryId: <entryId>} */ try { let strang = xhr.getResponseHeader('location'); let parse = strang.split('/'); let ticket = parse[(parse.length -1)]; resolve({ url: strang, entryId: ticket }); }catch (e){ reject(new ARSRestException({ messageType: 'non-ars', message: `failed to parse server response for record identification (merge successful?): ${e}`, thrownByFunction: 'mergeData', thrownByFunctionArgs: p })); } }).catch(function(e){ // handle error e.thrownByFunction = 'mergeData'; e.thrownByFunctionArgs = p; reject(e); }); } })); } } // end RemedyRestAPI class // hook for node module.exports = RemedyRestAPI;
Shell
UTF-8
760
3.703125
4
[ "LLVM-exception", "Apache-2.0" ]
permissive
#!/bin/bash set -euo pipefail # This is a convenience script for maintainers changing a cranelift # dependencies versions. To use, bump the version number below, run the # script. topdir=$(dirname "$0")/.. cd "$topdir" # All the cranelift-* crates have the same version number version="0.49" # Update all of the Cargo.toml files. echo "Updating crate versions to $version" for crate in . crates/* crates/misc/* fuzz; do # Update the version number of this crate to $version. sed -i.bk -e "/^cranelift-/s/\"[^\"]*\"/\"$version\"/" \ "$crate/Cargo.toml" # Update the required version number of any cranelift* dependencies. sed -i.bk -e "/^cranelift-/s/version = \"[^\"]*\"/version = \"$version\"/" \ "$crate/Cargo.toml" done
JavaScript
UTF-8
698
3.03125
3
[]
no_license
import Quiz from './Quiz.js' /** * The starting point of the application * Enter the Nickname * @module js/app * @author Adrian Rosales * @version 1.0.0 * * @param {@listens} event */ function submit (event) { if (event.which === 13 || event.keyCode === 13 || event.type === 'click') { event.preventDefault() const textInput = document.querySelector('#nickname').value let startGame if (textInput.length > 1) { startGame = new Quiz(textInput) startGame.run() } } } const form = document.querySelector('#quizForm') const button = document.querySelector('#submit') button.addEventListener('click', submit, true) form.addEventListener('keypress', submit, true)
Python
UTF-8
294
3.421875
3
[ "MIT", "LicenseRef-scancode-unknown" ]
permissive
import pygame class Obstacle: def __init__(self, location, radius, weight=None): self.location = location self.radius = radius self.weight = weight def draw(self, canvas): pygame.draw.circle(canvas, pygame.Color('red'), self.location, self.radius, 2)
C
UTF-8
1,410
3.921875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define DEBUG if(0) int main() { int i, len, count = 0, countWord = 0; char string[200]; scanf(" %[^\n]", string); len = strlen(string); //tamanho da string DEBUG { printf("%d\n", len); } for(i = 0 ; i < len ; i++) //passo a string inteira para minusculo { string[i] = tolower(string[i]); } for(i = 0 ; i < len ; i++) //busco se existe numero na string { if(string[i] >= 48 && string[i] <= 57) { count++; } } for(i = len - 1 ; i >= 0 ; i--) { DEBUG { printf("%c", string[i]); } } if(count > 0 || string[0] == '\0') //se houver numero ou string vazia, ja imprimo a mensagem { printf("numeros\n0\n"); } else { for(i = len - 1 ; i >= 0 ; i--) //substituo os simbolos pelas letras e imprimo { if(string[i] == 'a') { string[i] = '@'; countWord++; } else if(string[i] == 'e') { string[i] = '3'; countWord++; } else if(string[i] == 'i') { string[i] = '1'; countWord++; } else if(string[i] == 'o') { string[i] = '0'; countWord++; } else if(string[i] == 't') { string[i] = '7'; countWord++; } else if(string[i] == 's') { string[i] = '5'; countWord++; } printf("%c", string[i]); } printf("\n%d", countWord); //imprimo quantas letras foram modificadas } return 0; }
Java
UTF-8
272
1.9375
2
[]
no_license
package com.qa.pages; import org.openqa.selenium.ScreenOrientation; import com.qa.base.TestBase; public class ScreenRotate extends TestBase { public void rotateScreen() { driver.rotate(ScreenOrientation.LANDSCAPE); driver.rotate(ScreenOrientation.PORTRAIT); } }
C#
UTF-8
3,071
2.953125
3
[]
no_license
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Telerik.JustMock; namespace JustMock.ElevatedExamples.BasicUsage.Mock_MustBeCalled { /// <summary> /// The MustBeCalled method is used to assert that a call to a given method or property is made during the execution of a test. /// See http://www.telerik.com/help/justmock/basic-usage-mock-must-be-called.html for full documentation of the feature. /// </summary> [TestClass] public class Mock_MustBeCalled_Tests { [TestMethod] public void Execute_OnExecute_ShouldBeCalled() { // ARRANGE var foo = new Foo(); // Arranging: foo.Execute() should be called during the test method. Mock.Arrange(() => foo.Execute()).MustBeCalled(); // ACT foo.Execute(); // ASSERT - Asserting all arrangements on "foo". Mock.Assert(foo); } [TestMethod] [ExpectedException(typeof(AssertFailedException))] public void Execute_NotExecuted_ShouldNotBeCalled() { // ARRANGE var foo = new Foo(); // Arranging: foo.Execute() should be called during the test method. Mock.Arrange(() => foo.Execute()).MustBeCalled(); // ACT - Not calling foo.Execute() should generate AssertFailedException. // ASSERT - Asserting all arrangements on "foo". Mock.Assert(foo); } [TestMethod] public void Echo_OnExecuteWithTheCorrectArgs_ShouldBeCalled() { // ARRANGE // Creating a mocked instance of the "Foo" class. var foo = Mock.Create<Foo>(); // Arranging: foo.Echo() with argument 1 should be called during the test method. Mock.Arrange(() => foo.Echo(1)).MustBeCalled(); // ACT var actual = foo.Echo(1); // ASSERT - Asserting all arrangements on "foo". Mock.Assert(foo); } [TestMethod] [ExpectedException(typeof(AssertFailedException))] public void Execute_OnExecuteWithWronArgs_ShouldNotBeCalled() { // ARRANGE // Creating a mocked instance of the "Foo" class. var foo = Mock.Create<Foo>(); // Arranging: foo.Echo() with argument 1 should be called during the test method. Mock.Arrange(() => foo.Echo(1)).MustBeCalled(); // ACT - Calling foo.Echo() with different argument than the expected. foo.Echo(10); // ASSERT - Asserting all arrangements on "foo". Mock.Assert(foo); } } #region SUT public class Foo { public void Execute() { } public int Execute(int str) { return str; } public int Echo(int a) { return 5; } } #endregion }
C
UTF-8
145
2.875
3
[]
no_license
#include <stdio.h> int main(int argc, char const *argv[]) { int a; float b; scanf("%d",&a); b = 5*(a-32)/9; printf("c=%.2f",b); return 0; }
Python
UTF-8
504
3.25
3
[ "Apache-2.0" ]
permissive
import six from ast import literal_eval def convert_string_to_float_int(string): if isinstance(string, six.string_types): try: # evaluate the string to float, int or bool value = literal_eval(string) except Exception: value = string else: value = string # check if the the value is float or int if isinstance(value, float): if value.is_integer(): return int(value) return value return value
Java
UTF-8
1,609
1.804688
2
[]
no_license
package com.adjust.sdk; import android.content.Context; import android.net.Uri; public class Adjust { private static AdjustInstance defaultInstance; private Adjust() { } public static synchronized AdjustInstance getDefaultInstance() { AdjustInstance adjustInstance; synchronized (Adjust.class) { if (defaultInstance == null) { defaultInstance = new AdjustInstance(); } adjustInstance = defaultInstance; } return adjustInstance; } public static void onCreate(AdjustConfig adjustConfig) { getDefaultInstance().onCreate(adjustConfig); } public static void trackEvent(AdjustEvent adjustEvent) { getDefaultInstance().trackEvent(adjustEvent); } public static void onResume() { getDefaultInstance().onResume(); } public static void onPause() { getDefaultInstance().onPause(); } public static void setEnabled(boolean z) { getDefaultInstance().setEnabled(z); } public static boolean isEnabled() { return getDefaultInstance().isEnabled(); } public static void appWillOpenUrl(Uri uri) { getDefaultInstance().appWillOpenUrl(uri); } public static void setReferrer(String str) { getDefaultInstance().sendReferrer(str); } public static void setOfflineMode(boolean z) { getDefaultInstance().setOfflineMode(z); } public static void getGoogleAdId(Context context, OnDeviceIdsRead onDeviceIdsRead) { Util.getGoogleAdId(context, onDeviceIdsRead); } }
Shell
UTF-8
1,835
3.984375
4
[]
no_license
#!/bin/bash # Script to automagically generate SUMO network and demand-files with recommended options from OSM with coordinates if [[ "$1" =~ --help ]]; then printf "Generates SUMO net-file from OSM network given by coords and models demand on that network\nUsage: \$script <W,S,E,N> <PREFIX>\n" printf "The coordinates and prefix are inputs. If not set, they will take defaults; Aalborg metro-area\n" exit 0 fi if [ -z "$SUMO_HOME"]; then printf "[ERROR] \$SUMO_HOME is unset!\n" exit 1 fi # Use arguments as filenames coord_input="$1" osm_file_prefix="$2" aalborg_osm_file_prefix="aalborg_metro" osm_file_postfix="_bbox.osm.xml" aalborg_coords="9.8012,56.9581,10.0765,57.1142" # Set defaults coord_input=${coord_input:=$aalborg_coords} osm_file_prefix=${osm_file_prefix:=$aalborg_osm_file_prefix} printf "Using SUMO_HOME:\t%s\nUsing coords:\t\t%s\nUsing prefix:\t\t%s\n" "$SUMO_HOME" "$coord_input" "$osm_file_prefix" # Get Aalborg metropolitan area printf "Running: osmGet.py --bbox %s --prefix %s\n" "$coord_input" "$osm_file_prefix" $SUMO_HOME/tools/osmGet.py --bbox "$coord_input" --prefix "$osm_file_prefix" # recommended netconvert options netconvert_options="--geometry.remove,--roundabouts.guess,--ramps.guess,-v,--junctions.join," netconvert_options+="--tls.guess-signals,--tls.discard-simple,--tls.join,--output.original-names,--junctions.corner-detail," netconvert_options+="5,--output.street-names" # additional sidewalk and crosswalk guessing netconvert_options+="--sidewalks.guess,true,--crossings-guess,true" # osmBuild uses recommended netconvert args by default printf "Running: osmBuild.py --osm-file %s --prefix %s\n" "${osm_file_prefix}${osm_file_postfix}" "$osm_file_prefix" $SUMO_HOME/tools/osmBuild.py --osm-file "${osm_file_prefix}${osm_file_postfix}" --prefix "$osm_file_prefix" --pedestrian
Java
UTF-8
2,861
2.265625
2
[]
no_license
package edu.epam.service; import java.sql.SQLException; import java.util.List; import java.util.Map; import edu.epam.constants.EFactoryType; import edu.epam.factory.AbstractDAOFactory; import edu.epam.model.CourseComment; import edu.epam.model.Direction; import edu.epam.model.TestResults; public class DirectionService { public static Integer createDirection(Direction direction) throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().createDirection(direction); } public static boolean deleteDirection(int id) throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().deleteDirection(id); } public static List<Direction> getAllDirections() throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getAllDirections(); } public static List<Direction> getAllDirectionsForAdmin() throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getAllDirectionsForAdmin(); } public static List<Direction> getDirectionsByHRId(int hrId) throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getDirectionsByHRId(hrId); } public static boolean setDirectionActive(Integer directionId, Boolean active) { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().setDirectionActive(directionId,active); } public static Map<Direction, List<TestResults>> getTop10Map() throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getTop10Map(); } public static Direction getDirectionById(Integer id) throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getDirectionById(id); } public static boolean updateDirectionData(Direction direction) { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().updateDirectionData(direction); } public static boolean setDirectionHR(Integer directionId, Integer hrId) { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().setDirectionHR(directionId,hrId); } public static List<Direction> getTeacherDirections(Integer teacherId) throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getTeacherDirections(teacherId); } public static List<Direction> getAllDirectionsWithInterview() throws SQLException{ return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getAllDirectionsWithInterview(); } public static List<CourseComment> getCourseComments(Integer directionId) throws SQLException { return AbstractDAOFactory.getFactory(EFactoryType.MySQL) .getDirectionDAO().getCourseComments(directionId); } }
TypeScript
UTF-8
1,603
2.6875
3
[]
no_license
import EDDSA from "elliptic" import { Blockchain } from "../blockchain/blockchain" import { ChainUtil } from "../chain-util" import { INITIAL_BALANCE } from "../config" import { Transaction } from "./transaction" import { TransactionPool } from "./transaction-pool" export class Wallet { balance: number keyPair: EDDSA.eddsa.KeyPair publicKey: string constructor(secret: EDDSA.eddsa.Bytes) { this.balance = INITIAL_BALANCE this.keyPair = ChainUtil.genKeyPair(secret) this.publicKey = this.keyPair.getPublic("hex") } toString = (): string => `Wallet - publicKey: ${this.publicKey.toString()} balance: ${this.balance}` sign = (dataHash: EDDSA.eddsa.Bytes): string => this.keyPair.sign(dataHash).toHex() createTransaction = (to: string, amount: number, type: string, blockchain: Blockchain, transactionPool: TransactionPool): Transaction|undefined => { this.balance = this.getBalance(blockchain) if (amount > this.balance) { console.log(`Amount: ${amount} exceeds the current balance: ${this.balance}`) return } let transaction = Transaction.newTransaction(this, to, amount, type) if (transaction) { transactionPool.addTransaction(transaction) return transaction } console.log('Could not create transaction') return } getBalance = (blockchain: Blockchain): number => blockchain.getBalance(this.publicKey) getPublicKey = (): string => this.publicKey }
Java
UTF-8
2,072
1.78125
2
[]
no_license
package com.jeecg.position.service.impl; import com.jeecg.position.entity.PositionModuleEntity; import com.jeecg.position.service.PositionModuleServiceI; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.common.service.impl.CommonServiceImpl; import org.jeecgframework.core.util.HexConvertUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; @Service("positionModuleService") @Transactional public class PositionModuleServiceImpl extends CommonServiceImpl implements PositionModuleServiceI { @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; public void delete(PositionModuleEntity entity) throws Exception { super.delete(entity); } public Serializable save(PositionModuleEntity entity) throws Exception { Serializable t = super.save(entity); return t; } public void saveOrUpdate(PositionModuleEntity entity) throws Exception { super.saveOrUpdate(entity); } @Override public void manualPosition(IoSession session) { byte[] bMPosition = HexConvertUtil.hexStringToBytes("78 78 01 80 0D 0A"); session.write(IoBuffer.wrap(bMPosition)); } @Override public Map<String, Map<String, Object>> apendParams(DataGrid dataGrid) { Map<String, Map<String, Object>> extMap = new HashMap<String, Map<String, Object>>(); List<PositionModuleEntity> list = (List<PositionModuleEntity>) dataGrid.getResults(); for (PositionModuleEntity temp : list) { Map<String, Object> m = new HashMap<String, Object>(); extMap.put(temp.getId(), m); } return extMap; } }
Java
UTF-8
1,365
1.867188
2
[]
no_license
package com.cms.service.impl; import com.cms.core.foundation.Page; import com.cms.dao.mapper.CmsModelItemMapper; import com.cms.service.api.CmsModelItemService; import com.cms.service.converter.CmsModelItemConverter; import com.cms.service.dto.CmsModelItemDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CmsModelItemServiceImpl implements CmsModelItemService { @Autowired private CmsModelItemMapper cmsModelItemMapper; @Override public void save(CmsModelItemDto dto) { } @Override public void deleteById(Integer id) { } @Override public void update(CmsModelItemDto dto) { } @Override public CmsModelItemDto getById(Integer id) { return null; } @Override public Page<CmsModelItemDto> getPage(CmsModelItemDto dto) { return null; } @Override public void batchInsert(List<CmsModelItemDto> list) { cmsModelItemMapper.batchInsert(CmsModelItemConverter.CONVERTER.dtoToEntity(list)); } @Override public List<CmsModelItemDto> getByModelIdAndChannelModel(Integer modelId, Boolean channelModel) { return CmsModelItemConverter.CONVERTER.entityToDto(cmsModelItemMapper.selectByModelIdAndChannelModel(modelId,channelModel)); } }
C++
UTF-8
7,674
2.96875
3
[]
no_license
#include "store/values.h" #include <gtest/gtest.h> namespace store { const uint64 kStoreSize = 1024 * 1024; class ArityTest : public testing::Test { protected: ArityTest() : store_(kStoreSize) { } StaticStore store_; }; TEST_F(ArityTest, EmptyArity) { const vector<Value> features; const Arity* arity = Arity::Get(features); EXPECT_EQ(0UL, arity->size()); EXPECT_EQ(arity, Arity::Get(features)); } TEST_F(ArityTest, SingleFeature) { vector<Value> features; features.push_back(Atom::Get("coucou")); const Arity* arity = Arity::Get(features); EXPECT_EQ(1UL, arity->size()); EXPECT_EQ(arity, Arity::Get(features)); } TEST_F(ArityTest, AtomOrdering) { vector<Value> features; features.push_back(Atom::Get("atom1")); features.push_back(Atom::Get("atom2")); features.push_back(Atom::Get("atom3")); features.push_back(Atom::Get("atom4")); features.push_back(Atom::Get("atom5")); const Arity* arity1 = Arity::Get(features); EXPECT_EQ(5UL, arity1->size()); features.clear(); features.push_back(Atom::Get("atom1")); features.push_back(Atom::Get("atom5")); features.push_back(Atom::Get("atom3")); features.push_back(Atom::Get("atom2")); features.push_back(Atom::Get("atom4")); const Arity* arity2 = Arity::Get(features); EXPECT_EQ(5UL, arity2->size()); EXPECT_EQ(arity1, arity2); } TEST_F(ArityTest, FeaturesOrdering) { Name* name1 = Name::New(&store_); Name* name2 = Name::New(&store_); ASSERT_TRUE(Literal::LessThan(name1, name2)); // Build the arity: // arity(1 15 51 atom1 atom2 atom3 atom4 atom5 name1 name2) vector<Value> features; features.push_back(Atom::Get("atom5")); features.push_back(Value::Integer(15)); features.push_back(Atom::Get("atom2")); features.push_back(Value::Integer(51)); features.push_back(Atom::Get("atom1")); features.push_back(Value::Integer(1)); features.push_back(Atom::Get("atom4")); features.push_back(Atom::Get("atom3")); features.push_back(name1); features.push_back(name2); Arity* arity = Arity::Get(features); EXPECT_EQ(10UL, arity->size()); EXPECT_EQ(1, IntValue(arity->features()[0])); EXPECT_EQ(15, IntValue(arity->features()[1])); EXPECT_EQ(51, IntValue(arity->features()[2])); EXPECT_EQ(Value::ATOM, arity->features()[3].type()); EXPECT_EQ("atom1", arity->features()[3].as<Atom>()->value()); EXPECT_EQ(0UL, arity->Map(1)); EXPECT_EQ(1UL, arity->Map(15)); EXPECT_EQ(2UL, arity->Map(51)); EXPECT_EQ(3UL, arity->Map("atom1")); EXPECT_EQ(4UL, arity->Map("atom2")); EXPECT_EQ(5UL, arity->Map("atom3")); EXPECT_EQ(6UL, arity->Map("atom4")); EXPECT_EQ(7UL, arity->Map("atom5")); EXPECT_EQ(8UL, arity->Map(name1)); EXPECT_EQ(9UL, arity->Map(name2)); EXPECT_FALSE(arity->Has(-1)); EXPECT_FALSE(arity->Has("atom0")); EXPECT_TRUE(arity->Has(15)); EXPECT_TRUE(arity->Has("atom5")); } TEST_F(ArityTest, IsSubsetOf) { Name* name1 = Name::New(&store_); Name* name2 = Name::New(&store_); ASSERT_TRUE(Literal::LessThan(name1, name2)); Value arity1[] = { Value::Integer(2), Atom::Get("atom1"), }; Value arity2[] = { Value::Integer(1), Value::Integer(2), Value::Integer(3), Atom::Get("atom1"), Atom::Get("atom2"), }; Value arity3[] = { Value::Integer(1), Value::Integer(2), Value::Integer(4), Atom::Get("atom1"), Atom::Get("atom2"), }; Value arity4[] = { Value::Integer(1), Value::Integer(2), Value::Integer(3), Value::Integer(4), Value::Integer(5), Atom::Get("atom1"), Atom::Get("atom2"), name1, name2, }; Arity* a0 = KArityEmpty(); // empty arity Arity* a1 = Arity::Get(ArraySize(arity1), arity1); Arity* a2 = Arity::Get(ArraySize(arity2), arity2); Arity* a3 = Arity::Get(ArraySize(arity3), arity3); Arity* a4 = Arity::Get(ArraySize(arity4), arity4); EXPECT_TRUE(a0->IsSubsetOf(a0)); EXPECT_TRUE(a1->IsSubsetOf(a1)); EXPECT_TRUE(a2->IsSubsetOf(a2)); EXPECT_TRUE(a3->IsSubsetOf(a3)); EXPECT_TRUE(a4->IsSubsetOf(a4)); EXPECT_TRUE(a0->IsSubsetOf(a1)); EXPECT_TRUE(a0->IsSubsetOf(a2)); EXPECT_TRUE(a1->IsSubsetOf(a2)); EXPECT_FALSE(a1->IsSubsetOf(a0)); EXPECT_FALSE(a2->IsSubsetOf(a0)); EXPECT_FALSE(a2->IsSubsetOf(a1)); EXPECT_FALSE(a2->IsSubsetOf(a3)); EXPECT_FALSE(a3->IsSubsetOf(a2)); } TEST_F(ArityTest, Serialization) { { Arity* arity = KArityEmpty(); EXPECT_EQ("{NewArity 0 features()}", Value(arity).ToString()); } { Arity* arity = KAritySingleton(); EXPECT_EQ("{NewArity 1 features(1)}", Value(arity).ToString()); } { Value features[] = { Atom::Get("atom1") }; Arity* arity = Arity::Get(ArraySize(features), features); EXPECT_EQ("{NewArity 1 features(atom1)}", Value(arity).ToString()); } { Value features[] = { Atom::Get("atom1"), Value::Integer(-1), Name::New(&store_) }; Arity* arity = Arity::Get(ArraySize(features), features); EXPECT_EQ("{NewArity 3 features(~1 atom1 {NewName})}", Value(arity).ToString()); } } TEST_F(ArityTest, Extend) { Value i1 = Value::Integer(1); Value i2 = Value::Integer(2); Value i3 = Value::Integer(3); Arity* empty = KArityEmpty(); EXPECT_EQ(0UL, empty->size()); Arity* single_one = empty->Extend(i1); EXPECT_EQ(1UL, single_one->size()); Arity* single_two = empty->Extend(i2); EXPECT_EQ(1UL, single_two->size()); Arity* tuple2_1 = single_one->Extend(i2); Arity* tuple2_2 = single_two->Extend(i1); EXPECT_EQ(tuple2_1, tuple2_2); EXPECT_EQ(KArityPair(), tuple2_1); Arity* tuple3 = single_one->Extend(i3)->Extend(i2); EXPECT_EQ(Arity::GetTuple(3), tuple3); } TEST_F(ArityTest, Subtract) { Value i1 = Value::Integer(1); Value i2 = Value::Integer(2); Value i3 = Value::Integer(3); Value i4 = Value::Integer(4); EXPECT_EQ(Arity::GetTuple(3), Arity::GetTuple(4)->Subtract(i4)); EXPECT_EQ(Arity::Get(i2), KArityPair()->Subtract(i1)); EXPECT_EQ(Arity::Get(i3), Arity::GetTuple(3)->Subtract(i1)->Subtract(i2)); EXPECT_EQ(Arity::Get(i3), Arity::GetTuple(3)->Subtract(i2)->Subtract(i1)); EXPECT_EQ(KArityEmpty(), KArityPair()->Subtract(i2)->Subtract(i1)); } TEST_F(ArityTest, LessThan) { EXPECT_FALSE(KArityEmpty()->LessThan(KArityEmpty())); EXPECT_TRUE(KArityEmpty()->LessThan(KAritySingleton())); EXPECT_FALSE(KAritySingleton()->LessThan(KArityEmpty())); EXPECT_FALSE(KAritySingleton()->LessThan(KAritySingleton())); EXPECT_TRUE(KArityPair()->LessThan( Arity::GetTuple(3)->Subtract(Value::Integer(2)))); } TEST_F(ArityTest, SubsetMask) { Value i1 = Value::Integer(1); Value i2 = Value::Integer(2); Value i3 = Value::Integer(3); Value i4 = Value::Integer(4); EXPECT_TRUE(Equals( Value::Integer(0), Arity::GetTuple(10)->ComputeSubsetMask(&store_, KArityEmpty()))); EXPECT_TRUE(Equals( Value::Integer(1), Arity::GetTuple(10)->ComputeSubsetMask(&store_, KAritySingleton()))); EXPECT_TRUE(Equals( Value::Integer(1 | 2), Arity::GetTuple(10)->ComputeSubsetMask(&store_, KArityPair()))); EXPECT_TRUE(Equals( Value::Integer(0), KArityEmpty()->ComputeSubsetMask(&store_, KArityPair()))); EXPECT_TRUE(Equals( Value::Integer(1), KAritySingleton()->ComputeSubsetMask(&store_, KArityPair()))); EXPECT_TRUE(Equals( Value::Integer(2), Arity::Get(i1, i3)->ComputeSubsetMask(&store_, Arity::Get(i3)))); EXPECT_TRUE(Equals( Value::Integer(0), Arity::Get(i1, i3)->ComputeSubsetMask(&store_, Arity::Get(i4)))); EXPECT_TRUE(Equals( Value::Integer(4), Arity::Get(i1, i2, i4)->ComputeSubsetMask(&store_, Arity::Get(i4)))); } } // namespace store
Ruby
UTF-8
1,570
3.875
4
[]
no_license
require 'byebug' class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @game_over = false @sequence_length = 1 @seq = [] end def play until game_over take_turn end game_over_message reset_game end def take_turn show_sequence require_sequence unless @game_over @sequence_length += 1 round_success_message end end def show_sequence add_random_color puts "Sequence is: #{@seq.join(' ')}" sleep(2) system("clear") end def require_sequence guess = nil prompt_for_input until is_valid?(guess) puts "Invalid response. Try again with proper formatting." if guess guess = gets.chomp.split end @game_over = is_wrong?(guess) end def prompt_for_input puts "What was the sequence? Guess colors with spaces between each color." puts "For example: red blue blue green red yellow" end def is_wrong?(guess) guess != @seq end def is_valid?(sequence) return false unless sequence sequence.is_a?(Array) && sequence.all? { |color| COLORS.include?(color) } end def add_random_color @seq << COLORS.sample end def round_success_message puts "Correct! Your score is #{sequence_length} colors." end def game_over_message puts "Game over :( Sequence was #{@seq.join(' ')}." end def reset_game @game_over = false @sequence_length = 1 @seq = [] end end if __FILE__ == $PROGRAM_NAME simon = Simon.new simon.play end
Markdown
UTF-8
2,583
3
3
[ "Apache-2.0" ]
permissive
# S3 Storage This document covers the process of Monolith's S3 Storage module. ## Structure The following structure defines the flat module: ``` ├── __init__.py ├── bucket_manager.py ├── errors.py └── file_manager.py ``` The engine is stored in the ```__init__.py```. It's currently got a flat structure as there doesn't seem to be a need for complex design at this stage. If common patterns start to arise then developing a deeper structure can be explored. Right now the engine uses multiple inheritance. The two objects it inherits (file and bucket managers) are not tied. If the implementation of this module remains simple in the future with no need for more development, the file manager could simply inherit the bucker manager. However, if protocols such as back-up or migration are needed then this approach should be kept as these protocols can be defined in the engine. ## Use Below is an example of using the engine pickle a list, upload it, download it, and deserialise it for use: ```python from monolith_filemanager.s3storage import V1Engine import pickle test = V1Engine() bucket = 'demo-data.monolith' data = pickle.dumps([1, 2, 3]) test.upload_serialised_data(bucket_name=bucket, file_name="test-list.pkl", data=data) downloaded_data = test.download_file_to_memory(bucket_name=bucket, file_name="test-list.pkl") usable_data = pickle.loads(downloaded_data) ``` ## To Do Right now the standlone module works out of the box and can be used but below are some areas that could be developed: - **path protocols**: Right now the ```FileManager``` is merely holding ```self.BASE_DIR``` and ```self.FILE_PATH``` to manage the download to disk and upload from disk functions. Agreemet on disk upload/download protocols with defined paths should really be agreed on before this gets implemented. - **creating buckets**: The function for creating a bucket exists however, it complains about not defining a region. This bug fix isn't essential as I doubt that we have automated functions that are creating buckets right now, however, it should be fixed at some point. - **naming convention**: naming convention needs to be agreed on. Right now before uploading, the ```FileManager``` just uploads the name passed to it. When downloading it does the same. This doesn't affect the user interface and tells use where a file should be. However, there is a risk of versions getting in the way. It would be nice to agree on a naming protocol that indicates a version so this can be managed.
PHP
UTF-8
6,728
2.8125
3
[]
no_license
<?php namespace Application\Service; use Application\Entity\Book; use Application\Entity\User; use Application\Entity\BookIssue; class BookManager { /** * Doctrine entity manager. * @var Doctrine\ORM\EntityManager */ private $entityManager; // Constructor is used to inject dependencies into the service. public function __construct($entityManager) { $this->entityManager = $entityManager; } /** * Book issue * * @param type $bookIssueData */ public function bookIssue($bookIssueData) { $bookIssue = new BookIssue(); $bookIssue->userId = $bookIssueData['user_id']; $bookIssue->bookId = $bookIssueData['book_id']; $bookIssue->bookIssueDate = new \DateTime(); $bookIssue->bookReturnDate = NULL; $bookIssue->paidRent = 0.00; $this->entityManager->persist($bookIssue); $this->entityManager->flush(); } /** * Book return * * @param type $bookReturnData */ public function bookReturn($bookReturnData) { $amount = $this->getPaidRent($bookReturnData); $updateQueryBuilder = $this->entityManager->createQueryBuilder(); $update = $updateQueryBuilder->update(BookIssue::class, 'bi') ->set('bi.bookReturnDate', '?1') ->set('bi.paidRent', '?4') ->where('bi.userId = ?2') ->andWhere('bi.bookId = ?3') ->andWhere('bi.bookReturnDate IS NULL') ->setParameter(1, new \DateTime()) ->setParameter(2, $bookReturnData['user_id']) ->setParameter(3, $bookReturnData['book_id']) ->setParameter(4, $amount) ->getQuery(); $update->execute(); $this->entityManager->flush(); } /** * Total rent Paid */ public function getTotalRent() { $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select("SUM(bi.paidRent) as totalRentPaid") ->from(BookIssue::class, 'bi') ->where('bi.bookReturnDate IS NOT NULL'); $result = $queryBuilder->getQuery()->getOneOrNullResult(); return isset($result['totalRentPaid']) ? $result['totalRentPaid'] : 0; } /** * Get rent paid * * @param type $bookReturnData * @return type */ public function getPaidRent($bookReturnData) { $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select('bi.bookIssueDate') ->from(BookIssue::class, 'bi') ->where('bi.userId = ?1') ->andWhere('bi.bookId = ?2') ->andWhere('bi.bookReturnDate IS NULL') ->setParameter(1, $bookReturnData['user_id']) ->setParameter(2, $bookReturnData['book_id']); $result = $queryBuilder->getQuery()->getOneOrNullResult(); $issueDate = $result['bookIssueDate']->format('d-m-Y'); $currentDate = date("d-m-Y"); $diff = date_diff(date_create($issueDate), date_create($currentDate)); $amount = ($diff->format("%a") + 1) * 2; return $amount; } /** * Book issue on that day * * @param type $dateData * @return int */ public function bookIssuedOnDay($dateData) { $issuedBookDetail = []; $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select('b.id', 'b.name', 'u.username as personName') ->from(BookIssue::class, 'bi') ->join(Book::class, 'b', 'with', 'b.id = bi.bookId' ) ->join(User::class, 'u', 'with', 'u.userId = bi.userId' ) ->where('bi.bookIssueDate = ?1') ->setParameter('1', date_create($dateData)); $result = $queryBuilder->getQuery()->getResult(); foreach ($result as $key => $value) { $issuedBookDetail[$key] = $value; $issuedBookDetail[$key]['quantity'] = 1; } return $issuedBookDetail; } /** * Book returned on that day * * @param type $dateData * @return int */ public function bookReturnedOnDay($dateData) { $returnedBookDetail = []; $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select('b.id', 'b.name', 'u.username as personName') ->from(BookIssue::class, 'bi') ->join(Book::class, 'b', 'with', 'b.id = bi.bookId' ) ->join(User::class, 'u', 'with', 'u.userId = bi.userId' ) ->where('bi.bookReturnDate = ?1') ->setParameter('1', date_create($dateData)); $result = $queryBuilder->getQuery()->getResult(); foreach ($result as $key => $value) { $returnedBookDetail[$key] = $value; $returnedBookDetail[$key]['quantity'] = 1; } return $returnedBookDetail; } /** * Total Charge on the day * * @param type $dateData * @return type */ public function totalChargeOnDay($dateData) { $returnedBookDetail = []; $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select('SUM(bi.paidRent) as totalRentPaid') ->from(BookIssue::class, 'bi') ->where('bi.bookReturnDate = ?1') ->setParameter('1', date_create($dateData)); $result = $queryBuilder->getQuery()->getOneOrNullResult(); return !empty($result['totalRentPaid']) ? $result['totalRentPaid'] : 0; } /** * Number of book issued * * @param type $bookIssueData * @return type */ public function numberOfBookIssued($bookIssueData) { $queryBuilder = $this->entityManager->createQueryBuilder(); $queryBuilder->select('bi.id') ->from(BookIssue::class, 'bi') ->where('bi.userId = ?1') ->andWhere('bi.bookReturnDate IS NULL') ->setParameter('1', $bookIssueData['user_id']); $result = $queryBuilder->getQuery()->getResult(); return $result; } }
Markdown
UTF-8
6,023
2.921875
3
[]
no_license
# FPGA, ASIC et HDL [^fpga]: *Field Programmable Gate Array* [^asic]: *Application Specific Integrated Circuit* [^hdl]: *Hardware Description Language* Les circuits intégrés ont fait leur apparition dans les années 60, leur création ayant été rendue possible par les avancées dans le développement des matériaux semi-conducteurs et de leur utilisation en tant que tubes électroniques. Au fur et à mesure des avancées technologiques et de l'évolution des besoins en matière de puissance et d'énergie, il a fallu que les composants des différents systèmes deviennent le plus performant possible, afin d'accomplir les tâches auxquelles ils sont dédiés de manière rapide et optimisée. De l'idée de créer des composant dédiés à des types d'applications spécifiques sont nés, au cours des années 80, les ASIC. ## ASIC[^asic] Les ASIC\cite{Smith:1998:AIC:298606} (soit circuits intégrés pour applications) sont des circuits conçus spécifiquement pour un type d'application (c'est-à-dire d'utilisation). Ainsi, pour un type de produit, un design de circuit va être élaboré de manière à ce que celui-ci soit le plus performant possible vis-à-vis de son utilisation au sein du produit. Une fois ce design produit, on pourra créer une certaine quantité de circuits intégrés spécialisés pour l'utilisation que l'on veut en faire. Cette forme de circuit intégré a pour but de réduire grandement les coûts de production et d'augmenter la fiabilité et la performance de celui-ci pour le produit que l'on désire créer. Aussi, ce type de circuit est adapté aux situations où l'on désire produire un grand nombre d'instances de celui-ci. La fabrication d'un ASIC commence à la conception de son modèle. Après que l'on ai décidé de l'usage que la puce aura, sa structure et son comportement sont décrits grâce à un langage de description de matériel. Le modèle est ensuite envoyé en fonderie, où il peut passer plusieurs mois afin que son comportement soit gravé. Les inconvénients qui apparaissent sont leur fort coût d'élaboration, ainsi que le temps que celle-ci dure, nécessitant de devoir produire une très grande quantité de circuits afin que leur utilisation puisse être rentable. De plus, étant spécifiques à une application, les ASIC ne sont aucunement modifiables : on ne peut pas reprogrammer un ASIC après que le design de celui-ci a été implémenté. C'est pour répondre à des besoins auxquels les ASIC ne sont pas adaptés que les FPGA sont apparus. ## FPGA[^fpga] Un FPGA (soit matrice de portes logiques programmable) est un type de circuit intégré apparu au milieu des années 80 et dont la particularité est qu'il peut être utilisé pour plusieurs types d'application. À l'instar des ASIC, la programmation des FPGA est faite avec un HDL, qui permet de décrire le comportement du circuit. Cependant, les FPGA sont conçus de manière à pouvoir être reprogrammés. On peut en effet "flasher" ceux-ci afin d'en modifier le comportement et ainsi ceux-ci ne sont pas limités à une utilisation. La modification possible de l'application pour un FPGA en fatt de solides concurrents aux ASIC, surtout dans les domaines où ceux-là n'excellent pas. En particulier, le coût de design d'un FPGA est moindre par rapport à celui d'un ASIC et l'on peut les utiliser pour plusieurs types d'applications. Cela en fait une bonne option pour, par exemple, l'expérimentation et les prototypes, ou bien la fabrication de produits lorsqu'il ne s'agit pas d'en fabriquer un grand nombre et qu'il faut y avoir accès rapidement. Au vu de leur adaptabilité, leur coût de conception réduit et leur vitesse de fabrication et disponibilité, on peut se demander pourquoi les FPGA ne sont pas utilisés pour tous types d'applications. Aujourd'hui, la performance des FPGA reste limitée par rapport à celle des ASIC. C'est pourquoi ces derniers restent le choix optimal pour les projets conséquents. ## HDL[^hdl] Les circuits intégrés cités précédemment cités sont programmés à l'aide d'un HDL, à savoir un langage de description de matériel. Ceux-ci sont des langages informatiques décrivant le comportement d'un circuit électronique, ou bien les portes logiques utilisées par celui-ci. Un langage de description matérielle permet donc, en outre : - de décrire le fonctionnement d'un circuit - de décrire la structure d'un circuit - de vérifier la fonctionnalité d'un circuit, par simulation Les principaux langages de description sont SystemC, Verilog et VHDL. Ce dernier, créé en 1981 par le Département de la Défense des États-Unis, peut décrire le comportement d'une puce, qui sera interprété par des outils de synthèse logique. Un exemple de programme en VHDL\cite{vhdl-edu} ressemblerait à ceci : ```vhdl -- Chargement des bibliothèques utilisées library ieee use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; -- Description d'une entité (entrées/sorties) entity exemple is port(a , b : in std_logic_vector(3 downto 0); op, clk, reset : in std_logic; c : out std_logic_vector(3 downto 0)); end exemple; -- Architecture (ensemble de processus) -- processus internes architecture test of exemple is signal moinsb, opb, aopb : std_logic_vector(3 downto 0); begin moinsb <= not b + "0001" opb <= b when op='0' else moins; aopb <= a + opb; -- processus externes process (reset, clk) begin if reset='0' then c <= "0000"; else if (clk'event and clk='1') then c <= aopb; end if; end if; end process; end test; ``` En VHDL, les entrées/sorties sont les *ports* de l'entité. Chaque composant interne est un *processus* de l'architecture et ceux-ci s'exécutent en parallèle. La transformation d'un langage de description en un schéma en porte logique, qui permet la description du comportement et de la structure d'un circuit, est possible grâce à la synthèse logique. \newpage
C++
UTF-8
3,033
2.59375
3
[]
no_license
/* * Set to 1 if you want to run this sketch. Other RUNNING macros should then be * set to 0 in order prevent multiple definitions of setup and loop. */ #define RUNNING 0 #if RUNNING #include <CurieBLE.h> #include "/../SolarTracking.h" /* * Sketch to test Bluetooth connectivity from the Arduino 101 to any peripheral * devices. In this test, the value of the NW LDR sensor is read and outputted. * If a peripheral device is connected to the Arduino 101, then this device will * be able to read the nw_ldr_char and see how it periodically changes. * * AUTHOR: * Nikola Istvanic */ BLEPeripheral blep; BLEService st = BLEService("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); BLEUnsignedCharCharacteristic nw_ldr_char( "6E400002-B5A3-F393-E0A9-E50E24DCCA9E", BLERead | BLEWrite | BLENotify); BLEDescriptor nw_descriptor = BLEDescriptor("2901", "NW Reading Percentage"); u_int8_t nw = 0; // last NW LDR reading as a percentage void update_ldr_reading(u_int16_t new_reading) { u_int8_t curr_reading = map(new_reading, 0, 1023, 0, 100); /* Update Bluetooth characteristic value only when necessary */ if (curr_reading != nw) { Serial.print("\n***\n*** Updating LDR reading in "); Serial.print((sensor) 0); Serial.print(" LDR to "); Serial.print(curr_reading); Serial.println("\n***"); nw_ldr_char.setValue(curr_reading); nw = curr_reading; } } void setup() { Serial.end(); delay(100); Serial.begin(9600); /* Setup BLE */ blep.setLocalName("Helios Panel"); blep.setAdvertisedServiceUuid(st.uuid()); blep.addAttribute(st); blep.addAttribute(nw_ldr_char); blep.addAttribute(nw_descriptor); /* Initialize Bluetooth Characteristic value */ nw_ldr_char.setValue(0); blep.begin(); Serial.println("\n***\n*** Bluetooth system activated, awaiting peripheral " "connection\n***"); } void loop() { /* Listen for BLE central (non-server) to connect to */ BLECentral central = blep.central(); u_int16_t nw_current_reading = read_ldr((sensor) 0); /* If connected to a central device */ if (central) { Serial.print( "\n***\n*** Bluetooth peripheral device connected. MAC address: "); Serial.print(central.address()); Serial.println("\n***"); /* While connected to a device, update its NW LDR measurement */ while (central.connected()) { update_ldr_reading(nw_current_reading); delay(READ_DELAY); } /* Disconnected */ Serial.print("\n***\n*** Disconnected from central device: "); Serial.print(central.address()); Serial.println("\n***"); } else { /* Run like normal if not connected, don't update characterisic value */ Serial.print("\n***\n*** LDR reading in "); Serial.print((sensor) 0); Serial.print(": "); Serial.print(nw_current_reading); Serial.println("\n***"); delay(READ_DELAY); } } #endif
Python
UTF-8
1,126
2.78125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Created on Thu Feb 21 17:20:50 2019 @author: Jason @e-mail: jasoncoding13@gmail.com """ import os import scrapy class ExampleSpider(scrapy.Spider): name = 'example' start_urls = [ 'https://web.timetable.usyd.edu.au/menu.jsp?siteMap=true' ] custom_settings = { 'ROBOTSTXT_OBEY': False} def __init__(self): # Count the number of pages crawled. self.num = 0 # Regenerate the file items.json. if os.path.isfile('./items.json'): os.remove('./items.json') def parse(self, response): for a in response.css('li.siteMapItem a'): yield { (str(self.num)): a.css('::text').get(), } self.num += 1 # Note that the next page is the same as the initial page. # Demonstrate it can follow the link to the next page. # Actually crawl the initial page twice. next_page = response.css('td.footer a::attr("href")').get() if next_page is not None and self.num < 2: yield response.follow(next_page, self.parse)
JavaScript
UTF-8
2,622
3.1875
3
[]
no_license
document.addEventListener("DOMContentLoaded", function(event) { var allCardsHtml = document.getElementById("stacks-template").innerHTML; var cardHtml = document.getElementById("addStack-template").innerHTML; var newCardHtml = document.getElementById("addNewStack-template").innerHTML; var HandlebarsStacksTemplate = Handlebars.compile(allCardsHtml); var HandlebarsCardTemplate = Handlebars.compile(cardHtml); var HandlebarsNewCardTemplate = Handlebars.compile(newCardHtml); // Fetch Stacks from api and assign them to a handlebars template fetch('./webapi/stacks/getAllStacks') .then( function (response) { if (response.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + response.status); return; } response.json().then(function (data) { document.getElementsByClassName("stackContainer")[0].innerHTML = HandlebarsStacksTemplate(data); document.querySelector(".addNewStack button").addEventListener('click', function(e) { postNewStack(document.querySelector(".addNewStack input").value) }) }); } ) .catch(function(err) { console.log('Fetch Error :-S', err); }); //Post data to server function postNewStack(newStackname) { this.newStackname = newStackname; fetch('./webapi/stacks/addStack', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({'stackname': this.newStackname}) }) .then(res => res.json()) .then(function (data) { var newCardData = { "stackid": data, "stackname": this.newStackname, "cardCount": 0 } var my_elem = document.getElementsByClassName('addNewStack')[0]; var newCard = document.createElement('span'); newCard.innerHTML = HandlebarsCardTemplate(newCardData); my_elem.parentNode.insertBefore(newCard, my_elem); document.querySelector(".addNewStack input").value = ""; console.log('Request succeeded with JSON response', data); }) .catch(function (error) { console.log('Request failed', error); }); } });
Shell
UTF-8
1,185
3.21875
3
[]
no_license
#!/bin/bash for c in inp sch exe out do for s in 250 500 1000 do for a in 1 2 4 8 do for w in 1 2 4 8 do f="sids/$c.$s.$a.$w.sids" grep "$c : $s : 0 : $a : $w : " experiment.sids > $f test -s $f || rm -f $f done done for r in bw comet stampede do f="sids/$c.$s.$r.sids" grep "$c : $s : " experiment.sids | grep $r > $f test -s $f || rm -f $f done done done export TIMEFORMAT="r:%lR u:%lU s:%lS" unset `env | grep VERBOSE | cut -f 1 -d =` rm -f plot_all.lst touch plot_all.lst for sid in sids/*.sids do old_len=0 new_len=`wc -l $sid | cut -f 1 -d ' '` touch "$sid.len" old_len=`cat "$sid.len"` if test "$old_len" = "$new_len" then printf "======= %2d == %2d : $sid\n" $new_len $old_len continue else printf "======= %2d != %2d : $sid\n" $new_len $old_len echo $sid >> plot_all.lst echo "$new_len" > $sid.len fi done cat plot_all.lst echo "plotting `wc -l plot_all.lst | cut -f 1 -d ' '` sids" time parallel ./plot.py < plot_all.lst
Java
UTF-8
1,824
3
3
[]
no_license
package com.other; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class TestMultiThread { // private final Queue<Integer> indexlDs = new LinkedList<>(); private final Stack<Integer> indexlDs = new Stack<>(); public void th(){ for( int i = 0 ; i < 10000; i++){ indexlDs.add(i); } new Thread(() ->{ for( int i = 10000 ; i < 1000000; i++){ indexlDs.add(i); } }).start(); new Thread(() ->{ System.out.println(indexlDs.size()); List<Integer> ids = new ArrayList<>(); while (!indexlDs.isEmpty()) { ids.add(indexlDs.pop()); } }).start(); // new Thread(() ->{ // while (!indexlDs.isEmpty()) { // try { // Integer id = indexlDs.poll(); // if (id != null) { // System.out.println(Thread.currentThread().getName() + "indexing chemical product " + id); // } // } catch (EmptyStackException e) { // e.printStackTrace(); // } // } // }).start(); // new Thread(() ->{ // while (!indexlDs.isEmpty()) { // try { // Integer id = indexlDs.poll(); // if (id != null) { // System.out.println(Thread.currentThread().getName() + "indexing chemical product " + id); // } // } catch (EmptyStackException e) { // e.printStackTrace(); // } // } // }).start(); } public static void main(String[] args) { new TestMultiThread().th(); } }
C++
UTF-8
2,305
2.53125
3
[]
no_license
#include "step.hh" namespace Dune { namespace Mock { void Step::init(Vector& x, Vector& b) { x0 = x; b0 = b; wasInitialized = true; } void Step::reset(Vector& x, Vector& b) { x0 = x; b0 = b; wasReset = true; } void Step::compute(Vector& x, Vector& b) { x0 += b0; } Vector Step::getFinalIterate() { return x0; } double Step::residualNorm() const { return residualNorm_; } double Step::preconditionedResidualNorm() const { return preconditionedResidualNorm_; } double Step::alpha() const { return alpha_; } double Step::length() const { return length_; } void Step::postProcess(Vector&) {} std::string Step::name() const { return "dummy step"; } RestartingStep::RestartingStep(bool restart) : doRestart(restart) {} void RestartingStep::init(Vector& x, Vector& b) { x0 = x; b0 = b; wasInitialized = true; } void RestartingStep::reset(Vector& x, Vector& b) { x0 = x; b0 = b; wasReset = true; } void RestartingStep::compute(Vector& x, Vector& b) { x0 += b0; } bool RestartingStep::terminate() const { return doTerminate && wasReset; } bool RestartingStep::restart() const { doTerminate = true; return doRestart; } Vector RestartingStep::getFinalIterate() { return x0; } void RestartingStep::postProcess(Vector&) {} std::string RestartingStep::name() const { return "dummy step"; } void TerminatingStep::init(Vector& x, Vector& b) { x0 = x; b0 = b; wasInitialized = true; } void TerminatingStep::reset(Vector& x, Vector& b) { x0 = x; b0 = b; wasReset = true; } void TerminatingStep::compute(Vector& x, Vector& b) { x0 += b0; } Vector TerminatingStep::getFinalIterate() { return x0; } void TerminatingStep::postProcess(Vector&) {} std::string TerminatingStep::name() const { return "dummy step"; } bool TerminatingStep::terminate() const { return doTerminate; } } }
C++
UTF-8
4,837
2.984375
3
[]
no_license
#include <iostream> #include <ctime> #include <deque> #include <pthread.h> using namespace std; enum kierunek { polnoc = 0, wschod = 1, poludnie = 2, zachod = 3 }; class Punkt { public: int x; int y; Punkt(){ x = y = 0; } Punkt(int x, int y){ this->x = x; this->y = y; } }; const int rozmiar = 201; char grid[rozmiar*rozmiar]; unsigned char labirynt[rozmiar][rozmiar][3]; int labirynt2D[rozmiar][rozmiar]; pthread_mutex_t tab_muteksow[rozmiar][rozmiar]; void *rysuj(void *arg){ deque<Punkt*> otoczenie; deque<pthread_t> watki; Punkt *dane = (Punkt*)arg; int x = dane->x; int y = dane->y; pthread_t id = pthread_self(); bool flaga = false; do { flaga = false; pthread_mutex_lock(&tab_muteksow[x][y]); labirynt2D[x][y] = id; pthread_mutex_unlock(&tab_muteksow[x][y]); for(int i = -1; i < 2; i += 2){ pthread_mutex_lock(&tab_muteksow[x+i][y]); if(labirynt2D[x+i][y] == 0){ Punkt *p = new Punkt(x+i, y); otoczenie.push_back(p); } pthread_mutex_unlock(&tab_muteksow[x+i][y]); pthread_mutex_lock(&tab_muteksow[x][y+i]); if(labirynt2D[x][y+i] == 0){ Punkt *p = new Punkt(x, y+i); otoczenie.push_back(p); } pthread_mutex_unlock(&tab_muteksow[x][y+i]); } if(otoczenie.size() >= 1){ flaga = true; Punkt *p = otoczenie.front(); otoczenie.pop_front(); x = p->x; y = p->y; for(int i = 0; otoczenie.size() > 0; i++){ pthread_t watek; pthread_create(&watek, NULL, rysuj, otoczenie.front()); otoczenie.pop_front(); watki.push_front(watek); } otoczenie.clear(); } }while(flaga); for(int i = 0; watki.size() > 0; i++){ pthread_join(watki.front(), NULL); watki.pop_front(); } watki.clear(); pthread_exit(NULL); } void ResetGrid(){ for (int i=0; i < rozmiar*rozmiar; i++){ grid[i] = '#'; } } long XYToIndex( long x, long y ){ return y * rozmiar + x; } int IsInBounds( int x, int y ){ if (x < 0 || x >= rozmiar - 1) return false; if (y <0 || y >= rozmiar - 1) return false; return true; } void Visit( int x, int y ){ grid[ XYToIndex(x,y) ] = ' '; int dirs[4]; dirs[0] = kierunek(polnoc); dirs[1] = kierunek(wschod); dirs[2] = kierunek(poludnie); dirs[3] = kierunek(zachod); for (int i=0; i<4; ++i){ int r = rand() & 3; int temp = dirs[r]; dirs[r] = dirs[i]; dirs[i] = temp; } for (int i=0; i<4; ++i){ int dx=0, dy=0; switch (dirs[i]){ case kierunek(polnoc): dy = -1; break; case kierunek(poludnie): dy = 1; break; case kierunek(wschod): dx = 1; break; case kierunek(zachod): dx = -1; break; } int x2 = x + (dx<<1); int y2 = y + (dy<<1); if (IsInBounds(x2,y2)){ if (grid[ XYToIndex(x2,y2) ] == '#'){ grid[ XYToIndex(x2-dx,y2-dy) ] = ' '; Visit(x2,y2); } } } } void PrintGrid(){ for (int x=0; x<rozmiar; ++x){ for (int y=0; y<rozmiar; ++y){ if(grid[XYToIndex(x,y)] == '#'){ labirynt2D[x][y] = -1; } else{ labirynt2D[x][y] = 0; } } } } int main(){ for(int i = 0; i < rozmiar; i++){ for(int j = 0; j < rozmiar; j++){ tab_muteksow[i][j] = PTHREAD_MUTEX_INITIALIZER; } } srand( time(NULL) ); ResetGrid(); Visit(1,1); PrintGrid(); Punkt p(1,1); pthread_t watek; pthread_create(&watek, NULL, rysuj, &p); pthread_join(watek, NULL); FILE *fptr = fopen("labirynt.ppm", "wb"); fprintf(fptr,"P6\n %s\n %d\n %d\n %d\n", "# ", rozmiar, rozmiar, 255); for(int i = 0; i < rozmiar; i++){ for(int j = 0; j < rozmiar; j++){ if(labirynt2D[i][j] == -1){ for(int k = 0; k < 3; k++){ labirynt[i][j][k] = 0; } } else{ int klr = labirynt2D[i][j]; unsigned char r = (klr) % 255; klr = klr + 100; unsigned char g = (klr) % 255; klr = klr + 100; unsigned char b = (klr) % 255; labirynt[i][j][0] = r; labirynt[i][j][1] = g; labirynt[i][j][2] = b; } } } fwrite(labirynt, 1 ,3*rozmiar*rozmiar, fptr); fclose(fptr); }
Java
UTF-8
3,798
2.234375
2
[]
no_license
package io.rong.push.common; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Parcelable; import android.os.Process; import android.util.Log; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; public class RLog { static final boolean DEBUG = true; private static String FILE_NAME = "PushLog.txt"; private static Boolean IS_WRITE_TO_FILE = Boolean.valueOf(true); private static int LOG_FILE_SAVE_DAYS = 1; private static String LOG_PATH = "/sdcard/"; private static String RongLog = "RongLog-Push"; private static SimpleDateFormat fileNameFormat = new SimpleDateFormat("yyyy-MM-dd"); private static SimpleDateFormat logFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /* renamed from: i */ public static void m8382i(String str, String str2) { log(str, str2, 'i'); } /* renamed from: v */ public static void m8383v(String str, String str2) { log(str, str2, 'v'); } /* renamed from: d */ public static void m8380d(String str, String str2) { log(str, str2, 'd'); } /* renamed from: e */ public static void m8381e(String str, String str2) { log(str, str2, 'e'); } private static void log(String str, String str2, char c) { String str3 = RongLog + "[" + str + "]"; if ('e' == c) { Log.e(str3, str2); } else if ('w' == c) { Log.w(str3, str2); } else if ('d' == c) { Log.d(str3, str2); } else if ('i' == c) { Log.i(str3, str2); } else { Log.v(str3, str2); } } private static void writeLogtoFile(String str, String str2, String str3) { Date date = new Date(); String format = fileNameFormat.format(date); String str4 = logFormat.format(date) + " " + str + " " + Process.myPid() + " " + str2 + " " + str3; File file = new File(LOG_PATH, format + FILE_NAME); delFile(); try { Writer fileWriter = new FileWriter(file, true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(str4); bufferedWriter.newLine(); bufferedWriter.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public static void delFile() { File file = new File(LOG_PATH, fileNameFormat.format(getDateBefore()) + FILE_NAME); if (file.exists()) { file.delete(); } } private static Date getDateBefore() { Date date = new Date(); Calendar instance = Calendar.getInstance(); instance.setTime(date); instance.set(5, instance.get(5) - LOG_FILE_SAVE_DAYS); return instance.getTime(); } public static void sendLog(Context context, List<String> list) { Parcelable fromFile; try { fromFile = Uri.fromFile(new File(LOG_PATH, fileNameFormat.format(new Date()) + FILE_NAME)); } catch (Exception e) { e.printStackTrace(); fromFile = null; } if (fromFile != null) { Intent intent = new Intent("android.intent.action.SEND"); intent.setType("message/rfc822"); intent.putExtra("android.intent.extra.EMAIL", list.toArray()); intent.putExtra("android.intent.extra.SUBJECT", "RongCloud log"); intent.putExtra("android.intent.extra.STREAM", fromFile); context.startActivity(intent); } } }
C++
UTF-8
4,062
2.59375
3
[]
no_license
#pragma once #include <QString> //------------------------------------------------------------------------------ // PlayerPosition // TODO: Just use a bitfield here... //------------------------------------------------------------------------------ enum class PlayerPosition { None, Catcher, First, Second, SS, Third, Outfield, DH, Pitcher, MiddleInfield, CornerInfield, Utility, Starter, Relief, COUNT, }; using PlayerPositionBitfield = uint32_t; inline PlayerPositionBitfield ToBitfield(const PlayerPosition& position) { return 1 << PlayerPositionBitfield(position); } inline PlayerPositionBitfield ToBitfield(const std::initializer_list<PlayerPosition>& positions) { PlayerPositionBitfield bitfield = 0; for (auto& position : positions) { bitfield |= (1 << PlayerPositionBitfield(position)); } return bitfield; } inline PlayerPositionBitfield AddFauxPositions(const PlayerPositionBitfield& positions) { PlayerPositionBitfield ret = positions; if (positions & ToBitfield(PlayerPosition::SS) || positions & ToBitfield(PlayerPosition::Second)) { ret |= ToBitfield(PlayerPosition::MiddleInfield); } if (positions & ToBitfield(PlayerPosition::First) || positions & ToBitfield(PlayerPosition::Third)) { ret |= ToBitfield(PlayerPosition::CornerInfield); } if (positions & ToBitfield(PlayerPosition::Catcher) || positions & ToBitfield(PlayerPosition::First) || positions & ToBitfield(PlayerPosition::Second) || positions & ToBitfield(PlayerPosition::SS) || positions & ToBitfield(PlayerPosition::Third) || positions & ToBitfield(PlayerPosition::Outfield)) { ret |= ToBitfield(PlayerPosition::Utility); } return ret; } //------------------------------------------------------------------------------ // Player //------------------------------------------------------------------------------ struct Player { enum Catergory { Hitter = 1 << 1, Pitcher = 1 << 2, }; // CatergoryMask using CatergoryMask = uint32_t; enum Flag { FLAG_NONE, FLAG_STAR, FLAG_WATCH, FLAG_AVOID, FLAG_COUNT, }; // User flag uint32_t flag = FLAG_NONE; // Player data uint32_t index; QString id; // player id QString name; QString team; // TODO: change to ID uint32_t age = 0; uint32_t experience = 0; CatergoryMask catergory; PlayerPositionBitfield eligiblePositionBitfield = uint32_t(0); // Fantasy int32_t ownerId = 0; float paid = 0; PlayerPosition draftPosition = PlayerPosition::None; // Cost estimate category uint32_t categoryRank = 0; float zScoreBonus = 0; float zScore = 0; float cost = 0; // Hitting stats struct HittingStats { // sub-stat uint32_t PA = 0; uint32_t AB = 0; uint32_t H = 0; // core stats float AVG = 0; uint32_t R = 0; uint32_t RBI = 0; uint32_t HR = 0; uint32_t SB = 0; // zScores float zAVG = 0; float zR = 0; float zHR = 0; float zRBI = 0; float zSB = 0; // weighted zScores float wAVG = 0; // SPG float spgAVG = 0; float spgR = 0; float spgHR = 0; float spgRBI = 0; float spgSB = 0; } hitting; // Pitching stats struct PitchingStats { // Stats float IP = 0; float ER = 0; uint32_t H = 0; uint32_t BB = 0; uint32_t SO = 0; uint32_t W = 0; uint32_t SV = 0; float ERA = 0; float WHIP = 0; // zScores float zSO = 0; float zW = 0; float zSV = 0; float zERA = 0; float zWHIP = 0; // weighted score float wERA = 0; float wWHIP = 0; } pitching; // Comment QString comment; };
Python
UTF-8
139
3.0625
3
[]
no_license
def on_square(squareNb): return 2 ** (squareNb - 1) def total_after(squareNb): return sum(2 ** i for i in range (0 , squareNb) )
Java
UTF-8
1,456
4
4
[]
no_license
package com.arrays; /** * 测试数组的拷贝 * @author Administrator * */ public class TestArrayCopy { public static void main(String[] args) { testBasicCopy(); testDelByCopy(); String[] s = {"a","b","c","d","e"}; s = removeElement(s, 1); s = extendArray(s); for(int i=0; i<s.length; i++){ System.out.println(i+"---"+s[i]); } } /** * 数组拷贝的基本方法 */ public static void testBasicCopy(){ String[] s1 = {"aa","bb","cc","dd","ee"}; String[] s2 = new String[10]; System.arraycopy(s1, 2, s2, 6, 3); for(int i=0; i<s2.length; i++){ System.out.println(i+"---"+s2[i]); } } /** * 通过数组拷贝实现删除 */ public static void testDelByCopy(){ String[] s1 = {"aa","bb","cc","dd","ee"}; System.arraycopy(s1, 3, s1, 3-1, s1.length-3); s1[s1.length -1] = null; for(int i=0; i<s1.length; i++){ System.out.println(i+"---"+s1[i]); } } /** * 删除数组中的一个元素 * @param s * @param index * @return */ public static String[] removeElement(String[] s,int index){ System.arraycopy(s, index+1, s, index, s.length-index-1); s[s.length -1] = null; return s; } public static String[] extendArray(String[] array){ String[] newArray = new String[array.length * 2]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; } }
Python
UTF-8
882
3.8125
4
[]
no_license
#Intro to strings my_name="bibek" my_newname="bibek1" print(f"my name is : {my_name} \nmy new name is : {my_newname}") space="" space1=" " print(f"{bool(space)}") print(f"{bool(space1)}") my_fav_script="python scripting" print(my_fav_script) print(my_fav_script[0]) print(my_fav_script[5]) print(my_fav_script[5]) print(my_fav_script[-1]) print(my_fav_script[5]) print(my_fav_script[0:5]) #prints character from 0 to 4 print(my_fav_script[0:]) #prints 0 to last print(my_fav_script[:5]) #prints character from 0 to 4 print(my_fav_script[4:11]) #strings are immutable.. That means u cant delete or assign part of the string. #length of the string mystringlen=len(my_fav_script) print(f"length of the given string is : {len(my_fav_script)}") print(my_fav_script[-16:-5]) test1="bibek" test2="mohanty" space=" " add_test=test1+" "+test2+space +"is very handsome" print(add_test)
Ruby
UTF-8
1,191
2.53125
3
[]
no_license
class Feed < ActiveRecord::Base has_many :items, :order => "id DESC" has_many :feed_tags has_many :tags, :through => :feed_tags def self.find_all_with_unread #fields = self.columns.map {|f| "f." + f.name }.join(",") #self.find_by_sql("SELECT #{fields}, COUNT(i.id)-SUM(i.seen) AS unread FROM feeds f, items i WHERE i.feed_id=f.id GROUP BY #{fields} ORDER BY f.id") #self.find_by_sql("SELECT #{fields}, COUNT(i.id) AS unread FROM feeds f, items i WHERE i.feed_id=f.id AND i.seen IS NULL GROUP BY #{fields} ORDER BY f.id") self.find(:all, :conditions => ["unread > 0"], :order => :id) end def unread_items Item.find_all_by_feed_id_and_seen(self.id, nil, :order => "id DESC") end def mark_as_read(item_id = nil) if (item_id) connection.update("UPDATE items SET seen=1 WHERE feed_id=#{self.id} AND seen IS NULL AND id >= #{item_id}") else connection.update("UPDATE items SET seen=1 WHERE feed_id=#{self.id} AND seen IS NULL") end update_unread end def update_unread unread = Item.where(:feed_id => self.id, :seen => nil).size puts "unread = #{unread}" self.unread = unread self.save! end end
Rust
UTF-8
23,119
3.015625
3
[]
no_license
use eetf::Term; use std::io::{self, Read}; use std::iter; use std::str; use heck::CamelCase; use num_traits::cast::{FromPrimitive, ToPrimitive}; use serde::de::{ self, DeserializeOwned, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor, }; use crate::error::{Error, Result}; use self::private::*; /// Deserializes an `eetf::Term` /// /// Generally you should use the from_bytes or from_reader functions instead. pub struct Deserializer<'a> { term: &'a Term, } impl<'a> Deserializer<'a> { pub fn from_term(term: &'a Term) -> Self { Deserializer { term } } } trait IntoEetfDeserializer { fn into_deserializer(&self) -> Deserializer; } impl IntoEetfDeserializer for Term { fn into_deserializer(&self) -> Deserializer { Deserializer::from_term(self) } } // impl<'de, 'a: 'de> From<&'a Term> for Deserializer<'de> { // fn from(term: &'a Term) -> Self { // Deserializer::from_term(term) // } // } /// Deserializes some EETF from a Read pub fn from_reader<R, T>(reader: R) -> Result<T> where R: Read, T: DeserializeOwned, { let term = Term::decode(reader)?; let deserializer = Deserializer::from_term(&term); let t = T::deserialize(deserializer)?; Ok(t) } /// Deserializes some EETF from a slice of bytes. pub fn from_bytes<T>(bytes: &[u8]) -> Result<T> where T: DeserializeOwned, { let cursor = io::Cursor::new(bytes); from_reader(cursor) } // Implementation methods for deserializer that require a lifetime. impl<'a> Deserializer<'a> { fn parse_integer<T>(&self) -> Result<T> where T: FromPrimitive, { match self.term { Term::FixInteger(fix_int) => { if let Some(num) = T::from_i32(fix_int.value) { Ok(num) } else { Err(Error::IntegerConvertError) } } Term::BigInteger(big_int) => { if let Some(num) = big_int.to_i64() { if let Some(num) = T::from_i64(num) { Ok(num) } else { Err(Error::IntegerConvertError) } } else { Err(Error::IntegerConvertError) } } _ => Err(Error::ExpectedFixInteger), } } fn parse_float<T>(&self) -> Result<T> where T: FromPrimitive, { match self.term { Term::Float(float) => { if let Some(num) = T::from_f64(float.value) { Ok(num) } else { Err(Error::IntegerConvertError) } } _ => Err(Error::ExpectedFloat), } } fn parse_binary(&self) -> Result<&[u8]> { match self.term { Term::Binary(binary) => Ok(&binary.bytes), _ => Err(Error::ExpectedBinary), } } fn parse_string(&self) -> Result<String> { match self.parse_binary() { Ok(bytes) => str::from_utf8(&bytes) .map(|s| s.to_string()) .or(Err(Error::Utf8DecodeError)), Err(e) => Err(e), } } } impl<'de, 'a: 'de> de::Deserializer<'de> for Deserializer<'a> { type Error = Error; fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value> where V: Visitor<'de>, { Err(Error::TypeHintsRequired) } fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Atom(b) => { if b.name == "true" { visitor.visit_bool(true) } else if b.name == "false" { visitor.visit_bool(false) } else { Err(Error::InvalidBoolean) } } _ => Err(Error::ExpectedBoolean), } } fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_i8(self.parse_integer()?) } fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_i16(self.parse_integer()?) } fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_i32(self.parse_integer()?) } fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_i64(self.parse_integer()?) } fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_u8(self.parse_integer()?) } fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_u16(self.parse_integer()?) } fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_u32(self.parse_integer()?) } fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_u64(self.parse_integer()?) } fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_f32(self.parse_float()?) } fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_f64(self.parse_float()?) } fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.parse_string() { Err(Error::ExpectedBinary) => Err(Error::ExpectedChar), Err(other) => Err(other), Ok(string) => { if string.len() == 1 { visitor.visit_char(string.chars().next().unwrap()) } else { Err(Error::ExpectedChar) } } } } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_string(self.parse_string()?) } fn deserialize_string<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { self.deserialize_str(visitor) } fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_bytes(self.parse_binary()?) } fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_bytes(self.parse_binary()?) } fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Atom(atom) => { if atom.name == "nil" { visitor.visit_none() } else { visitor.visit_some(self) } } _ => visitor.visit_some(self), } } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Atom(atom) => { if atom.name == "nil" { visitor.visit_unit() } else { Err(Error::ExpectedNil) } } _ => Err(Error::ExpectedNil), } } fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { self.deserialize_unit(visitor) } fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { visitor.visit_newtype_struct(self) } // Deserialization of compound types like sequences and maps happens by // passing the visitor an "Access" object that gives it the ability to // iterate through the data contained in the sequence. fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::List(list) => { let seq_deserializer = ListDeserializer::new(list.elements.iter()); visitor.visit_seq(seq_deserializer) // TODO: Figure out how to call end here. } other => { eprintln!("{}", other); Err(Error::ExpectedList) } } } fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Tuple(tuple) => { if tuple.elements.len() != len { return Err(Error::WrongTupleLength); } let seq_deserializer = ListDeserializer::new(tuple.elements.iter()); visitor.visit_seq(seq_deserializer) // TODO: Figure out how to call end here. } _ => Err(Error::ExpectedTuple), } } // Tuple structs look just like tuples in EETF. fn deserialize_tuple_struct<V>( self, _name: &'static str, len: usize, visitor: V, ) -> Result<V::Value> where V: Visitor<'de>, { self.deserialize_tuple(len, visitor) } fn deserialize_map<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Map(map) => { let mut map_deserializer = MapDeserializer::new(map.entries.iter()); visitor.visit_map(&mut map_deserializer).and_then(|result| { match map_deserializer.end() { Ok(()) => Ok(result), Err(e) => Err(e), } }) } _ => Err(Error::ExpectedMap), } } fn deserialize_struct<V>( self, _name: &'static str, _fields: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Map(map) => { let mut map_deserializer = MapDeserializer::new(map.entries.iter()); visitor.visit_map(&mut map_deserializer).and_then(|result| { match map_deserializer.end() { Ok(()) => Ok(result), Err(e) => Err(e), } }) } _ => Err(Error::ExpectedMap), } } fn deserialize_enum<V>( self, _name: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Atom(atom) => { // We have a unit variant. visitor.visit_enum(atom.name.to_camel_case().into_deserializer()) } Term::Tuple(tuple) => match tuple.elements.as_slice() { [variant_term, value_term] => { visitor.visit_enum(EnumDeserializer::new(&variant_term, &value_term)) } _ => Err(Error::MisSizedVariantTuple), }, _ => Err(Error::ExpectedAtomOrTuple), } } fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Atom(atom) => visitor.visit_string(atom.name.clone()), _ => Err(Error::ExpectedAtom), } } fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { // Just skip over this by calling visit_unit. visitor.visit_unit() } } struct ListDeserializer<I> where I: Iterator, { iter: iter::Fuse<I>, } impl<I> ListDeserializer<I> where I: Iterator, { fn new(iter: I) -> Self { ListDeserializer { iter: iter.fuse() } } } impl<'de, 'a: 'de, I> SeqAccess<'de> for ListDeserializer<I> where I: Iterator<Item = &'a Term>, { type Error = Error; fn next_element_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>> where V: de::DeserializeSeed<'de>, { match self.iter.next() { Some(term) => seed.deserialize(Deserializer::from_term(term)).map(Some), None => Ok(None), } } } // TODO: Look at https://github.com/flavray/avro-rs/blob/master/src/de.rs#L50-L53 // and figure out if we can use it's ideas to simplify all this lifetime shit. struct MapDeserializer<'de, I, T> where I: Iterator<Item = T>, T: Pair<'de> + 'de, First<'de, I::Item>: 'de, Second<'de, I::Item>: 'de, { items: iter::Fuse<I>, current_value: Option<&'de T::Second>, } impl<'de, I, T> MapDeserializer<'de, I, T> where I: Iterator<Item = T>, T: Pair<'de>, { fn new(iter: I) -> Self { MapDeserializer { items: iter.fuse(), current_value: None, } } fn end(self) -> Result<()> { if self.items.count() == 0 { Ok(()) } else { Err(Error::TooManyItems) } } } impl<'a, 'de: 'a, I, T> MapAccess<'de> for &'a mut MapDeserializer<'de, I, T> where I: Iterator<Item = T>, T: Pair<'de>, First<'de, I::Item>: IntoEetfDeserializer, Second<'de, I::Item>: IntoEetfDeserializer, { type Error = Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: DeserializeSeed<'de>, { if self.current_value.is_some() { panic!("MapDeserializer.next_key_seed was called twice in a row") } match self.items.next() { Some(pair) => { let (key, val) = pair.split(); self.current_value = Some(val); seed.deserialize(key.into_deserializer()).map(Some) } None => Ok(None), } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> where V: DeserializeSeed<'de>, { if let Some(value) = self.current_value { self.current_value = None; seed.deserialize(value.into_deserializer()) } else { panic!("MapDeserializer.next_value_seed was called before next_key_seed") } } } struct EnumDeserializer<'de> { variant: &'de Term, term: &'de Term, } impl<'de> EnumDeserializer<'de> { fn new(variant: &'de Term, term: &'de Term) -> Self { EnumDeserializer { variant, term } } } // `EnumAccess` is provided to the `Visitor` to give it the ability to determine // which variant of the enum is supposed to be deserialized. // // Note that all enum deserialization methods in Serde refer exclusively to the // "externally tagged" enum representation. impl<'de> EnumAccess<'de> for EnumDeserializer<'de> { type Error = Error; type Variant = Self; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)> where V: DeserializeSeed<'de>, { let val = seed.deserialize(VariantNameDeserializer::from_term(self.variant))?; Ok((val, self)) } } // `VariantAccess` is provided to the `Visitor` to give it the ability to see // the content of the single variant that it decided to deserialize. impl<'de> VariantAccess<'de> for EnumDeserializer<'de> { type Error = Error; // If the `Visitor` expected this variant to be a unit variant, the input // should have been the plain string case handled in `deserialize_enum`. fn unit_variant(self) -> Result<()> { Err(Error::ExpectedAtom) } // Newtype variants are represented in JSON as `{ NAME: VALUE }` so // deserialize the value here. fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> where T: DeserializeSeed<'de>, { seed.deserialize(Deserializer::from_term(self.term)) } // Tuple variants are represented in JSON as `{ NAME: [DATA...] }` so // deserialize the sequence of data here. fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { let deserializer = Deserializer::from_term(self.term); de::Deserializer::deserialize_tuple(deserializer, len, visitor) } // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }` so // deserialize the inner map here. fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> where V: Visitor<'de>, { let deserializer = Deserializer::from_term(self.term); de::Deserializer::deserialize_map(deserializer, visitor) } } struct VariantNameDeserializer<'a> { term: &'a Term, } impl<'a> VariantNameDeserializer<'a> { pub fn from_term(term: &'a Term) -> Self { VariantNameDeserializer { term } } } impl<'de, 'a: 'de> de::Deserializer<'de> for VariantNameDeserializer<'a> { type Error = Error; fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { match self.term { Term::Atom(atom) => visitor.visit_string(atom.name.to_camel_case()), _ => Err(Error::ExpectedAtom), } } forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any } } mod private { // Some code I stole from serde. /// Avoid having to restate the generic types on `MapDeserializer`. The /// `Iterator::Item` contains enough information to figure out K and V. pub trait Pair<'a> { type First; type Second; fn split(self) -> &'a (Self::First, Self::Second); } impl<'a, A, B> Pair<'a> for &'a (A, B) { type First = A; type Second = B; fn split(self) -> &'a (A, B) { self } } pub type First<'a, T> = <T as Pair<'a>>::First; pub type Second<'a, T> = <T as Pair<'a>>::Second; } #[cfg(test)] mod tests { use super::*; use eetf::{self, Term}; // Helper function for tests. Runs things through our serializer then // decodes and returns. fn deserialize<T>(input: Term) -> T where T: DeserializeOwned, { let mut cursor = io::Cursor::new(vec![]); Term::encode(&input, &mut cursor).expect("encode failed"); from_bytes(&cursor.into_inner()).expect("deserialize failed") } #[test] fn test_unsigned_ints_and_structs() { #[derive(Deserialize, Debug, PartialEq)] struct TestStruct { unsigned8: u8, unsigned16: u16, unsigned32: u32, unsigned64: u64, } let result: TestStruct = deserialize(Term::Map(eetf::Map::from(vec![ ( Term::Atom(eetf::Atom::from("unsigned8")), Term::FixInteger(eetf::FixInteger::from(129)), ), ( Term::Atom(eetf::Atom::from("unsigned16")), Term::FixInteger(eetf::FixInteger::from(65530)), ), ( Term::Atom(eetf::Atom::from("unsigned32")), Term::BigInteger(eetf::BigInteger::from(65530)), ), ( Term::Atom(eetf::Atom::from("unsigned64")), Term::BigInteger(eetf::BigInteger::from(65530)), ), ]))); assert_eq!( result, TestStruct { unsigned8: 129, unsigned16: 65530, unsigned32: 65530, unsigned64: 65530, } ) } #[test] fn test_signed_ints_and_tuple_structs() { #[derive(Deserialize, Debug, PartialEq)] struct TestStruct(i8, i16, i32, i64); let result: TestStruct = deserialize(Term::Tuple(eetf::Tuple::from(vec![ Term::FixInteger(eetf::FixInteger::from(-127)), Term::FixInteger(eetf::FixInteger::from(30000)), Term::FixInteger(eetf::FixInteger::from(65530)), Term::BigInteger(eetf::BigInteger::from(65530)), ]))); assert_eq!(result, TestStruct(-127, 30000, 65530, 65530)) } #[test] fn test_binaries_tuples_and_lists() { let result: (String, Vec<u8>) = deserialize(Term::Tuple(eetf::Tuple::from(vec![ Term::Binary(eetf::Binary::from("ABCD".as_bytes())), Term::List(eetf::List::from(vec![ Term::FixInteger(eetf::FixInteger::from(0)), Term::FixInteger(eetf::FixInteger::from(1)), Term::FixInteger(eetf::FixInteger::from(2)), ])), ]))); assert_eq!(result, ("ABCD".to_string(), vec![0, 1, 2])) } #[test] fn test_option() { let nil_result: Option<u8> = deserialize(Term::Atom(eetf::Atom::from("nil"))); let some_result: Option<u8> = deserialize(Term::FixInteger(eetf::FixInteger::from(0))); assert_eq!(nil_result, None); assert_eq!(some_result, Some(0)); } #[test] fn test_unit_variant() { #[derive(Deserialize, Debug, PartialEq)] enum E { AnOption, AnotherOption, }; let result: E = deserialize(Term::Atom(eetf::Atom::from("an_option"))); assert_eq!(result, E::AnOption); } #[test] fn test_newtype_variant() { // Not 100% sure if this is a tuple variant or a newtype variant. // But whatever I guess? #[derive(Deserialize, Debug, PartialEq)] enum ErlResult { Ok(String), }; let result: ErlResult = deserialize(Term::Tuple(eetf::Tuple::from(vec![ Term::Atom(eetf::Atom::from("ok")), Term::Binary(eetf::Binary::from("test".as_bytes())), ]))); assert_eq!(result, ErlResult::Ok("test".to_string())); } #[test] fn test_tuple_variant() { // Not 100% sure if this is a tuple variant or a newtype variant. // But whatever I guess? #[derive(Deserialize, Debug, PartialEq)] enum Testing { Ok(u8, u8), }; let result: Testing = deserialize(Term::Tuple(eetf::Tuple::from(vec![ Term::Atom(eetf::Atom::from("ok")), Term::Tuple(eetf::Tuple::from(vec![ Term::FixInteger(eetf::FixInteger::from(1)), Term::FixInteger(eetf::FixInteger::from(2)), ])), ]))); assert_eq!(result, Testing::Ok(1, 2)); } // TODO: test actual maps, as well as structs. Suspect they're broken. // some quickcheck based roundtrip tests would also be great. }
Java
UTF-8
1,158
2.65625
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aula1; /** * * @author 19221080 */ public class Caixa { private double largura; private double altura; private double profundidade; public static String cor = "Vermelho"; public Caixa() { } public Caixa(double largura, double altura, double profundidade) { this.largura = largura; this.altura = altura; this.profundidade = profundidade; } public double getVolume() { return largura * altura * profundidade; } public double getLargura() { return largura; } public void setLargura(double largura) { this.largura = largura; } public double getAltura() { return altura; } public void setAltura(double altura) { this.altura = altura; } public double getProfundidade() { return profundidade; } public void setProfundidade(double profundidade) { this.profundidade = profundidade; } }
Python
UTF-8
1,266
3.453125
3
[]
no_license
class Solution: def canJump(self, nums: List[int]) -> bool: j= len(nums)-1 i = j # Iterate from last index to the first index of nums # Check if the farthest index can be reach at current position is greater than j. # Update j if True. while i>=0: if i + nums[i] >= j: j = i i-=1 return j == 0 # Dynamic Programming Iterative class Solution_2: def canJump(self, nums: List[int]) -> bool: opt=[None]*len(nums) opt[-1] =True i = len(nums) - 1 while i>=0: for j in range(i,min(i+nums[i]+1,len(nums)))[::-1]: opt[i] = opt[j] if opt[i]: break i-=1 return opt[0] # Dynamic Programing Recursive class Solution_3: def canJump(self, nums: List[int]) -> bool: opt=[None]*len(nums) opt[-1] =True def helper(n): if opt[n]: return opt[n] opt[n] = False for i in range(n+1,n+nums[n]+1): opt[n] = opt[n] or helper(i) if opt[n]: break return opt[n] helper(0) print(opt) return opt[0]
PHP
UTF-8
300
3.109375
3
[]
no_license
<?php class classname { public $attribute; function __construct($param) { $this->attribute=$param; echo $this->attribute; } public function operation() { echo 'this is operation'; } function __destruct() { echo 'destruct'; } }
Java
UTF-8
654
3.015625
3
[]
no_license
package domain; import java.util.Timer; import java.util.TimerTask; public class Reloj { private Reloj instance = null; public Reloj getInstance() { if (instance == null) { return new Reloj(); } return instance; } Timer timer = new Timer(); public int segundos; public boolean frozen; class Contador extends TimerTask { public void run() { segundos++; System.out.println("segundo: " + segundos); } } public void Contar() { this.segundos = 0; timer = new Timer(); timer.schedule(new Contador(), 0, 1000); } public void Detener() { timer.cancel(); } public int getSegundos() { return this.segundos; } }
C++
UTF-8
5,087
2.75
3
[]
no_license
#pragma once #include "luaState.h" #include <filesystem> namespace file = std::tr2::sys; namespace lua { /*---------------------------------------------------------------------------------------> || note: default argument values are not given here (see class declaration) || note: function explanations are not given here (see class declaration) || note: 'string' = 'std::string' || || class: lua::luastream || intent: Provide a ostream-esque interface to lua || constructors: || default: given - void || copy: given - luastream -- currently private || luaFunc: given - lua_State* || interface: || dumpImpl: return - string given - void use - dumpImpl() || operator*: return - lua_State* given - void use - *<stream> || load: return - void given - file::path& use - load(<path of lua script>) || move: return - void given - luastream&,int use - move(<stream to>,<num to move>) || call: return - bool given - string,int use - call(<func>,<numArgs>) || clear: return - void given - void use - clear() || size: return - int given - void use - size() || valid: return - int given - int,int use - valid(<index>,<modifier>) || typeat: return - string given - int use - typeat(<index>) || operator--: return - luastream& given - void use - --<stream> || operator--: return - luastream& given - void use - <stream>-- || operator++: return - luastream& given - void use - ++<stream> || operator++: return - luastream& given - void use - <stream>++ || operator<<: return - luastream& insertion operator use - <stream> << <value> || operator>>: return - luastream& extraction operator use - <stream> >> <variable> || totop: return - void given - luastream&,int use - luastream::totop(<stream>,<index>) || TODO: || Enable copy constructor || Have impl be changeable || Template operator>> & operator<< (luaBindings.h would have to be included) \*---------------------------------------------------------------------------------------->*/ void addFile(lua_State*,file::path&); class luastream { private: luaState stack; // forward declaration of pimpl class struct impl; impl* state; luastream& operator=(const luastream&); // delete function keyword not currently supported in vs2012 luastream(const luastream&); public: // constructors/destructors luastream(); // default luastream(lua_State*); // luaFunc Enables luastream use in functions registered with lua ~luastream(); // state functions std::string dumpImpl(const char*); // Returns the internal state as a string // stack getters luaState& get(); // Returns internal luaState& lua_State* operator*(void); // Returns internal lua_State* operator lua_State* (); // Conversion operator // stack interaction void load(file::path&); // Load a file into lua void move(luastream&,int=-1); // Move values into the passed luastream. Passes all values by default bool call(std::string,int=0); // Calls the passed function with x arguments. Defaults to 0 arguments void clear(); // Clears the stack of all values // stack info functions int size(); // Returns the number of values in the stack bool valid(int,int=0); // Is the passed index a valid lua index. Second arg adds to the stack size // (Stack's expected future size at time of use) (defaults to no change) std::string typeat(int); // Returns the type of the value at stack[index] -- Mark bool typecheck(int,int); // Checks if the value at stack[index] is the passed type // stack size operators luastream& operator--(); // Decreases the stack's size by one. Removes the top value from the stack luastream& operator--(int); luastream& operator++(); // Increases the stack's size by one. Pushes a nil value onto stack top luastream& operator++(int); // stream operator overloads -- override these to enable insertion and extraction of custom types // do not override with templates if you want the manipulators to work (???) friend luastream& operator<<(luastream&,lua_Integer); friend luastream& operator<<(luastream&,lua_Number); friend luastream& operator<<(luastream&,const char*); friend luastream& operator<<(luastream&,std::string); friend luastream& operator<<(luastream&,bool); friend luastream& operator>>(luastream&,lua_Integer&); friend luastream& operator>>(luastream&,lua_Number&); friend luastream& operator>>(luastream&,std::string&); friend luastream& operator>>(luastream&,bool&); // manipulator helper function -- common code for use in custom manipulators static void totop(luastream&,int); // Moves the value at <stream>[index] to the top of the stream }; // debug overloads for luastream. Same usage as shown in luaBindings.h int start(luastream&); int end(luastream&); std::string debugHead(luastream&); std::string debugBody(luastream&,const char* = "-"); };
Markdown
UTF-8
1,665
2.828125
3
[]
no_license
# 一、个人博客 出于省钱考虑,原博客域名已经卖掉,学习笔记现在全部记录在 fedbook 这个仓库下,该仓库将不再维护。 # 二、我的书单 ## 已读书单 推荐星级 - ★★★:值得一看,看了不会后悔的 - ★★☆:可以一看,能学到点东西 - ★☆☆:稍微看看,了解了解 - ☆☆☆:不推荐,有这个时间不如出去放松一下吧 ### 前端 - [x] ★★☆ **重学前端** winter <sub>`2019`</sub> ### Python - [x] ★★☆ **Python爬虫开发与项目实战** <sub>`2017`</sub> - [x] ★★☆ **Python3网络爬虫开发实战** <sub>`2017`</sub> - [x] ★☆☆ 跟老齐学Python:Django实战 <sub>`2018`</sub> ### MySQL - [x] ★★☆ **深入浅出MySQL:数据库开发、优化与管理维护** <sub>`2017`</sub> ### Elasticsearch - [x] ★★☆ **深入理解Elasticsearch** <sub>`2018`</sub> - [x] ★☆☆ 从Lucene到Elasticsearch 全文检索实战 <sub>`2018`</sub> ### 其他技术书 - [x] ★★☆ **图解HTTP** <sub>`2019`</sub> ### 课外书 - [x] ★★☆ **洋葱阅读法** 彭小六 <sub>`2020`</sub> - [x] ★★☆ **小狗钱钱** <sub>`2019`</sub> - [x] ★★☆ **你凭什么做好互联网** 曹政 <sub>`2019`</sub> - [x] ★☆☆ 你没有退路,才有出路 李尚龙 <sub>`2019`</sub> - [x] ★☆☆ 新媒体运营:产品运营+内容运营+用户运营+活动运营 <sub>`2019`</sub> <br/> ###### PS:一千个读者,就有一千个哈姆雷特,上述标记为“不推荐”只是个人学习过后的感受,并非否定作者或作品,望知悉
Java
UTF-8
9,151
1.734375
2
[]
no_license
package com.ceic.mem.persistence.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "users_relation") public class UsersRelationEntity implements Serializable { private static final long serialVersionUID = 3686074225896762417L; private String fromUserId; private String toUserId; private Boolean viewProfile; private Date viewProfileTime; private Boolean like; private Date likeTime; private Boolean sendRequest; private Date sendRequestTime; private Boolean acceptRequest; private Date acceptRequestTime; private Boolean viewMobile; private Date viewMobileTime; private Boolean viewEmail; private Date viewEmailTime; private Boolean sendMail; private Date sendMailTime; private Boolean block; private String mailContent; private Boolean requestPicks; private Date requestPicksTime; private Boolean respondPicks; private Date respondPicksTime; private Boolean requestFile; private Date requestFileTime; private Boolean respondFile; private Date respondFileTime; private Boolean requestHadoop; private Date requestHadoopTime; private Boolean respondHadoop; private Date respondHadoopTime; public UsersRelationEntity() { super(); // TODO Auto-generated constructor stub } @Id @Column(name = "c_from_user_id", unique = true, nullable = false) public String getFromUserId() { return fromUserId; } public void setFromUserId(String fromUserId) { this.fromUserId = fromUserId; } @Column(name = "c_to_user_id", nullable = false) public String getToUserId() { return toUserId; } public void setToUserId(String toUserId) { this.toUserId = toUserId; } @Column(name = "b_viewed_profile") public Boolean getViewProfile() { return viewProfile; } public void setViewProfile(Boolean viewProfile) { this.viewProfile = viewProfile; } @Column(name = "t_viewed_profile_time") public Date getViewProfileTime() { return viewProfileTime; } public void setViewProfileTime(Date viewProfileTime) { this.viewProfileTime = viewProfileTime; } @Column(name = "b_like") public Boolean getLike() { return like; } public void setLike(Boolean like) { this.like = like; } @Column(name = "t_like_time") public Date getLikeTime() { return likeTime; } public void setLikeTime(Date likeTime) { this.likeTime = likeTime; } @Column(name = "b_send_request") public Boolean getSendRequest() { return sendRequest; } public void setSendRequest(Boolean sendRequest) { this.sendRequest = sendRequest; } @Column(name = "t_send_request_time") public Date getSendRequestTime() { return sendRequestTime; } public void setSendRequestTime(Date sendRequestTime) { this.sendRequestTime = sendRequestTime; } @Column(name = "b_accept_request") public Boolean getAcceptRequest() { return acceptRequest; } public void setAcceptRequest(Boolean acceptRequest) { this.acceptRequest = acceptRequest; } @Column(name = "t_accept_request_time") public Date getAcceptRequestTime() { return acceptRequestTime; } public void setAcceptRequestTime(Date acceptRequestTime) { this.acceptRequestTime = acceptRequestTime; } @Column(name = "b_viewed_mobile_no") public Boolean getViewMobile() { return viewMobile; } public void setViewMobile(Boolean viewMobile) { this.viewMobile = viewMobile; } @Column(name = "t_view_mobile_time") public Date getViewMobileTime() { return viewMobileTime; } public void setViewMobileTime(Date viewMobileTime) { this.viewMobileTime = viewMobileTime; } @Column(name = "b_viewed_email") public Boolean getViewEmail() { return viewEmail; } public void setViewEmail(Boolean viewEmail) { this.viewEmail = viewEmail; } @Column(name = "t_view_email_time") public Date getViewEmailTime() { return viewEmailTime; } public void setViewEmailTime(Date viewEmailTime) { this.viewEmailTime = viewEmailTime; } @Column(name = "b_send_mail") public Boolean getSendMail() { return sendMail; } public void setSendMail(Boolean sendMail) { this.sendMail = sendMail; } @Column(name = "t_send_email_time") public Date getSendMailTime() { return sendMailTime; } public void setSendMailTime(Date sendMailTime) { this.sendMailTime = sendMailTime; } @Column(name = "b_block") public Boolean getBlock() { return block; } public void setBlock(Boolean block) { this.block = block; } @Column(name = "c_mail_content") public String getMailContent() { return mailContent; } public void setMailContent(String mailContent) { this.mailContent = mailContent; } @Column(name = "b_request_picks") public Boolean getRequestPicks() { return requestPicks; } public void setRequestPicks(Boolean requestPicks) { this.requestPicks = requestPicks; } @Column(name = "t_request_picks_time") public Date getRequestPicksTime() { return requestPicksTime; } public void setRequestPicksTime(Date requestPicksTime) { this.requestPicksTime = requestPicksTime; } @Column(name = "b_respond_picks") public Boolean getRespondPicks() { return respondPicks; } public void setRespondPicks(Boolean respondPicks) { this.respondPicks = respondPicks; } @Column(name = "t_respond_picks_time") public Date getRespondPicksTime() { return respondPicksTime; } public void setRespondPicksTime(Date respondPicksTime) { this.respondPicksTime = respondPicksTime; } @Column(name = "b_request_file") public Boolean getRequestFile() { return requestFile; } public void setRequestFile(Boolean requestFile) { this.requestFile = requestFile; } @Column(name = "t_request_file_time") public Date getRequestFileTime() { return requestFileTime; } public void setRequestFileTime(Date requestFileTime) { this.requestFileTime = requestFileTime; } @Column(name = "b_respond_file") public Boolean getRespondFile() { return respondFile; } public void setRespondFile(Boolean respondFile) { this.respondFile = respondFile; } @Column(name = "t_respond_file_time") public Date getRespondFileTime() { return respondFileTime; } public void setRespondFileTime(Date respondFileTime) { this.respondFileTime = respondFileTime; } @Column(name = "b_request_hadoop") public Boolean getRequestHadoop() { return requestHadoop; } public void setRequestHadoop(Boolean requestHadoop) { this.requestHadoop = requestHadoop; } @Column(name = "t_request_hadoop_time") public Date getRequestHadoopTime() { return requestHadoopTime; } public void setRequestHadoopTime(Date requestHadoopTime) { this.requestHadoopTime = requestHadoopTime; } @Column(name = "b_respond_hadoop") public Boolean getrespondHadoop() { return respondHadoop; } public void setrespondHadoop(Boolean respondHadoop) { this.respondHadoop = respondHadoop; } @Column(name = "t_respond_hadoop_time") public Date getrespondHadoopTime() { return respondHadoopTime; } public void setrespondHadoopTime(Date respondHadoopTime) { this.respondHadoopTime = respondHadoopTime; } public static long getSerialversionuid() { return serialVersionUID; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((fromUserId == null) ? 0 : fromUserId.hashCode()); result = prime * result + ((toUserId == null) ? 0 : toUserId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UsersRelationEntity other = (UsersRelationEntity) obj; if (fromUserId == null) { if (other.fromUserId != null) return false; } else if (!fromUserId.equals(other.fromUserId)) return false; if (toUserId == null) { if (other.toUserId != null) return false; } else if (!toUserId.equals(other.toUserId)) return false; return true; } @Override public String toString() { return "UsersRelationEntity [fromUserId=" + fromUserId + ", toUserId=" + toUserId + ", viewProfile=" + viewProfile + ", viewProfileTime=" + viewProfileTime + ", like=" + like + ", likeTime=" + likeTime + ", sendRequest=" + sendRequest + ", sendRequestTime=" + sendRequestTime + ", acceptRequest=" + acceptRequest + ", acceptRequestTime=" + acceptRequestTime + ", viewMobile=" + viewMobile + ", viewMobileTime=" + viewMobileTime + ", viewEmail=" + viewEmail + ", viewEmailTime=" + viewEmailTime + ", sendMail=" + sendMail + ", sendMailTime=" + sendMailTime + ", block=" + block + ", mailContent=" + mailContent + ", requestPicks=" + requestPicks + ", requestPicksTime=" + requestPicksTime + ", respondPicks=" + respondPicks + ", respondPicksTime=" + respondPicksTime + ", requestFile=" + requestFile + ", requestFileTime=" + requestFileTime + ", respondFile=" + respondFile + ", respondFileTime=" + respondFileTime + ", requestHadoop=" + requestHadoop + ", requestHadoopTime=" + requestHadoopTime + ", respondHadoop=" + respondHadoop + ", respondHadoopTime=" + respondHadoopTime + "]"; } }
PHP
UTF-8
1,671
2.65625
3
[]
no_license
<?php require_once('../config.php'); require_once(DBAPI); $atletas = null; $atleta = null; /** * Listagem de Atletas */ function index() { global $atletas; $atletas = find_all('atletas'); } /** * Cadastro de Atletas */ function add() { if (!empty($_POST['atleta'])) { $today = date_create('now', new DateTimeZone('America/Sao_Paulo')); $atleta = $_POST['atleta']; $atleta['modificado'] = $atleta['criado'] = $today->format("Y-m-d H:i:s"); save('atletas', $atleta); header('location: index.php'); } } /** * Atualizacao/Edicao de Atleta */ function edit() { $now = date_create('now', new DateTimeZone('America/Sao_Paulo')); if (isset($_GET['id'])) { $id = $_GET['id']; if (isset($_POST['atleta'])) { $atleta = $_POST['atleta']; $atleta['modificado'] = $now->format("Y-m-d H:i:s"); update('atletas', $id, $atleta); header('location: index.php'); } else { global $atleta; $atleta = find('atletas', $id); } } else { header('location: index.php'); } } /** * Visualização de um atleta */ function view($id = null) { global $atleta; $atleta = find('atletas', $id); } /** * Exclusão de um Atleta */ function delete($id = null) { global $atleta; $atleta = remove('atletas', $id); header('location: index.php'); }
Markdown
UTF-8
3,961
3.125
3
[ "ICU", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- title: " DTOJ3238交通\t\t" tags: - 二分 - 思路 url: 7096.html id: 7096 categories: - Solution date: 2019-03-24 10:29:35 --- 思考一下我们要做的操作。就是对于当前点,从其最大的子树中挑一个点出来,将这个点及其子树的大小算到当前点最小的子树中,让答案尽可能小。 首先可以知道,答案是可二分的,我们二分答案,转为判定性问题。其答案下界是 次大子树大小 与 最大最小子树大小平均值 的最大值,而上界自然是 最大子树大小。 不妨在树状数组内处理答案。那么对于当前点,其子树在dfs序上就是连续的一段区间。那么我们在树状数组上维护子树内所有点的 $size$ 信息。 那么我们对于当前答案$mid$,就是要考虑在最大点所在子树中,是否存在大小在$\[Max - mid - 1, mid - Min\]$之间的子树。在树状数组上查询区间和即可。 但是其最大子树在父亲的情况要单独拎出来考虑:仍然用树状数组维护,对于每个点用一个$vector$维护管辖区间内对应子树大小的点的dfs序。那么每次相当于询问子树大小在$\[Max - mid - 1, mid - Min\]$之间,同时dfs序在$\[pos,pos+size-1\]$之间的点的个数。考虑用根的答案减去当前点的子树内的答案就是当前点往上的部分,满足条件的点的个数了。 时间效率$O(n \\log^2 n)$。 #include<bits/stdc++.h> #define N 100005 int n, fa\[N\], Size\[N\], pos\[N\], tim, ans\[N\]; std::vector<int> e\[N\]; struct node { int Max, Max2, Min, id; void update (int sz, int x) { if (sz > Max) Max2 = Max, Max = sz, id = x; else Max2 = std::max (Max2, sz); Min = std::min (Min, sz); } }t\[N\]; class BIT1 { int t\[N\]; public: void add (int x, int v) { for (; x <= n; x += x & -x) t\[x\] += v; } int ask (int x) { int res = 0; for (; x > 0; x -= x & -x) res += t\[x\]; return res; } int query (int l, int r) { return ask (r) - ask (l); } }T1; class BIT2 { std::vector<int> t\[N\]; public: int calc (std::vector<int> &x, int l, int r) { return std::upper\_bound (x.begin (), x.end (), r) - std::lower\_bound (x.begin (), x.end (), l); } void add (int x, int v) { for (; x <= n; x += x & -x) t\[x\].push_back (v); } int ask (int x, int l, int r) { int res = 0; for (; x > 0; x -= x & -x) res += calc (t\[x\], l, r); return res; } int asksz (int x) { int res = 0; for (; x > 0; x -= x & -x) res += t\[x\].size (); return res; } int query (int l, int r, int a, int b) { return ask (r, a, b) - ask (l, a, b); } void sort () { for (int i = 1; i <= n; i++) std::sort (t\[i\].begin (), t\[i\].end ()); } }T2; void dfs1 (int u) { Size\[u\] = 1, pos\[u\] = ++tim; for (int v : e\[u\]) dfs1 (v), Size\[u\] += Size\[v\], t\[u\].update (Size\[v\], v); if (u ^ 1) t\[u\].update (n - Size\[u\], fa\[u\]); ans\[u\] = t\[u\].Max, T2.add (Size\[u\], pos\[u\]); } void doupd (int u) { int l = std::max (t\[u\].Max2, t\[u\].Max + t\[u\].Min >> 1), r = t\[u\].Max; for (int mid, L, R, cnt; l < r;) { mid = l + r >> 1, L = t\[u\].Max - mid - 1, R = mid - t\[u\].Min, cnt = 0; if (t\[u\].id == fa\[u\]) { cnt += T2.asksz (R) - T2.asksz (L) - T2.query (L, R, pos\[u\], pos\[u\] + Size\[u\] - 1); cnt += T1.query (std::min (L + Size\[u\], n), std::min (R + Size\[u\], n)) - T1.query (L, R); } else cnt += T2.query (L, R, pos\[t\[u\].id\], pos\[t\[u\].id\] + Size\[t\[u\].id\] - 1); cnt > 0 ? r = mid : l = mid + 1; } ans\[u\] = std::min (ans\[u\], l); } void dfs2 (int u) { if (e\[u\].size () + (fa\[u\] > 0) > 1) doupd (u); T1.add (Size\[u\], 1); for (int v : e\[u\]) dfs2 (v); T1.add (Size\[u\], -1); } int main () { scanf ("%d", &n); for (int i = 1; i <= n; i++) t\[i\].Min = 1e9, t\[i\].Max = t\[i\].Max2 = -1e9; for (int i = 2; i <= n; i++) scanf ("%d", &fa\[i\]), e\[fa\[i\]\].push_back (i); dfs1 (1); T2.sort (), dfs2 (1); for (int i = 1; i <= n; i++) printf ("%d\\n", ans\[i\]); }
Python
UTF-8
701
3.796875
4
[]
no_license
# Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals.sort(key = lambda x: x.start) print(intervals) result = [intervals[0]] for interval in intervals: prev = result[-1] if interval.start <= prev.end: prev.end = max(interval.end, prev.end) else: result.append(interval) return result print(Solution().merge([[1,3],[2,6],[8,10],[15,18]])) print(Solution().merge([[2,3],[1,2],[3,4],[6,18]]))
JavaScript
UTF-8
1,347
2.546875
3
[ "MIT" ]
permissive
const express = require('express'); const router = express.Router(); const priceController = require('./price.controller'); const paramValidation = require('./priceParam-validation'); const validate = require('express-validation'); // routes router.post('/submit', [validate(paramValidation.createPrice), submit]); router.get('/', getAll); router.get('/:id', [validate(paramValidation.GetPrice), getById]); router.put('/:id', [validate(paramValidation.updatePrice), update]); module.exports = router; function submit(req, res, next) { priceController.create(req.body) .then(url => url ? res.status(200).json(url) : res.status(403).json({ 'message': ' Request failed please try again' })) .catch(err => next(err)); } function getById(req, res, next) { priceController.getById(req.params.id) .then(price => price ? res.json(price) : res.sendStatus(404)) .catch(err => next(err)); } function getAll(req, res, next) { priceController.getAll() .then(price => res.json(price)) .catch(err => next(err)); } function update(req, res, next) { priceController.update(req.params.id, req.body) .then(url => url ? res.json({ "message": "The price has updated" }).send(200) : res.status(403).json({ 'message': ' Request failed please try again' })) .catch(err => next(err)); }
Ruby
UTF-8
771
4.3125
4
[]
no_license
# Implement a caesar cipher that takes in a string and the # shift factor and then outputs the modified string # From: https://www.theodinproject.com/paths/full-stack-ruby-on-rails/courses/ruby-programming/lessons/caesar-cipher def caesar_cipher(text, shift) upper = ('A'..'Z').to_a lower = ('a'..'z').to_a shifted = text.split('').map do |character| case character when /[[:upper:]]/ then (upper.rotate(shift))[upper.index(character)] when /[[:lower:]]/ then (lower.rotate(shift))[lower.index(character)] else character end end shifted.join end print "Enter a phrase: " phrase = gets.chomp print "Enter the shift value: " shift = gets.chomp.to_i puts caesar_cipher(phrase, shift)
Python
UTF-8
453
2.90625
3
[]
no_license
import yfinance as yf import pandas as pd msft = yf.Ticker("FROTO.IS") print(msft.info) x = msft.info zip = x["zip"] print("Posta Kodu :",zip) #print(x) xxx = msft.quarterly_financials print(type(xxx)) print(xxx.head()) print(xxx) print(xxx[["2021-03-31"]]) x2= xxx[["2021-03-31"]] test = pd.DataFrame(x2) test2 = test.values.tolist() print(type(test2)) print(test2[0]) #hist = msft.history(period="max") #print(hist) #xx=msft.financials #print(xx)
Swift
UTF-8
8,417
2.734375
3
[]
no_license
// // MovieListView.swift // Movies // // Created by Ho Duy Luong on 5/4/20. // Copyright © 2020 Ho Duy Luong. All rights reserved. // import UIKit import iCarousel class MovieListViewController: UIViewController { private let backgroundImageView: UIImageView = { let backgroundImage = UIImage(named: "background") let view = UIImageView() view.image = backgroundImage view.contentMode = .scaleAspectFill view.translatesAutoresizingMaskIntoConstraints = false return view }() private let carousel: iCarousel = { let carousel = iCarousel() carousel.backgroundColor = .none carousel.translatesAutoresizingMaskIntoConstraints = false carousel.isPagingEnabled = true carousel.isScrollEnabled = true carousel.type = .rotary return carousel }() private lazy var pageControl: UIPageControl = { let pc = UIPageControl() pc.currentPage = 0 pc.numberOfPages = 20 pc.pageIndicatorTintColor = .gray pc.currentPageIndicatorTintColor = .white return pc }() private let previousButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Previous", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) button.setTitleColor(.gray, for: .normal) button.setTitleColor(.green, for: .selected) button.setTitleColor(.green, for: .highlighted) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(handlePrevious), for: .touchUpInside) return button }() private let nextButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Next", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(handleNext), for: .touchUpInside) return button }() private let watchButton: UIButton = { let button = UIButton(type: .system) button.setTitle("WATCH THIS MOVIE", for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) button.setTitleColor(.white, for: .normal) button.setTitleColor(.green, for: .highlighted) button.backgroundColor = .darkGray button.layer.cornerRadius = 3 button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(handleWatchThisMovie), for: .touchUpInside) return button }() var bottomControlsStackView = UIStackView() override func viewDidLoad() { super.viewDidLoad() carousel.dataSource = self carousel.delegate = self setupBottomControls() setupWatchThisMovie() setupCollection() } // MARK:- Setup Movie Collection View func setupCollection() { view.addSubview(backgroundImageView) view.addSubview(carousel) view.sendSubviewToBack(carousel) view.sendSubviewToBack(backgroundImageView) NSLayoutConstraint.activate([ backgroundImageView.topAnchor.constraint(equalTo: view.topAnchor), backgroundImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor), backgroundImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor), backgroundImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor), carousel.bottomAnchor.constraint(equalTo: watchButton.topAnchor, constant: -20), carousel.leadingAnchor.constraint(equalTo: view.leadingAnchor), carousel.trailingAnchor.constraint(equalTo: view.trailingAnchor), carousel.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.6), ]) } // MARK: - Setup Page Control UI And Function fileprivate func setupBottomControls() { bottomControlsStackView = UIStackView(arrangedSubviews: [pageControl]) // [previousButton, pageControl, nextButton]) bottomControlsStackView.translatesAutoresizingMaskIntoConstraints = false bottomControlsStackView.distribution = .fillEqually view.addSubview(bottomControlsStackView) NSLayoutConstraint.activate([ bottomControlsStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), bottomControlsStackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), bottomControlsStackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), bottomControlsStackView.heightAnchor.constraint(equalToConstant: 50) ]) } @objc private func handlePrevious() { let preIndex = max(pageControl.currentPage - 1, 0) pageControl.currentPage = preIndex carousel.scrollToItem(at: preIndex, animated: true) } @objc private func handleNext() { print("Trying to advance to next") let nextIndex = min(pageControl.currentPage + 1, pageControl.numberOfPages - 1) pageControl.currentPage = nextIndex carousel.scrollToItem(at: nextIndex, animated: true) } // MARK:- Setup Watch Button UI and Function fileprivate func setupWatchThisMovie() { watchButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(watchButton) NSLayoutConstraint.activate([ watchButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), watchButton.bottomAnchor.constraint(equalTo: bottomControlsStackView.topAnchor, constant: 0), watchButton.widthAnchor.constraint(equalToConstant: view.frame.width * 3/4), watchButton.heightAnchor.constraint(equalToConstant: 50) ]) } @objc private func handleWatchThisMovie() { print("handleWatchThisMovie") watchMovieAnimation() } fileprivate func watchMovieAnimation() { } } // MARK: - Movie List View DataSource extension MovieListViewController: iCarouselDataSource { func numberOfItems(in carousel: iCarousel) -> Int { return 20 } func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView { let cell = MoviePageCell(frame: CGRect(x: 0, y: 0, width: carousel.frame.width * 3 / 4, height: carousel.frame.height)) return cell } } // MARK: - Movie List View Delegate extension MovieListViewController: iCarouselDelegate { func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat { var result: CGFloat switch option { case iCarouselOption.spacing: result = 1.25 return result case iCarouselOption.radius: result = value*0.88 return result case iCarouselOption.showBackfaces: result = 0.0 return result case iCarouselOption.wrap: result = 0.0 return result default: result = value break } return result } func carouselDidEndDecelerating(_ carousel: iCarousel) { print(carousel.currentItemIndex) pageControl.currentPage = carousel.currentItemIndex } func carousel(_ carousel: iCarousel, didSelectItemAt index: Int) { if index == carousel.currentItemIndex { if let currentCell = carousel.currentItemView { UIView.animate(withDuration: 0.1, animations: { //Fade-out currentCell.transform = CGAffineTransform(scaleX: 0.97, y: 0.97) }) { (completed) in UIView.animate(withDuration: 0.1, animations: { //Fade-out currentCell.transform = CGAffineTransform.identity currentCell.transform = CGAffineTransform.init(translationX: 0, y: -50) }) } } } } }
Go
UTF-8
561
2.53125
3
[]
no_license
package storage import ( "fmt" "os" "github.com/gomodule/redigo/redis" ) const redisHost string = "redis-cluster-ip-service" const redisPort string = "6379" // GetRedisConn returns a redis Conn func GetRedisConn(redisDial func(network, address string, options ...redis.DialOption) (redis.Conn, error)) redis.Conn { password := os.Getenv("REDIS_PASSWORD") host := fmt.Sprintf("%v:%v", redisHost, redisPort) conn, err := redisDial("tcp", host) _, err = conn.Do("AUTH", password) if err != nil { fmt.Println("ERROR: ", err) } return conn }
Markdown
UTF-8
1,089
2.578125
3
[ "MIT" ]
permissive
Virtual File System Virtual File System (VFS) or virtual filesystem switch is an abstraction layer on top of a more concrete file system. The purpose of a VFS is to allow client applications to access different types of concrete file systems in a uniform way. The virtual file system provides all the functionality to the user which is same as the UNIX based file system. It provides all necessary commands and system calls implementations of file system through customised shell. In these project we implement all necessary data structures of File Subsystem as Inode, Incore Inode Table, File Table, User File Descriptor Table etc. By using these project we can emulate UNIX file system on any windows platform. A virtual File System (VFS), sometimes referred to as a Hidden File System, is a storage technique most commonly used by kernel mode malware, usually to store components outside of the existing filesystem. By using a virtual filesystem, malware developers can both bypass antivirus scanners as well as complicating work for forensic experts.
Shell
UTF-8
516
2.90625
3
[ "Apache-2.0" ]
permissive
#!/bin/bash HOST=$1 ORG=$2 REPO=$3 PR=$4 [ "$HOST" == "" ] && ( echo "no host specified"; exit 1; ) [ "$ORG" == "" ] && ( echo "no org specified"; exit 1; ) [ "$REPO" == "" ] && ( echo "no repo specified"; exit 1; ) [ "$PR" == "" ] && ( echo "no pr specified"; exit 1; ) mkdir -p src/$HOST/$ORG \ && cd src/$HOST/$ORG/ \ && git clone --dept=1 https://$HOST/$ORG/$REPO \ && cd $REPO \ && git fetch origin pull/$PR/head:local_branch \ && git checkout local_branch \ && godoc -goroot /usr/local/go -http=:6060
Shell
UTF-8
162
2.515625
3
[ "MIT" ]
permissive
set -e for filename in `ls src/*.re` do node_modules/.bin/bsc -format $filename > ${filename}2 mv ${filename}2 $filename git mv $filename ${filename%.re}.res done
Java
UHC
1,121
2.296875
2
[]
no_license
package mumi.usercontroller; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import mumi.model.service.MumiService; public class UserLeaveAction implements Action { @Override public ModelAndView execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ModelAndView mv = new ModelAndView(); try { HttpSession session = request.getSession(); String id = (String) session.getAttribute("id"); if(id==null) { throw new SQLException(" Ǿϴ."); } int result = MumiService.deleteUserById(id); if(result==0) { throw new SQLException("ȸŻ ߽ϴ."); } session.invalidate(); mv.setPath("index.html"); }catch(SQLException e) { e.printStackTrace(); request.setAttribute("errorMsg", e.getMessage()); mv.setPath("404.html"); } return mv; } }
C++
UTF-8
3,483
2.609375
3
[]
no_license
#include<iostream> using namespace std; int a[1000001],t[1000001]; void build(int node,int s,int e) { if(s==e) { t[node]=a[s]; cout<<"node = "<<node<<endl; cout<<"t[node] = "<<t[node]<<endl; } else{ int mid=(s+e)/2; build(2*node,s,mid); build(2*node+1,mid+1,e); t[node]=t[2*node]+t[2*node+1]; } } void update(int node,int s,int e,int index,int value) { if(s==e) { a[index]=value; t[node]=value; //cout<<"node ="<<node<<endl; //cout<<"welcome\n"; } else { int mid =(s+e)/2; if(s<=index&&index<=mid) { update(node*2,s,mid,index,value); } else { update(node*2+1,mid+1,e,index,value); } t[node]=t[2*node]+t[2*node+1]; } } void updaterange(int node,int s,int e,int l,int r,int val) { if(s>e||e<l|| s>r) { return; } if(s==e) { t[node]=val; return; } int mid=(s+e)/2; updaterange(2*node,s,mid,l,r,val); updaterange(2*node+1,mid+1,e,l,r,val); t[node]=t[2*node]+t[2*node+1]; } int query(int node,int s,int e,int l,int r) { if(s>e||r<s||l>e) { cout<<"\nr, s= "<<r<<" "<<s<<" l,e = "<<l<<" "<<e<<endl; return 0; } if(l<=s&&e<=r) { cout<<"l= "<<l <<" r ="<<r<<endl; cout<<"t[node]= "<<t[node]<<endl; return t[node]; } int mid=(s+e)/2; int left,right; left=query(2*node,s,mid,l,r); right=query(2*node+1,mid+1,e,l,r); return left+right; } int lazy[50]; int queryRange(int node,int s,int e,int l,int r) { if(s>e||r<s||l>e) { cout<<"\nr, s= "<<r<<" "<<s<<" l,e = "<<l<<" "<<e<<endl; return 0; } if(lazy[node]!=0) { t[node]=(e-s+1)*lazy[node]; // t[node]=lazy[node]; cout<<"\n\nvery very node ="<<node<<endl; if(s!=e) { // lazy[2*node]+=lazy[node]; // lazy[2*node+1]+=lazy[node]; actual lazy[2*node]+=lazy[node]; lazy[2*node+1]+=lazy[node]; } lazy[node]=0; } if(l<=s&&e<=r) { // cout<<"l= "<<l <<" r ="<<r<<endl; // cout<<"t[node]= "<<t[node]<<endl; return t[node]; } int mid=(s+e)/2; int left,right; left=queryRange(2*node,s,mid,l,r); right=queryRange(2*node+1,mid+1,e,l,r); return left+right; } void updateRange(int node,int s,int e,int l,int r,int val) { if(lazy[node] != 0) { // This node needs to be updated t[node] += (e - s+ 1) * lazy[node]; // Update it if(s != e) { lazy[node*2] += lazy[node]; // Mark child as lazy lazy[node*2+1] += lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if(s>e||e<l||r<s) { return ; } if(s>=l&&e<=r ) { t[node]+=(e-s+1)*val; cout<<"\n special s,e = "<<s<<" "<<e<<endl; cout<<"\n special node ="<<node<<endl; if(s!=e) { lazy[2*node]+=val; lazy[2*node+1]+=val; } return ; } int mid=(s+e)/2; updateRange(2*node,s,mid,l,r,val); updateRange(2*node+1,mid+1,e,l,r,val); t[node]=t[2*node]+t[2*node+1]; } int main() { cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; } build(1,0,n-1); for(int i=1;i<2*n;i++) { cout<<t[i]<<" "; } // int ans=query(1,0,n-1,0,3); // cout<<"my ans="<<ans<<endl; updateRange(1,0,n-1,0,1,100); cout<<"t[8] ="<<t[8]<<endl; int ans=queryRange(1,0,n-1,0,3); cout<<"t[8] ="<<t[8]<<endl; cout<<"my ans="<<ans<<endl; for(int i=1;i<2*n;i++) { cout<<t[i]<<" "; } }
C++
UTF-8
3,223
3.546875
4
[]
no_license
// An Iterative C++ program to do DFS traversal from // a given source vertex. DFS(int s) traverses vertices // reachable from s. #include <bits/stdc++.h> using namespace std; <<<<<<< HEAD enum edge_direction { ======= enum edge_direction { >>>>>>> cbacd2620d17b8b6f8adfee86cf4ea019165ab88 IN, OUT }; struct pair_hash { template <class T1, class T2> std::size_t operator() (const std::pair<T1, T2> &pair) const { return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second); } }; // This class represents a directed graph using adjacency // list representation class Graph { int V; // No. of vertices vector<pair<int, enum edge_direction> > *adj; // adjacency arrays unordered_map< pair<int, int>, int, pair_hash> edge_idx_map; public: Graph(int V); // Constructor int deg(int v); // return total degree of vertex v void addEdge(int v, int w); // to add an edge to graph void DFS(); // prints all vertices in DFS manner // prints all not yet visited vertices reachable from s void DFSUtil(int s, vector<bool> &visited); }; Graph::Graph(int V) { this->V = V; adj = new vector<pair<int, enum edge_direction> >[V]; } // return indegree(v) + outdegree(v) int Graph::deg(int v) { return adj[v].size(); } void Graph::addEdge(int v, int w) { adj[v].push_back({w, OUT}); // Add w to v’s list. edge_idx_map[{v, w}] = adj[v].size() - 1; adj[w].push_back({v, IN}); edge_idx_map[{w, v}] = adj[w].size() - 1; } // prints all not yet visited vertices reachable from v in undirected graph void Graph::DFSUtil(int v, vector<bool> &visited) { // Create a stack for DFS stack<int> stack; int k = -1, l = -1; int w, u; visited[v] = true; printf("%d ", v); while (true) { l++; if (l < deg(v)) { if (adj[v][(k + l + 1) % deg(v)].second == IN) continue; w = adj[v][(k + l + 1) % deg(v)].first; if (!visited[w]) { stack.push(l); k = edge_idx_map[{w, v}]; // adj[w][k] = v l = -1; v = w; visited[v] = true; printf("%d ", v); } } else { if (stack.empty()) break; u = adj[v][k].first; l = stack.top(); stack.pop(); k = (edge_idx_map[{u, v}] - (l + 1)) % deg(u); v = u; } } } // prints all vertices in DFS manner void Graph::DFS() { // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (!visited[i]) DFSUtil(i, visited); } // Driver program to test methods of graph class int main() { Graph g(8); // Total 5 vertices in graph g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(3, 1); g.addEdge(2, 7); g.addEdge(3, 4); g.addEdge(3, 5); g.addEdge(3, 6); g.addEdge(6, 5); g.addEdge(6, 0); g.addEdge(7, 3); cout << "Following is Depth First Traversal\n"; g.DFS(); cout << endl; return 0; }
Markdown
UTF-8
1,163
2.5625
3
[]
no_license
--- layout: post title: "AWS Academy in UTHermosillo!!" date: 2021-03-22 10:52:04 -0700 categories: blog update --- In our Academic Educators Group: ConSolTI, we are starting a new project, in which we have the goal to ADOPT CLOUD TECH to our Education Programs, and in our classroom. Our first phase is: AWS. --- Advance To this Day --- - _Stage 1. Inititation (Completed)_ - Assist the introductory webinars informativos to understand the advantages of these programs: AWS educate & AWS academy. - Make conctact with Latam Personal, to ask about conditions in this adoption project of ours. - Register each of us (educators of ConTolTI) in AWS Educate to self train and understand this plataform. - Register the institution in AWS Academy, so we can start to traing and proceed with a later certificacion, of each one of our educators in ConSolTI. - _Stage 2. Training (to this day)_ - Selftrain of each of us (educators of ConTolTI) in AWS Educate in the first course: Cloud Foundationals. - My self in training at module 6 right now. - Two more educator accepted the nomination and area training in the course right now.
Ruby
UTF-8
11,877
2.75
3
[ "BSD-3-Clause" ]
permissive
module Rubyplot module Artist class Axes < Base TITLE_MARGIN = 10.0 LEGEND_MARGIN = 15.0 LABEL_MARGIN = 10.0 DEFAULT_MARGIN = 10.0 THOUSAND_SEPARATOR = ','.freeze # Rubyplot::Figure object to which this Axes belongs. attr_reader :figure # Array of plots contained in this Axes. attr_reader :plots attr_reader :font, :marker_font_size, :legend_font_size, :title_font_size, :scale, :font_color, :marker_color, :axes, :legend_margin, :backend, :marker_caps_height attr_reader :label_stagger_height # Rubyplot::Artist::XAxis object. attr_reader :x_axis # Rubyplot::Artist::YAxis object. attr_reader :y_axis # Position of the legend box. attr_accessor :legend_box_position # Set true if title is to be hidden. attr_accessor :hide_title # Top margin. attr_accessor :top_margin # Left margin. attr_accessor :left_margin # Bottom margin. attr_accessor :bottom_margin # Right margin. attr_accessor :right_margin attr_accessor :grid, :bounding_box, :title_shift # Main title for this Axes. attr_accessor :title # X co-ordinate of lower left corner of this Axes. attr_accessor :abs_x # Y co-ordinate of lower left corner of this Axes. attr_accessor :abs_y # Width of this Axes object. Between Rubyplot.min_x and max_x. attr_accessor :width # Height of this Axes object. Between Rubyplot.min_y and MAX_Y. attr_accessor :height # Font size of the Axes title in pt. scale. attr_accessor :title_font_size # Flag for square axes attr_accessor :square_axes # @param figure [Rubyplot::Figure] Figure object to which this Axes belongs. # @param abs_x [Float] Absolute X co-ordinate of the lower left corner of the Axes. # @param abs_y [Flot] Absolute Y co-ordinate of the lower left corner of the Axes. # @param width [Float] Width between MIN_X and MAX_Y of this Axes object. # @param height [Float] Height between MIN_Y and MAX_Y of this Axes object. def initialize(figure, abs_x:, abs_y:, width:, height:) @figure = figure @abs_x = abs_x @abs_y = abs_y @width = width @height = height @x_title = '' @y_title = '' @top_margin = 5.0 @left_margin = 10.0 @bottom_margin = 10.0 @right_margin = 5.0 @title = '' @title_shift = 0 @title_margin = TITLE_MARGIN @text_font = :default @grid = true @bounding_box = true @plots = [] @raw_rows = width * (height/width) @theme = Rubyplot::Themes::CLASSIC_WHITE @font = :times_roman @font_color = :black @font_size = 15.0 @legend_font_size = 20.0 @legend_margin = LEGEND_MARGIN @title_font_size = 25.0 @plot_colors = [] @legends = [] @lines = [] @texts = [] @x_axis = Rubyplot::Artist::XAxis.new(self) @y_axis = Rubyplot::Artist::YAxis.new(self) @legend_box_position = :top @square_axes = true end # X co-ordinate of the legend box depending on value of @legend_box_position. def legend_box_ix case @legend_box_position when :top abs_x + width / 2 end end # Y co-ordinate of the legend box depending on value of @legend_box_position. def legend_box_iy case @legend_box_position when :top abs_y + height - top_margin - legend_margin end end def process_data assign_default_label_colors consolidate_plots @plots.each(&:process_data) set_axes_ranges end # Write an image to a file by communicating with the backend. def draw Rubyplot.backend.active_axes = self configure_title configure_legends assign_x_ticks assign_y_ticks @x_axis.draw @y_axis.draw @texts.each(&:draw) @legend_box.draw @plots.each(&:draw) end def scatter!(*_args, &block) add_plot! :Scatter, &block end def bar!(*_args, &block) add_plot! :Bar, &block end def line!(*_args, &block) add_plot! :Line, &block end def area!(*_args, &block) add_plot! :Area, &block end def bubble!(*_args, &block) add_plot! :Bubble, &block end def stacked_bar!(*_args, &block) add_plot! :StackedBar, &block end def histogram!(*_args, &block) add_plot! :Histogram, &block end def candle_stick!(*_args, &block) add_plot! :CandleStick, &block end def error_bar!(*_args, &block) add_plot! :ErrorBar, &block end def box_plot!(*_args, &block) add_plot! :BoxPlot, &block end def plot!(*_args, &block) add_plot! :BasicPlot, &block end def write(file_name) @plots[0].write file_name end def x_ticks= x_ticks @x_axis.major_ticks = x_ticks end def y_ticks= y_ticks @y_axis.major_ticks = y_ticks end def x_title= x_title @x_axis.title = x_title end def x_title_font_size= x_font_size @x_axis.title_font_size = x_font_size end def y_title= y_title @y_axis.title = y_title end def y_title_font_size= y_font_size @y_axis.title_font_size = y_font_size end def x_range [@x_axis.min_val, @x_axis.max_val] end def y_range [@y_axis.min_val, @y_axis.max_val] end # Set the X range of the Axes. def x_range= xr @x_axis.min_val = xr[0] @x_axis.max_val = xr[1] end def y_range= xy @y_axis.min_val = xy[0] @y_axis.max_val = xy[1] end def origin [@x_axis.min_val, @y_axis.min_val] end private def add_plot! klass, &block plot = Kernel.const_get("Rubyplot::Artist::Plot::#{klass}").new self yield(plot) if block_given? @plots << plot end def assign_default_label_colors @plots.each_with_index do |p, i| if p.color == :default p.color = @figure.theme_options[:label_colors][ i % @figure.theme_options[:label_colors].size] end end end def assign_x_ticks value_distance = @x_axis.spread / (@x_axis.major_ticks_count.to_f - 1) unless @x_axis.major_ticks # create labels if not present @x_axis.major_ticks = @x_axis.major_ticks_count.times.map do |i| @x_axis.min_val + i * value_distance end end unless @x_axis.major_ticks.all? { |t| t.is_a?(Rubyplot::Artist::XTick) } @x_axis.major_ticks.map!.with_index do |tick_label, i| Rubyplot::Artist::XTick.new( self, coord: i * value_distance + @x_axis.min_val, label: Rubyplot::Utils.format_label(tick_label) ) end end @x_axis.minor_ticks = [] @x_axis.major_ticks.each_with_index do |major_tick, i| minor_tick_value_distance = value_distance / (@x_axis.minor_ticks_count.to_f + 1) if i < (@x_axis.major_ticks_count-1) # Skip the last tick for j in 1..@x_axis.minor_ticks_count do @x_axis.minor_ticks.push(major_tick.coord + j * minor_tick_value_distance) end end end unless @x_axis.minor_ticks.all? { |t| t.is_a?(Rubyplot::Artist::XTick) } @x_axis.minor_ticks.map!.with_index do |coord, i| Rubyplot::Artist::XTick.new( self, coord: coord, label: nil, tick_size: @x_axis.major_ticks[0].tick_size/2 ) end end end def assign_y_ticks value_distance = @y_axis.spread / (@y_axis.major_ticks_count.to_f-1) unless @y_axis.major_ticks @y_axis.major_ticks = (y_range[0]..y_range[1]).step(value_distance).map { |i| i } end unless @y_axis.major_ticks.all? { |t| t.is_a?(Rubyplot::Artist::YTick) } @y_axis.major_ticks.map!.with_index do |tick_label, i| Rubyplot::Artist::YTick.new( self, coord: @y_axis.min_val + i * value_distance, label: Rubyplot::Utils.format_label(tick_label) ) end end @y_axis.minor_ticks = [] @y_axis.major_ticks.each_with_index do |major_tick, i| minor_tick_value_distance = value_distance / (@y_axis.minor_ticks_count.to_f + 1) if i < (@y_axis.major_ticks_count-1) # Skip the last tick for j in 1..@y_axis.minor_ticks_count do # Skip the 0th index as major tick is already present @y_axis.minor_ticks.push(major_tick.coord + j * minor_tick_value_distance) end end end unless @y_axis.minor_ticks.all? { |t| t.is_a?(Rubyplot::Artist::YTick) } @y_axis.minor_ticks.map!.with_index do |coord, i| Rubyplot::Artist::XTick.new( self, coord: coord, label: nil, tick_size: @y_axis.major_ticks[0].tick_size/2 ) end end end # Figure out the co-ordinates of the title text w.r.t Axes. def configure_title @texts << Rubyplot::Artist::Text.new( @title, self, abs_x: abs_x + width / 2, abs_y: abs_y + height, font: @font, color: @font_color, size: @title_font_size, internal_label: 'axes title.') end # Figure out co-ordinates of the legends def configure_legends @legend_box = Rubyplot::Artist::LegendBox.new( self, abs_x: legend_box_ix, abs_y: legend_box_iy ) end def consolidate_plots bars = @plots.grep(Rubyplot::Artist::Plot::Bar) unless bars.empty? @plots.delete_if { |p| p.is_a?(Rubyplot::Artist::Plot::Bar) } @plots << Rubyplot::Artist::Plot::MultiBars.new(self, bar_plots: bars) end stacked_bars = @plots.grep(Rubyplot::Artist::Plot::StackedBar) unless stacked_bars.empty? @plots.delete_if { |p| p.is_a?(Rubyplot::Artist::Plot::StackedBar) } @plots << Rubyplot::Artist::Plot::MultiStackedBar.new(self, stacked_bars: stacked_bars) end candle_sticks = @plots.grep(Rubyplot::Artist::Plot::CandleStick) unless candle_sticks.empty? @plots.delete_if { |p| p.is_a?(Rubyplot::Artist::Plot::CandleStick) } @plots << Rubyplot::Artist::Plot::MultiCandleStick.new(self, candle_sticks: candle_sticks) end box_plots = @plots.grep(Rubyplot::Artist::Plot::BoxPlot) unless box_plots.empty? @plots.delete_if { |p| p.is_a?(Rubyplot::Artist::Plot::BoxPlot) } @plots << Rubyplot::Artist::Plot::MultiBoxPlot.new(self, box_plots: box_plots) end end def set_axes_ranges set_xrange set_yrange end def set_xrange if @x_axis.min_val.nil? @x_axis.min_val = @plots.map(&:x_min).min end if @x_axis.max_val.nil? @x_axis.max_val = @plots.map(&:x_max).max end end def set_yrange if @y_axis.min_val.nil? @y_axis.min_val = @plots.map(&:y_min).min end if @y_axis.max_val.nil? @y_axis.max_val = @plots.map(&:y_max).max end end end # class Axes end # module Artist end # module Rubyplot
Shell
UTF-8
793
2.59375
3
[]
no_license
#!/bin/bash echo 'alias p="docker run --rm -it -v /tmp/demo:/tmp/demo clearhaus/pedicel-pay"' function p() { docker run --rm -it -v /tmp/demo:/tmp/demo clearhaus/pedicel-pay $@ } p clean -p /tmp/demo/backend p clean -p /tmp/demo/client set -x read; clear p read; clear p help generate-backend read; clear p generate-backend -p /tmp/demo/backend read; clear p help generate-client read; clear p generate-client -p /tmp/demo/client -b /tmp/demo/backend read; clear p help generate-token read; clear p generate-token -b /tmp/demo/backend -c /tmp/demo/client | tee /tmp/demo/token.json read; clear set +x cat <<EOC docker run --rm -it -v /tmp/demo:/tmp/demo -v ~/src/clearhaus/pedicel:/p -w /p ruby:2.3 bash bundle install --without development irb -I lib -r pedicel -r json -r pp EOC
Go
UTF-8
1,042
3.71875
4
[]
no_license
package main import ( "container/heap" ) type intHeap []int func (h intHeap) Len() int { return len(h) } func (h intHeap) Less(i, j int) bool { return h[i] < h[j] } func (h intHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *intHeap) Push(x interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, // not just its contents. *h = append(*h, x.(int)) } func (h *intHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } func mergeKLists(lists []*ListNode) *ListNode { h := &intHeap{} for _, l := range lists { for p := l; p != nil; p = p.Next { // heap.Push(h, p.Val) // 之前插入元素时,无需始终保持堆序性质,使用直接向尾部添加的方式即可 h.Push(p.Val) } } heap.Init(h) tail := &ListNode{Val: -1} dummyHead := tail for h.Len() > 0 { node := heap.Pop(h) if val, ok := node.(int); ok { tail.Next = &ListNode{Val: val} tail = tail.Next } } return dummyHead.Next }
C
UTF-8
5,959
3.46875
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int ElemType; typedef int Status; //如果*T字符串串有值,直接释放free掉,之后malloc /* c4-2.h 串的堆分配存储 */ typedef struct { char *ch; /* 若是非空串,则按串长分配存储区,否则ch为NULL */ //char 数组指针 int length; /* 串长度 */ }HString; /* bo4-2.c 串采用堆分配存储结构(由c4-2.h定义)的基本操作(15个) */ /* 包括算法4.1、4.4 */ Status StrAssign(HString *T, char *chars) { /* 生成一个其值等于串常量chars的串T */ int i, j; if ((*T).ch) //如果*T字符串串有值 free((*T).ch); /* 释放T原有空间 */ i = strlen(chars); /* 求chars的长度i */ if (!i) { /* chars的长度为0 */ (*T).ch = NULL; (*T).length = 0; } else { /* chars的长度不为0 */ (*T).ch = (char*)malloc(i * sizeof(char)); /* 分配串空间 */ if (!(*T).ch) /* 分配串空间失败 */ exit(OVERFLOW); for (j = 0; j < i; j++) /* 拷贝串 */ (*T).ch[j] = chars[j]; (*T).length = i; } return OK; } /* 生成一个其值等于串常量chars的串T */ Status StrCopy(HString *T, HString S) { /* 初始条件:串S存在。操作结果: 由串S复制得串T */ int i; if ((*T).ch) //如果*T字符串串有值 free((*T).ch); /* 释放T原有空间 */ (*T).ch = (char*)malloc(S.length * sizeof(char)); /* 分配串空间 */ if (!(*T).ch) /* 分配串空间失败 */ exit(OVERFLOW); for (i = 0; i < S.length; i++) /* 拷贝串 */ (*T).ch[i] = S.ch[i]; (*T).length = S.length; return OK; } /* 初始条件:串S存在。操作结果: 由串S复制得串T */ Status StrEmpty(HString S) { /* 初始条件: 串S存在。操作结果: 若S为空串,则返回TRUE,否则返回FALSE */ if (S.length == 0 && S.ch == NULL) return TRUE; else return FALSE; } int StrCompare(HString S, HString T) { /* 若S>T,则返回值>0;若S=T,则返回值=0;若S<T,则返回值<0 */ int i; for (i = 0; i < S.length && i < T.length; ++i) if (S.ch[i] != T.ch[i]) return S.ch[i] - T.ch[i]; return S.length - T.length; } int StrLength(HString S) { /* 返回S的元素个数,称为串的长度 */ return S.length; } Status ClearString(HString *S) { /* 将S清为空串 */ if ((*S).ch) { free((*S).ch); (*S).ch = NULL; } (*S).length = 0; return OK; } Status Concat(HString *T, HString S1, HString S2) { /* 用T返回由S1和S2联接而成的新串 */ int i; if ((*T).ch) free((*T).ch); /* 释放旧空间 */ (*T).length = S1.length + S2.length; (*T).ch = (char *)malloc((*T).length * sizeof(char)); if (!(*T).ch) exit(OVERFLOW); for (i = 0; i < S1.length; i++) (*T).ch[i] = S1.ch[i]; for (i = 0; i < S2.length; i++) (*T).ch[S1.length + i] = S2.ch[i]; return OK; } Status SubString(HString *Sub, HString S, int pos, int len) { /* 用Sub返回串S的第pos个字符起长度为len的子串。 */ /* 其中,1≤pos≤StrLength(S)且0≤len≤StrLength(S)-pos+1 */ int i; if (pos<1 || pos>S.length || len<0 || len>S.length - pos + 1) return ERROR; if ((*Sub).ch) free((*Sub).ch); /* 释放旧空间 */ if (!len) /* 空子串 */ { (*Sub).ch = NULL; (*Sub).length = 0; } else { /* 完整子串 */ (*Sub).ch = (char*)malloc(len * sizeof(char)); if (!(*Sub).ch) exit(OVERFLOW); for (i = 0; i <= len - 1; i++) (*Sub).ch[i] = S.ch[pos - 1 + i]; (*Sub).length = len; } return OK; } void InitString(HString *T) { /* 初始化(产生空串)字符串T。另加 */ (*T).length = 0; (*T).ch = NULL; } int Index(HString S, HString T, int pos) /* 算法4.1 */ { /* T为非空串。若主串S中第pos个字符之后存在与T相等的子串, */ /* 则返回第一个这样的子串在S中的位置,否则返回0 */ int n, m, i; HString sub; InitString(&sub); if (pos > 0) { n = StrLength(S); m = StrLength(T); i = pos; while (i <= n - m + 1) { SubString(&sub, S, i, m); if (StrCompare(sub, T) != 0) ++i; else return i; } } return 0; } Status StrInsert(HString *S, int pos, HString T) /* 算法4.4 */ { /* 1≤pos≤StrLength(S)+1。在串S的第pos个字符之前插入串T */ int i; if (pos<1 || pos>(*S).length + 1) /* pos不合法 */ return ERROR; if (T.length) /* T非空,则重新分配空间,插入T */ { (*S).ch = (char*)realloc((*S).ch, ((*S).length + T.length) * sizeof(char)); if (!(*S).ch) exit(OVERFLOW); for (i = (*S).length - 1; i >= pos - 1; --i) /* 为插入T而腾出位置 */ (*S).ch[i + T.length] = (*S).ch[i]; for (i = 0; i < T.length; i++) (*S).ch[pos - 1 + i] = T.ch[i]; /* 插入T */ (*S).length += T.length; } return OK; } Status StrDelete(HString *S, int pos, int len) { /* 从串S中删除第pos个字符起长度为len的子串 */ int i; if ((*S).length < pos + len - 1) exit(ERROR); for (i = pos - 1; i <= (*S).length - len; i++) (*S).ch[i] = (*S).ch[i + len]; (*S).length -= len; (*S).ch = (char*)realloc((*S).ch, (*S).length * sizeof(char)); return OK; } Status Replace(HString *S, HString T, HString V) { /* 初始条件: 串S,T和V存在,T是非空串(此函数与串的存储结构无关) */ /* 操作结果: 用V替换主串S中出现的所有与T相等的不重叠的子串 */ int i = 1; /* 从串S的第一个字符起查找串T */ if (StrEmpty(T)) /* T是空串 */ return ERROR; do { i = Index(*S, T, i); /* 结果i为从上一个i之后找到的子串T的位置 */ if (i) /* 串S中存在串T */ { StrDelete(S, i, StrLength(T)); /* 删除该串T */ StrInsert(S, i, V); /* 在原串T的位置插入串V */ i += StrLength(V); /* 在插入的串V后面继续查找串T */ } } while (i); return OK; } void DestroyString() { /* 堆分配类型的字符串无法销毁 */ } void StrPrint(HString T) { /* 输出T字符串。另加 */ int i; for (i = 0; i < T.length; i++) printf("%c", T.ch[i]); printf("\n"); }
Swift
UTF-8
1,189
3.390625
3
[]
no_license
// // colorjSONModel.swift // ParsingJSON // // Created by Bienbenido Angeles on 12/2/19. // Copyright © 2019 Bienbenido Angeles. All rights reserved. // import Foundation struct ColorData: Codable{ var colors: [Colors] } struct Colors:Codable { var hex: HexData var rgb: RGBData var name: NameData } struct HexData:Codable { var value:String var clean: String } struct RGBData: Codable { var fraction: RGBDecimalVal var value: String } struct NameData:Codable { var value: String } struct RGBDecimalVal:Codable { var r: Double var g: Double var b: Double } extension Colors{ static func getColor() -> [Colors]{ var colors = [Colors]() guard let fileURL = Bundle.main.url(forResource: "colorData", withExtension: "json") else { fatalError("colorData.json not found") } do{ let data = try Data(contentsOf: fileURL) let colorData = try JSONDecoder().decode(ColorData.self, from: data) colors = colorData.colors }catch{ print("Could not load data. Error: \(error)") } return colors } }
C#
UTF-8
3,210
2.546875
3
[]
no_license
using PersonaDetalle.BLL; using PersonaDetalle.Entidades; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PersonaDetalle.UI.Registro { public partial class RegistroTipoTelefono : Form { public RegistroTipoTelefono() { InitializeComponent(); } public void Limpiar() { idTelefonoNumericUpDown.Value = 0; tipoTelefonoTextBox.Text = string.Empty; } private void GuardarButton_Click(object sender, EventArgs e) { bool paso = false; TipoTelefono telefono = new TipoTelefono() { TipoId = 0, TipoTelefonoR = tipoTelefonoTextBox.Text }; if (idTelefonoNumericUpDown.Value == 0) paso = TipoTelefonoBLL.Guardar(telefono); else { if (!ExisteEnLaBaseDeDatos()) { MessageBox.Show("No se puede Modificar un Tipo no existente", "Fallo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } paso = TipoTelefonoBLL.Modificar(telefono); } if (paso) { MessageBox.Show("Tipo Guardado!", "Exito!!", MessageBoxButtons.OK, MessageBoxIcon.Information); Limpiar(); } else MessageBox.Show("Tipo No guardado!!", "Fallo", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void Buscar_Click(object sender, EventArgs e) { var tipo = TipoTelefonoBLL.Buscar((int)idTelefonoNumericUpDown.Value); if (tipo != null) { idTelefonoNumericUpDown.Value = tipo.TipoId; tipoTelefonoTextBox.Text = tipo.TipoTelefonoR; MessageBox.Show("Encontrado", "Exito!!", MessageBoxButtons.OK, MessageBoxIcon.Information); } else MessageBox.Show("No Encontrado", "Fallo!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void EliminarButton_Click(object sender, EventArgs e) { int id; int.TryParse(idTelefonoNumericUpDown.Text, out id); if (!ExisteEnLaBaseDeDatos()) return; if (TipoTelefonoBLL.Eliminar(id)) { MessageBox.Show("Tipo de Telefono Eliminado!!", "Exito!!", MessageBoxButtons.OK, MessageBoxIcon.Information); Limpiar(); } else MessageBox.Show("Tipo de Telefono No Eliminado!!", "Fallo", MessageBoxButtons.OK, MessageBoxIcon.Error); } private bool ExisteEnLaBaseDeDatos() { TipoTelefono telefono = TipoTelefonoBLL.Buscar((int)idTelefonoNumericUpDown.Value); return (telefono != null); } private void NuevoButton_Click(object sender, EventArgs e) { Limpiar(); } } }
Java
UTF-8
1,013
2.859375
3
[]
no_license
package org.tsinghuatj.framework.constants; import java.util.EnumSet; public enum RoleEnum { admin(1, "管理员"), // warehouseKeeper(2, "仓库"), quality(3, "质检"), // repaire(4, "刃磨"), // technology(5, "工艺"),;// private Integer code; private String roleName; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } private RoleEnum(int code, String roleName) { this.setCode(code); this.setRoleName(roleName); } public static String getName(int code) { for (RoleEnum entity : EnumSet.allOf(RoleEnum.class)) { if (code == entity.getCode()) { return entity.getRoleName(); } } return null; } public static int getCode(String name) { for (RoleEnum entity : EnumSet.allOf(RoleEnum.class)) { if (name.equals(entity.getRoleName())) { return entity.getCode(); } } return 0; } }
Java
UHC
1,303
3.328125
3
[]
no_license
package com.day6; import java.util.Random; import java.util.Scanner; public class Quest2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Random rd = new Random(); int cnt; int num,a; String user= ""; while(true) { cnt=1; num = rd.nextInt(10)+1; while(true) { System.out.printf(" Էϼ.(%d° ȸ) : ",cnt); a= sc.nextInt(); if(a != num) { System.out.println("ƲȽϴ."); cnt++; }else if( a == num ){ System.out.println("Դϴ!"); break; }else { System.out.println("ȿ Դϴ. (1~10) Էּ"); } if(cnt>3) { break; } } System.out.printf(" %dԴϴ.\n",num); System.out.print("Ͻðڽϱ? (Y/N) : "); user = sc.next(); if(user.equals("N")||user.equals("n")) { System.out.println("մϴ."); break; }else if(user.equals("Y")||user.equals("y")){ continue; }else System.out.println("߸ Դϴ. ѹ մϴ."); System.out.println(""); } } }
Markdown
UTF-8
4,735
2.953125
3
[ "MIT" ]
permissive
--- layout: post title: "My year in books" modified: categories: blog excerpt: My favorite reads of 2015 tags: [books] image: feature: author: prateek_nigam date: 2015-12-25T12:39:55-04:00 share: true --- I read 22 books this year which was a personal best, just 2 shy of 2 books a month. A total of 8000 pages. :D I am going to aim a bit higher next year and read 30 books. Before I start picking out books for next year, let me break down 2015 in books by listing the top 10 books that I read this year. ![bookshelf 2015](http://iag0.github.io/images/yib1.png "bookshelf") <img src="http://iag0.github.io/images/yib2.png" width="272" height="170"> ###10. [Flowers for Algernon: Daniel Keyes](http://www.goodreads.com/book/show/18373.Flowers_for_Algernon) An autistic man becomes a subject for an experimental treatment that makes him a high functioning genius. All we read is the journal that the subject writes, yet the book is written in a manner that brings its characters alive. It may be science fiction, but keeps the character treatment sympathetic and humane. Beautifully written. I absolutely recommend this book to everyone. ###9. [The Last lecture: Randy Pausch](http://www.goodreads.com/book/show/2318271.The_Last_Lecture) Randy Pausch had just months to live, but a lifetime worth of advice to give. Not to the world, but to his kids. And he pens it down in the most simple way. A book worth reading and re-reading. ###8. [The Martian: Andy Weir](http://www.goodreads.com/book/show/18007564-the-martian) I got on the Martian bandwagon even before the movie was announced. I thoroughly enjoyed this book, which was more like Robinson Crusoe on Mars. I remember reading this book really did feel like sols Mark Watney spends trying to cross the Schiaprelly crater. The movie unfortunately failed to capture the essence of the book; i.e the journey on the barren planet. ###7. [A fine balance: Rohinton Mistry](http://www.goodreads.com/book/show/5211.A_Fine_Balance) From a previous post, you can figure out that I loved this book. Yet I am struggling to place it higher up because of the amount of sadness that is filled in this book. The tragedies that a pair of tailors suffer through a politically tumultuous years of emergency are heartbreaking to say the least. I cannot get myself to read this book again. ###6. [Slade House: David Mitchell](http://www.goodreads.com/book/show/24499258-slade-house) This is the first horror novella that I have read and though it quite doesn't work like it does in the movies, reading scary novels has a different charm. A set of stories surrounding a haunted house, this book is worth being made into a movie. Absolutely loved it. ###5. [Do Androids dream of electric sheep: Philip K. Dick](http://www.goodreads.com/book/show/7082.Do_Androids_Dream_of_Electric_Sheep_) This movie "Blade Runner" was kind of adapted from this book. Convinced yet? Again we learn how true science fiction is less about technology and more about how it affects human. This book has androids living amongst us, but with blurring lines, PKD explores the age old question of what it is to be human after all. ###4. [Sapiens: A brief history of humankind: Yual Noah Harari](http://www.goodreads.com/book/show/23692271-sapiens) Brilliant account of how humankind reached where it stands today. What worked and what did not in the history. Fascinating read. I was thoroughly entertained throughout the book. ###3. [Midnight's children: Salman Rushdie](http://www.goodreads.com/book/show/14836.Midnight_s_Children) I am nobody to be judging Midnight's children. All I can comment upon is my experience with it. Its a magnum opus, and a book that stands on its own right. It may have made for a lousy movie, but Salman Rushdie is master of his craft. Though there are parts which felt a bit forced and stretched out, this book makes for a wonderful read. It reminded me a lot of "A 100 years of solitude" in terms of narration. Absolute must read. ###2. [Piccadily Jim: P. G. Wodehouse](http://www.goodreads.com/book/show/18077.Piccadilly_Jim) Utter confusion, mistaken identity often ensues hilarity. This is my first Wodehouse, and I do not remember laughing as hard while reading any other novel. This book is funny as hell. ###1. [Cat's cradle: Kurt Vonnegut](http://www.goodreads.com/book/show/135479.Cat_s_Cradle) Kurt Vonnegut is a writer in his own right. The book is about a journalist writing a piece on the team responsible for creating the hydrogen bomb and stumbles upon a deadly weapon that could put the world in peril. His quest to solve this mystery takes him to a carribean island with a strange religion. Vonnegut invents a Bokonomism, a new age religion with its own creation myth and the whole shbang. This book is worth reading multiple times. Its a funny and entertaining "thriller".
Go
UTF-8
234
2.5625
3
[ "Apache-2.0" ]
permissive
package entity import uuid "github.com/satori/go.uuid" var genUUID = uuid.NewV4 func New(firstName, lastName string) *Account { return &Account{ UUID: genUUID().String(), FirstName: firstName, LastName: lastName, } }
C#
UTF-8
1,774
2.734375
3
[]
no_license
 using System; using System.Collections.Generic; using CoreGraphics; using ReadyToUseUIDemo.model; using UIKit; namespace ReadyToUseUIDemo.iOS.View { public class ButtonContainer : UIView { public UILabel Title { get; private set; } public List<ScannerButton> Buttons { get; private set; } nfloat padding = 15; nfloat titleHeight, buttonHeight; public nfloat Height { get { return titleHeight + (Buttons.Count * buttonHeight) + (Buttons.Count * padding); } } public ButtonContainer(string title, List<ListItem> data) { Title = new UILabel(); Title.Text = title; Title.Font = UIFont.FromName("HelveticaNeue-Bold", 13f); Title.TextColor = Colors.DarkGray; AddSubview(Title); Buttons = new List<ScannerButton>(); foreach(ListItem item in data) { var button = new ScannerButton(item); AddSubview(button); Buttons.Add(button); } titleHeight = 20; buttonHeight = 30; } public override void LayoutSubviews() { base.LayoutSubviews(); nfloat x = padding; nfloat y = 0; nfloat w = Frame.Width - 2 * padding; nfloat h = titleHeight; Title.Frame = new CGRect(x, y, w, h); y += h + padding; h = buttonHeight; foreach(ScannerButton button in Buttons) { button.Frame = new CGRect(x, y, w, h); y += h + padding; } } } }
Java
UTF-8
5,982
1.960938
2
[]
no_license
package com.example.juicekaaa.fireserver.activity; import android.annotation.SuppressLint; import android.content.Intent; import android.media.MediaPlayer; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.MediaController; import android.widget.TextView; import com.example.juicekaaa.fireserver.MainActivity; import com.example.juicekaaa.fireserver.R; import com.example.juicekaaa.fireserver.utils.FullVideoView; import com.example.juicekaaa.fireserver.utils.SosDialog; import com.romainpiel.shimmer.Shimmer; import com.romainpiel.shimmer.ShimmerTextView; import java.io.File; /** * 功能首页 */ public class FunctionHomeActivity extends BaseActivity implements View.OnClickListener { private FullVideoView videos; private TextView funtion_material; private TextView funtion_opendoor; private TextView funtion_sos; private TextView funtion_propaganda; private TextView online_help; private ShimmerTextView myShimmerTextView; private Shimmer shimmer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.funtion_homes_activity); intiView(); } @Override protected int getLayoutRes() { return R.layout.funtion_home_activity; } //初始化 private void intiView() { myShimmerTextView = findViewById(R.id.shimmer_tv); videos = findViewById(R.id.videos); funtion_material = findViewById(R.id.funtion_material); funtion_opendoor = findViewById(R.id.funtion_opendoor); funtion_sos = findViewById(R.id.funtion_sos); funtion_propaganda = findViewById(R.id.funtion_propaganda); online_help = findViewById(R.id.online_help); funtion_material.setOnClickListener(this); funtion_opendoor.setOnClickListener(this); funtion_sos.setOnClickListener(this); funtion_propaganda.setOnClickListener(this); online_help.setOnClickListener(this); } @Override protected void onResume() { hideBottomUIMenu(); setVideo(); shimmer = new Shimmer(); shimmer.start(myShimmerTextView); super.onResume(); } /** * 设置视频参数 */ @SuppressLint("ClickableViewAccessibility") private void setVideo() { videos = findViewById(R.id.videos); MediaController mediaController = new MediaController(FunctionHomeActivity.this); mediaController.setVisibility(View.GONE);//隐藏进度条 videos.setMediaController(mediaController); File file = new File(Environment.getExternalStorageDirectory() + "/" + "FireVideo", "1542178640266.mp4"); videos.setVideoPath(file.getAbsolutePath()); videos.start(); videos.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.start(); mediaPlayer.setLooping(true); } }); videos.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { shimmer.cancel(); Intent i = new Intent(FunctionHomeActivity.this, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(i); finish(); return false; } }); } @Override public void onClick(View v) { switch (v.getId()) { //物资 case R.id.funtion_material: shimmer.cancel(); Intent funtion_material = new Intent(FunctionHomeActivity.this, FunctionOperationActivity.class); startActivity(funtion_material); break; //开门 case R.id.funtion_opendoor: shimmer.cancel(); Intent funtion_opendoor = new Intent(FunctionHomeActivity.this, FunctionOperationActivity.class); startActivity(funtion_opendoor); break; //SOS case R.id.funtion_sos: SosDialog sosDialog = new SosDialog(FunctionHomeActivity.this); sosDialog.show(); break; //宣传 case R.id.funtion_propaganda: break; //在线帮助 case R.id.online_help: shimmer.cancel(); Intent funtion_help = new Intent(FunctionHomeActivity.this, FunctionHelpActivity.class); startActivity(funtion_help); break; } } @Override public void onBackPressed() { return;//在按返回键时的操作 } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { return true; } else { return super.onKeyDown(keyCode, event); } } /** * 隐藏虚拟按键,并且全屏 */ protected void hideBottomUIMenu() { //隐藏虚拟按键,并且全屏 if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api View v = this.getWindow().getDecorView(); v.setSystemUiVisibility(View.GONE); } else if (Build.VERSION.SDK_INT >= 19) { //for new api versions. View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); } } @Override protected void onDestroy() { super.onDestroy(); shimmer.cancel(); } }
Java
UTF-8
6,237
1.835938
2
[]
no_license
/******************************************************************************* * Copyright (c) 2017 ModelSolv, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * ModelSolv, Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ package com.reprezen.jsonoverlay; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.MissingNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import com.fasterxml.jackson.databind.node.ValueNode; public abstract class JsonOverlay<V> extends AbstractJsonOverlay<V> { protected final static ObjectMapper mapper = new ObjectMapper(); protected V value = null; protected JsonOverlay<?> parent; protected JsonNode json = null; protected ReferenceRegistry refReg; private String pathInParent = null; private Reference reference = null; public JsonOverlay(V value, JsonOverlay<?> parent, ReferenceRegistry refReg) { this.value = value; this.parent = parent; this.refReg = refReg; } public JsonOverlay(JsonNode json, JsonOverlay<?> parent, ReferenceRegistry refReg) { this.json = json; this.value = fromJson(json); this.parent = parent; this.refReg = refReg; } protected void setReference(Reference reference) { this.reference = reference; } @Override /* protected */boolean _isPresent() { return value != null && !json.isMissingNode(); } @Override /* package */boolean _isElaborated() { // most overlays are complete when constructed return true; } @Override /* package */ AbstractJsonOverlay<?> _find(JsonPointer path) { return path.matches() ? this : _findInternal(path); } abstract protected AbstractJsonOverlay<?> _findInternal(JsonPointer path); @Override /* package */ AbstractJsonOverlay<?> _find(String path) { return _find(JsonPointer.compile(path)); } /* package */ V _get() { return value; } /* package */void _set(V value) { _set(value, true); } protected void _set(V value, boolean invalidate) { this.value = value; } /* package */ JsonOverlay<?> _getParent() { return parent; } protected void setParent(JsonOverlay<?> parent) { this.parent = parent; } protected void setPathInParent(String pathInParent) { this.pathInParent = pathInParent; } /* package */String _getPathInParent() { return pathInParent; } /* package */String _getPathFromRoot() { return parent != null ? (parent._getParent() != null ? parent._getPathFromRoot() : "") + "/" + pathInParent : "/"; } @Override /* package */URL _getJsonReference() { URL result = null; try { if (reference != null) { result = new URL(reference.getCanonicalRefString()); } else { URL parentUrl = parent != null ? parent._getJsonReference() : null; if (parentUrl != null) { JsonPointer ptr = JsonPointer.compile(parentUrl.getRef()); ptr = ptr.append(JsonPointer.compile("/" + pathInParent)); result = new URL(parentUrl, "#" + ptr.toString()); } } } catch (IllegalArgumentException | MalformedURLException e) { } return result; } /* package */JsonOverlay<?> _getRoot() { return parent != null ? parent._getRoot() : this; } protected abstract V fromJson(JsonNode json); protected void elaborate() { } private static final SerializationOptions emptyOptions = new SerializationOptions(); @Override /* package */JsonNode _toJson() { return _toJsonInternal(emptyOptions); } @Override /* package */JsonNode _toJson(SerializationOptions.Option... options) { return _toJsonInternal(new SerializationOptions(options)); } @Override /* package */JsonNode _toJson(SerializationOptions options) { return _toJsonInternal(options); } /* package */abstract JsonNode _toJsonInternal(SerializationOptions options); // some utility classes for overlays protected static ObjectNode jsonObject() { return JsonNodeFactory.instance.objectNode(); } protected static ArrayNode jsonArray() { return JsonNodeFactory.instance.arrayNode(); } protected static TextNode jsonScalar(String s) { return JsonNodeFactory.instance.textNode(s); } protected static ValueNode jsonScalar(int n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonScalar(long n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonScalar(short n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonScalar(byte n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonScalar(double n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonScalar(float n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonScalar(BigInteger n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonScalar(BigDecimal n) { return JsonNodeFactory.instance.numberNode(n); } protected static ValueNode jsonBoolean(boolean b) { return JsonNodeFactory.instance.booleanNode(b); } protected static MissingNode jsonMissing() { return MissingNode.getInstance(); } protected static NullNode jsonNull() { return JsonNodeFactory.instance.nullNode(); } protected static final <T> Iterable<T> iterable(final Iterator<T> iterator) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } @Override public String toString() { return _toJson().toString(); } }
Java
UTF-8
6,253
2.09375
2
[]
no_license
package com.mt4.api; import com.mt4.api.bean.ConGroup; import com.mt4.api.bean.MarginLevel; import com.mt4.api.bean.RateInfo; import com.mt4.api.bean.ReportGroupRequest; import com.mt4.api.bean.SymbolInfo; import com.mt4.api.bean.TickRecord; import com.mt4.api.bean.TradeRecord; import com.mt4.api.bean.TradeTransInfo; import com.mt4.api.bean.UserRecord; public class MT4 implements ConnectorAPI{ //manager的指针地址 private int ptr; public MT4() { ptr = init(); if(ptr<0){ throw new RuntimeException(); } } /** * 初始化 * @return 返回CManagerInterface实例的地址 */ private native int init(); /** * 释放manager实例 * @param ptr * @return */ private native int Release(int ptr); /** * 获取错误信息 * @param ptr * @param code * @return */ private native String ErrorDescription(int ptr,int code); /** * 连接到服务端 * @param ptr * @param server * @return */ private native int Connect(int ptr,String server); /** * 断开链接 * @param ptr * @return */ private native int Disconnect(int ptr); /** * 是否连接 * @param ptr * @return */ private native int IsConnected(int ptr); /** * 心跳 * @param ptr * @return */ private native int Ping(int ptr); /** * 登陆 * @param ptr * @param uid * @param password * @return */ private native int Login(int ptr,int uid,String password); /** * 加载socket */ private static native void WinsockStartup(); private native long ServerTime(int ptr); //orders /** * 查询交易信息 * @param ptr * @return */ private native TradeRecord[] TradesRequest(int ptr); /** * 查询用户交易信息 * @param ptr * @return */ private native TradeRecord[] TradesUserHistory(int ptr); /** * 查询指定用户交易信息 * @param ptr * @param login * @param from * @param to * @return */ private native TradeRecord[] getTradesUserHistory(int ptr,int login,long from,long to); /** * 查询交易信息 * @param ptr * @param login * @param from * @param to * @return */ private native TradeRecord[] TradesGet(int ptr); /** * 用户创建 * @param ptr * @return */ private native int UserRecordNew(int ptr,UserRecord user); /** * 更新用户 * @param ptr * @return */ private native int UserRecordUpdate(int ptr,UserRecord user); /** * 查询用户列表 * @param ptr * @return */ private native UserRecord[] UserRecordsRequest(int ptr,int[] login); /** * 查询用户列表 * @param ptr * @return */ private native UserRecord[] UsersRequest(int ptr); /** * 查询组列表 * @param ptr * @return */ private native ConGroup[] GroupsRequest(int ptr); /** * 增加分组 * @param group * @return */ private native int CfgUpdateGroup(int ptr,ConGroup group); /** * 账户余额操作 * @return */ private native int TradeTransaction(int ptr,TradeTransInfo info); private native MarginLevel[] MarginsGet(int ptr); private native MarginLevel MarginLevelRequest(int ptr,int login); private native TradeRecord[] ReportsRequest(int ptr,ReportGroupRequest req,int[] logins); private native TickRecord[] TicksRequest(int ptr,String symbol,long from,long to ,char flag); private native TickRecord[] TickInfoLast(int ptr,String symbol); private native RateInfo[] ChartRequest(int ptr,String symbol,int period,long start,long end,long timesign,int mode); private native SymbolInfo SymbolInfoGet(int ptr,String symbol); private native int SymbolAdd(int ptr,String symbol); static{ System.loadLibrary("MTConnector64"); WinsockStartup(); } @Override public int release() { return Release(ptr); } @Override public String getErrorDescription(int code) { return ErrorDescription(ptr,code); } @Override public int connect(String server) { return Connect(ptr, server); } @Override public int disconnect() { return Disconnect(ptr); } @Override public boolean isConnected() { return IsConnected(ptr)==1; } @Override public int ping(){ return Ping(ptr); } @Override public int login(int uid, String password) { return Login(ptr, uid, password); } @Override public long serverTime(){ return ServerTime(ptr); } @Override public TradeRecord[] tradesRequest() { return TradesRequest(ptr); } @Override public int userRecordNew(UserRecord user){ return UserRecordNew(ptr, user); } @Override public UserRecord[] usersRequest(){ return UsersRequest(ptr); } @Override public UserRecord[] userRecordsRequest(int[] login){ return UserRecordsRequest(ptr,login); } @Override public ConGroup[] groupsRequest(){ return GroupsRequest(ptr); } @Override public int cfgUpdateGroup(ConGroup group){ return CfgUpdateGroup(ptr,group); } @Override public TradeRecord[] getTradesUserHistory(int login,long from,long to ){ return getTradesUserHistory(ptr, login, from, to); } @Override public int userRecordUpdate(UserRecord user){ return UserRecordUpdate(ptr, user); } @Override public TradeRecord[] tradesGet(){ return TradesGet(ptr); } @Override public int tradeTransaction(TradeTransInfo info){ return TradeTransaction(ptr,info); } @Override public MarginLevel[] marginsGet(){ return MarginsGet(ptr); } @Override public MarginLevel marginLevelRequest(int login){ return MarginLevelRequest(ptr,login); } @Override public TradeRecord[] reportsRequest(ReportGroupRequest req,int[] logins){ return ReportsRequest(ptr,req,logins); } /** * 历史价格查询 * @return */ @Override public TickRecord[] ticksRequest(String symbol,long from,long to ,char flag){ return TicksRequest(ptr,symbol,from,to,flag); } @Override public TickRecord[] tickInfoLast(String symbol){ return TickInfoLast(ptr,symbol); } @Override public RateInfo[] chartRequest(String symbol,int period,long start,long end,long timesign,int mode){ return ChartRequest(ptr, symbol, period, start, end, timesign, mode); } @Override public SymbolInfo symbolInfoGet(String symbol){ return SymbolInfoGet(ptr, symbol); } @Override public int symbolAdd(String symbol){ return SymbolAdd(ptr, symbol); } }
Java
UTF-8
501
1.992188
2
[]
no_license
package pl.luckyit.test.controller; import pl.luckyit.test.model.transport.ProjectDTO; import java.util.List; /** * Created by Lucjan.Kornacki on 2018-06-13. */ public interface GitRepoController { /** * List of user projects * * @param user name of user * @param actual flag of actuality of the project * @param sort direction of sorting * @return list of projects */ List<ProjectDTO> getGitProjectsByUser(String user, Boolean actual, String sort); }
PHP
UTF-8
2,077
2.59375
3
[]
no_license
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Upload extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { require_once APPPATH."libraries/bs-form/bs_config.php"; if(!is_login()){ header('Location:index'); exit(); } if(isset($_POST['task'])){ $task = filter_input(INPUT_POST,'task'); switch($task): case "upload_image": if(isset($_FILES['image']) && is_uploaded_file($_FILES['image']['tmp_name'])){ $file = $_FILES['image']; $fileInfo = pathinfo($file['name']); $fileName = $fileInfo['basename']; $output = array(); $uploaddir = IMAGEPATH; $uploadfile = $uploaddir .$fileName; $i = 1; while(file_exists($uploadfile)){ $fileName = $fileInfo['filename']."-".$i.".".$fileInfo['extension']; $uploadfile = $uploaddir .$fileName; $i++; } if($file['type'] != "image/jpeg" && $file['type'] != "image/png"){ $output['status'] = "error"; $output['message'] = "File type is not allowed"; }elseif($file['size']/(1024*1024) > IMAGEMAXSIZE){ $output['status'] = "error"; $output['message'] = "File size exceed the limit"; }elseif (move_uploaded_file($file['tmp_name'], $uploadfile)) { $output['status'] = "done"; $output['message'] = "Image added Successfully"; $output['file'] = $fileName; } else { $output['status'] = "error"; $output['message'] = "Unable to upload the file"; } echo json_encode($output); } break; endswitch; } } }
JavaScript
UTF-8
654
3.609375
4
[]
no_license
/** * Created by Tihomir Dimov on 27.7.2017 г.. */ function addRemoveElements(arr) { let numbers = []; for (let i = 0; i < arr.length; i++) { let input = arr[i].split(' '); let command = input[0]; let argument = input[1]; switch (command) { case ('add'): numbers.push(argument); break; case ('remove'): if (argument > -1 && argument < numbers.length) { numbers.splice(argument, 1); } break; } } for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } }
Java
UTF-8
1,255
3.375
3
[ "MIT" ]
permissive
package Parcial1_problema1; import java.util.Scanner; public class Problema2 { public void parcial() { System.out.println("Problema#2"); double total = 0; //Vector nota = new Vector(); int[] notas = new int[4]; String nom = ""; String apell = ""; double promedio=0; Scanner entrada = new Scanner(System.in); System.out.println("nombre"); nom = entrada.next(); System.out.println("apellido"); apell = entrada.next(); System.out.println("calificacion #1 ->"); notas[0] = entrada.nextInt(); System.out.println("calificacion #2 ->"); notas[1] = entrada.nextInt(); System.out.println("calificacion #3 ->"); notas[2] = entrada.nextInt(); System.out.println("calificacion #4 ->"); notas[3] = entrada.nextInt(); double temp = (notas[0] + notas[1] + notas[2] + notas[3]); promedio = temp/4; System.out.println("Su nombre es: -> " + nom+ " " + apell +", su promedio es de: "+ promedio); if (promedio >= 71) { System.out.println("Aprobo"); } else if (promedio <= 70) { System.out.println("No Aprobo"); } }}
Java
UTF-8
413
2.3125
2
[]
no_license
package com.example.robinsuri.addapp.util; import java.util.ArrayList; import java.util.List; /** * Created by robinsuri on 10/27/14. */ public interface IClock { public long currentTimeInMillis(); public void addListener(Listener listener); public void removeListener(Listener listener); public void runEverySecond(); public interface Listener { public void onTick(); } }
C#
UTF-8
1,348
2.65625
3
[]
no_license
/* FINAL GAME PROJECT * * File: HelpScreen.cs * Full Name: Hy Minh Tran * Student #: 7910276 * Date created: 11/30/2018 * Finished: 9:00 AM December 10, 2018. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace HMFinal { public class HelpScene : GameScene { private SpriteBatch spriteBatch; private Texture2D backgroundHelp; private Texture2D content; public HelpScene(Game game): base(game) { Game1 g = (Game1)game; this.spriteBatch = g.spriteBatch; backgroundHelp = g.Content.Load<Texture2D>("Images\\ShareBackGround"); content = g.Content.Load<Texture2D>("Images\\Help"); } public override void Update(GameTime gameTime) { base.Update(gameTime); } public override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.Draw(backgroundHelp, new Rectangle(0, 0, 1200, 1000), Color.White); spriteBatch.Draw(content, new Rectangle(200, 100, 800, 600), Color.White); spriteBatch.End(); base.Draw(gameTime); } } }
Java
UTF-8
1,310
3.53125
4
[]
no_license
package leetcode.BFS; import java.util.*; public class PostOfficeI { public int shortestDistance(int[][] grid) { if (grid.length == 0 || grid[0].length == 0) return 0; int[] rowCount = new int[grid.length]; int[] colCount = new int[grid[0].length]; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) { rowCount[i]++; colCount[j]++; } } } int[] rowDistance = new int[grid.length]; int[] colDistance = new int[grid[0].length]; getDistances(rowCount, grid.length, rowDistance); getDistances(colCount, grid[0].length, colDistance); int ans = Integer.MAX_VALUE; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 0) { int temp = rowDistance[i] + colDistance[j]; ans = Math.min(ans, temp); } } } return ans; } private void getDistances(int[] ary, int size, int[] ans) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += ary[j] * (Math.abs(j - i)); } } } public static void main(String[] args) { PostOfficeI po = new PostOfficeI(); //[[0,1,0,0],[1,0,1,1],[0,1,0,0]] int[][] input = { {0, 1, 0, 0}, {1, 0, 1, 1}, {0, 1, 0, 0} }; po.shortestDistance(input); } }
Markdown
UTF-8
2,456
2.609375
3
[]
no_license
### Hi there, I'm Chuck 👋 ___ ![Chuck's GitHub stats](https://github-readme-stats.vercel.app/api?username=chuckkainrath&count_private=true&show_icons=true&theme=merko) [![Top Langs](https://github-readme-stats.vercel.app/api/top-langs/?username=chuckkainrath&theme=merko&layout=compact)](https://github.com/anuraghazra/github-readme-stats) ___ ### About Me - My name is Chuck Kainrath - I'm located in Mundelein, Illinois (Greater Chicagoland Area) - Completed App Academy's Full Stack program on 05/28/2021 ### Programming Languages and Tools I've used ![Javascript](https://img.shields.io/badge/JavaScript-F7DF1E?style=for-the-badge&logo=javascript&logoColor=black) ![Python](https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white) ![Node.JS](https://img.shields.io/badge/Node.js-43853D?style=for-the-badge&logo=node.js&logoColor=white) ![React](https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB) ![Redux](https://img.shields.io/badge/Redux-593D88?style=for-the-badge&logo=redux&logoColor=white) ![Flask](https://img.shields.io/badge/Flask-000000?style=for-the-badge&logo=flask&logoColor=white) ![Express.JS](https://img.shields.io/badge/Express.js-404D59?style=for-the-badge) ![PostgreSQL](https://img.shields.io/badge/PostgreSQL-316192?style=for-the-badge&logo=postgresql&logoColor=white) ![HTML](https://img.shields.io/badge/HTML-239120?style=for-the-badge&logo=html5&logoColor=white) ![CSS](https://img.shields.io/badge/CSS-239120?&style=for-the-badge&logo=css3&logoColor=white) ### Contact Email: chuckkainrath@gmail.com [![Portfolio](https://img.shields.io/badge/-Portfolio-blue?style=for-the-badge)](https://chuckkainrath.github.io/) [![LinkedIn](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/chuck-kainrath-42820b20b/) [![AngelList](https://img.shields.io/badge/AngelList-000000?style=for-the-badge&logo=angellist&logoColor=darkgray)](https://angel.co/u/chuck-kainrath) <!-- **chuckkainrath/chuckkainrath** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile. Here are some ideas to get you started: - 🔭 I’m currently working on ... - 🌱 I’m currently learning ... - 👯 I’m looking to collaborate on ... - 🤔 I’m looking for help with ... - 💬 Ask me about ... - 📫 How to reach me: ... - 😄 Pronouns: ... - ⚡ Fun fact: ... -->
C#
UTF-8
6,834
2.734375
3
[ "Apache-2.0" ]
permissive
#if WINDOWS_PHONE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #else using NUnit.Framework; #endif namespace SerializationTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using DataObjects; using TextSerializationTests; using XLabs.Serialization; [TestFixture()] public abstract class CanSerializerTests { protected abstract ISerializer Serializer { get; } [Test()] public void CanSerializePrimitiveAsString() { var p = Primitives.Create(10); Assert.IsTrue(this.Serializer.CanSerializeString<Primitives>(p)); } [Test()] public void CanSerializeTuple() { Tuple<int, string> tuple; for (var n = 0; n < 10; n++) { tuple = new Tuple<int, string>(n, n.ToString()); var str = tuple.ToString(); Debug.WriteLine(str); Assert.IsTrue(this.Serializer.CanSerializeString<Tuple<int, string>>(tuple)); } } [Test()] public void CanSerializePrimitiveAsBytes() { var p = Primitives.Create(10); Assert.IsTrue(this.Serializer.CanSerializeBytes<Primitives>(p)); } [Test()] public void CanSerializePrimitiveAsStream() { var p = Primitives.Create(10); Assert.IsTrue(this.Serializer.CanSerializeStream<Primitives>(p)); } [Test()] public void CanSerializePrimitiveListString() { var list = new PrimitiveList(); for (var n = 0; n < 10; n++) { list.List.Add(Primitives.Create(n)); } Assert.IsTrue(this.Serializer.CanSerializeString<PrimitiveList>(list)); } [Test()] public void CanSerializePrimitiveListBytes() { var list = new PrimitiveList(); for (var n = 0; n < 10; n++) { list.List.Add(Primitives.Create(n)); } Assert.IsTrue(this.Serializer.CanSerializeBytes<PrimitiveList>(list)); } [Test()] public void CanSerializePrimitiveListStream() { var list = new PrimitiveList(); for (var n = 0; n < 10; n++) { list.List.Add(Primitives.Create(n)); } Assert.IsTrue(this.Serializer.CanSerializeStream<PrimitiveList>(list)); } [Test()] public void CanSerializeDateTimeAsString() { var p = DateTime.Now; Assert.IsTrue(this.Serializer.CanSerializeString<DateTime>(p)); } [Test()] public void CanSerializeDateTimeAsByte() { var p = DateTime.Now; Assert.IsTrue(this.Serializer.CanSerializeBytes<DateTime>(p)); } [Test()] public void CanSerializeDateTimeAsStream() { var p = DateTime.Now; Assert.IsTrue(this.Serializer.CanSerializeStream<DateTime>(p)); } [Test()] public void CanSerializeDateTimeOffsetAsString() { var p = new DateTimeOffset(DateTime.Now); Assert.IsTrue(this.Serializer.CanSerializeString<DateTimeOffset>(p)); } [Test()] public void CanSerializeDateTimeOffsetAsByte() { var p = new DateTimeOffset(DateTime.Now); Assert.IsTrue(this.Serializer.CanSerializeBytes<DateTimeOffset>(p)); } [Test()] public void CanSerializeDateTimeOffsetAsStream() { var p = new DateTimeOffset(DateTime.Now); Assert.IsTrue(this.Serializer.CanSerializeStream<DateTimeOffset>(p)); } [Test()] public void CanSerializeDates() { var p = DateTimeDto.Create(101); Assert.IsTrue(this.Serializer.CanSerializeString<DateTimeDto>(p)); } [Test()] public void CanSerializeSimple() { var person = new Person() { Id = 0, FirstName = "First", LastName = "Last" }; Assert.IsTrue(this.Serializer.CanSerializeString<Person>(person)); } [Test()] public void CanSerializeInterface() { var cat = new Cat() { Name = "Just some cat" }; Assert.IsTrue(this.Serializer.CanSerializeString<IAnimal>(cat)); } [Test()] public void CanSerializeAbstractClass() { var dog = new Dog() { Name = "GSP" }; Assert.IsTrue(this.Serializer.CanSerializeString<Animal>(dog)); } [Test()] public void CanSerializeListWithInterfaces() { var animals = new List<IAnimal> { new Cat() { Name = "Just some cat" }, new Dog() { Name = "GSP" } }; Assert.IsTrue(this.Serializer.CanSerializeEnumerable(animals)); } [Test] public void CanSerializeReadOnlyCollection() { var list = new ReadOnlyList<int> { Collection = new ReadOnlyCollection<int>(new[] {0, 1, 2}) }; Assert.IsTrue(this.Serializer.CanSerializeString(list)); } [DataContract] public class PrimitiveList : IEquatable<PrimitiveList> { public PrimitiveList() { this.List = new List<Primitives>(); } [DataMember(Order=1)] public List<Primitives> List { get; set; } #region IEquatable implementation public override bool Equals(object obj) { var list = obj as PrimitiveList; return (list != null && this.Equals(list)); } public bool Equals(PrimitiveList other) { return this.List.SequenceEqual(other.List); } public override int GetHashCode() { return this.List.GetHashCode(); } #endregion } } }
C#
UTF-8
1,432
2.703125
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoneRotation { private Transform boneTransform; private float rotationAngleMax; private float rotationAngleStep; private Vector3 rotationAxis; private float currentAngle = 0; private float defaultAngle; public BoneRotation( Transform boneTransform, float rotationAngleMax, float rotationAngleStep, float defaultAngle, Vector3 rotationAxis) { this.boneTransform = boneTransform; this.rotationAngleMax = rotationAngleMax; this.rotationAngleStep = rotationAngleStep; this.defaultAngle = defaultAngle; this.rotationAxis = rotationAxis; } public void SetDefault() { this.Rotate(this.defaultAngle); } public void Animate() { this.currentAngle = this.currentAngle + this.rotationAngleStep; this.Rotate(this.rotationAngleStep); if (this.rotationAngleMax <= this.currentAngle || this.currentAngle <= -this.rotationAngleMax) { this.rotationAngleStep = -this.rotationAngleStep; } } private void Rotate(float angleToAdd) { Quaternion _q = this.boneTransform.localRotation; Quaternion q = Quaternion.AngleAxis(angleToAdd, this.rotationAxis); this.boneTransform.localRotation = _q * q; } }
C++
UTF-8
2,184
2.671875
3
[]
no_license
#include <stdio.h> #include <thread> #include <atomic> #include "CoreArbiter/CoreArbiterClient.h" #include "CoreArbiter/Logger.h" #include "PerfUtils/Cycles.h" #include "PerfUtils/TimeTrace.h" #include "PerfUtils/Util.h" using PerfUtils::TimeTrace; using CoreArbiter::CoreArbiterClient; using namespace CoreArbiter; #define NUM_TRIALS 1000 /** * This thread will get unblocked when a core is allocated, and will block * itself again when the number of cores is decreased. */ void coreExec(CoreArbiterClient* client) { for (int i = 0; i < NUM_TRIALS; i++) { TimeTrace::record("Core thread about to block"); client->blockUntilCoreAvailable(); TimeTrace::record("Core thread returned from block"); while (!client->mustReleaseCore()); TimeTrace::record("Core informed that it should block"); } } void coreRequest(CoreArbiterClient* client) { std::vector<uint32_t> oneCoreRequest = {1,0,0,0,0,0,0,0}; client->setRequestedCores(oneCoreRequest); client->blockUntilCoreAvailable(); std::vector<uint32_t> twoCoresRequest = {2,0,0,0,0,0,0,0}; for (int i = 0; i < NUM_TRIALS; i++) { // When the number of blocked threads becomes nonzero, we request a core. while (client->getNumBlockedThreads() == 0); TimeTrace::record("Detected thread block"); client->setRequestedCores(twoCoresRequest); TimeTrace::record("Requested a core"); // When the number of blocked threads becomes zero, we release a core. while (client->getNumBlockedThreads() == 1); TimeTrace::record("Detected thread wakeup"); client->setRequestedCores(oneCoreRequest); TimeTrace::record("Released a core"); } } int main(){ Logger::setLogLevel(ERROR); CoreArbiterClient* client = CoreArbiterClient::getInstance("/tmp/CoreArbiter/testsocket"); std::thread requestThread(coreRequest, std::ref(client)); while (client->getNumOwnedCores() == 0); std::thread coreThread(coreExec, std::ref(client)); coreThread.join(); requestThread.join(); TimeTrace::setOutputFileName("CoreRequest_Noncontended.log"); TimeTrace::print(); }
C#
UTF-8
425
2.828125
3
[]
no_license
namespace Estates.Data.Offers { using Interfaces; public class SaleOffer : Offer, ISaleOffer { private static readonly OfferType OfferType = OfferType.Sale; public SaleOffer() : base(OfferType) { } public decimal Price { get; set; } public override string ToString() { return base.ToString() + $", Price = {this.Price}"; } } }
TypeScript
UTF-8
1,081
2.96875
3
[]
no_license
import * as pathToRegexp from "path-to-regexp"; interface ICache{ [pattern:string]:pathToRegexp.PathFunction } interface IpatternCache{ [pattern:string]:ICache } const patternCache:IpatternCache = {}; const cacheLimit = 10000; let cacheCount = 0; const compileGenerator = (pattern:string) => { const cacheKey = pattern; const cache = patternCache[cacheKey] || (patternCache[cacheKey] = {}); if (cache[pattern]) { return cache[pattern]} const compiledGenerator = pathToRegexp.compile(pattern); if (cacheCount < cacheLimit) { cache[pattern] = compiledGenerator; cacheCount++; } return compiledGenerator; }; /** * Public API for generating a URL pathname from a pattern and parameters. */ const generatePath = (pattern = "/", params: { [paramName: string]: string | number | boolean } = {}):string => { if (pattern === "/") { return pattern; } const generator = compileGenerator(pattern); return generator(params, { pretty: true } as pathToRegexp.PathFunctionOptions); // return generator(params); }; export default generatePath;
Java
UTF-8
2,389
2.421875
2
[]
no_license
// Copyright 2012 Google Inc. All Rights Reserved. package com.google.android.sdk; import com.android.tradefed.config.Option; import com.android.tradefed.log.LogUtil.CLog; import com.android.tradefed.result.ITestInvocationListener; import com.android.tradefed.util.ArrayUtil; import com.android.tradefed.util.FileUtil; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; /** * A result reporter that appends {@link SdkDlTest} metrics results to a csv file. */ public class SdkDlCsvMetricsReporter implements ITestInvocationListener { @Option(name = "csv-file", description = "filesystem path to csv file to write results to", mandatory = true) private File mCsvFile = null; // static lock object for file access private static Object mLock = new Object(); /** * Writes a row to csv file, */ @Override public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) { SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm:ss"); String timestamp = formatter.format(new Date()); String result = runMetrics.get(SdkDlTest.SUCCESS); String time = runMetrics.get(SdkDlTest.TIME); String rate = runMetrics.get(SdkDlTest.KB_PER_SEC); String entry = ArrayUtil.join(",", timestamp, result, time, rate); CLog.i("Updating file %s", mCsvFile.getAbsolutePath()); synchronized (mLock) { try { writeHeaderIfNecessary(mCsvFile); appendToFile(entry + "\n", mCsvFile); } catch (IOException e) { CLog.e("Failed to write to %s", mCsvFile); CLog.e(e); } } } private void writeHeaderIfNecessary(File csvFile) throws IOException { if (!csvFile.exists()) { csvFile.createNewFile(); FileUtil.writeToFile("End time,success,download time, KB/s\n", csvFile); } } private void appendToFile(String inputString, File destFile) throws IOException { Writer writer = new BufferedWriter(new FileWriter(destFile, true)); try { writer.write(inputString); } finally { writer.close(); } } }
Java
UTF-8
750
2.34375
2
[ "MIT" ]
permissive
package com.mp.piggymetrics.statistics.domain.timeseries; import org.jnosql.artemis.Column; import org.jnosql.artemis.Entity; import java.util.Date; @Entity public class DataPointId { @Column private String account; @Column private Date date; public DataPointId() { } public DataPointId(String account, Date date) { this.account = account; this.date = date; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "DataPointId{" + "account='" + account + '\'' + ", date=" + date + '}'; } }
Java
UTF-8
2,206
1.976563
2
[]
no_license
package com.makenv.controller; import com.makenv.condition.StationDetailCondition; import com.makenv.config.SpeciesConfig; import com.makenv.domain.City; import com.makenv.service.RankService; import com.makenv.service.StationDetailService; import com.makenv.service.StationService; import com.makenv.service.impl.StationDetailServiceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpRequest; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.http.HttpServletRequest; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by wgy on 2016/8/6. */ @RestController @RequestMapping("makenv") public class TestController extends BaseController { private final static Logger logger = LoggerFactory.getLogger(TestController.class); @Autowired private StationService stationService; @Autowired private StationDetailService stationDetailService; @Autowired private SpeciesConfig speciesConfig; @Autowired private RankService rankService; /* @Resource private RedisTemplate RedisTemplate;*/ @RequestMapping("/test") @ResponseBody public Map test(HttpServletRequest request){ ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); String beanDefinitionName[] =applicationContext.getBeanDefinitionNames(); Object obj = applicationContext.getBean("stationDetailServiceImpl"); System.out.println(obj); return new HashMap(); } @RequestMapping("/testCache") public List test(City city){ LocalDateTime startTime = LocalDateTime.of(2016,8,1,0,0); LocalDateTime endTime = startTime.plus(1, ChronoUnit.MONTHS); rankService.getRankResultDataByArea(new StationDetailCondition(), startTime, endTime); return null; } }
Python
UTF-8
517
2.796875
3
[]
no_license
# -*- coding: utf-8 -*- """ @author by mkzhou @time 2020/6/7 16:21 """ from multiprocessing import Pool import os import random import time def worker(msg): t_start = time.time() print('{}开始执行,进程号{}'.format(msg, os.getpid())) time.sleep(random.random()*2) t_stop = time.time() print('{}执行完毕,耗时{:.2f}'.format(msg, (t_stop-t_start))) po = Pool(3) for i in range(0,10): po.apply_async(worker, (i,)) print('----start----') po.close() po.join() print('----end----')
Java
UTF-8
400
1.960938
2
[ "MIT" ]
permissive
package com.dcpuz.spring.servera.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * web controller * </p> * * @author dengc * @since 2020/6/11 */ @RestController public class WebController { @RequestMapping("/hello") public String hello(){ return "hello servera!"; } }
Java
UTF-8
885
2
2
[]
no_license
package ru.babobka.node.dummybenchmark; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import ru.babobka.nodetester.benchmark.NodeBenchmark; import ru.babobka.nodetester.benchmark.NodeBenchmarkCLI; import java.util.Collections; import java.util.List; public class DummyNodeBenchmarkAp extends NodeBenchmarkCLI { @Override protected List<Option> createBenchmarkOptions() { return Collections.emptyList(); } @Override protected void benchmarkRun(CommandLine cmd) { new NodeBenchmark(getAppName(), getTests(cmd)) .run(getSlaves(cmd), getServiceThreads(cmd), new DummyNodeBenchmarkPerformer()); } @Override public String getAppName() { return "dummy-node-benchmark"; } public static void main(String[] args) { new DummyNodeBenchmarkAp().onStart(args); } }
C++
UTF-8
211
2.5625
3
[]
no_license
#include <cmp/TextureCmp.hpp> #include <ostream> std::ostream & operator<<(std::ostream &os, const TextureCmp & cmp) { cmp.print(os, TextureCmp::getName()) << "\n\tITexture: " << cmp.texture; return os; }
Java
UTF-8
1,405
2.5
2
[]
no_license
package scheduler.ycp.edu.shared; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.shared.GWT; @SuppressWarnings("serial") public class Schedule extends Publisher implements Serializable{ public enum Events{ ADD_REQUIRED, REMOVE_REQUIRED, ADD_OPTIONAL, REMOVE_OPTIONAL, } private List<String> requiredList; private List<String> optionalList; GenerateInit generate = new GenerateInit(); public Schedule(){ this.requiredList = new ArrayList<String>(); this.optionalList = new ArrayList<String>(); } public void addRequired(String course){ if(!requiredList.contains(course)){ requiredList.add(course); notifySubscribers(Events.ADD_REQUIRED, course); } } public void addOptional(String course){ if(!optionalList.contains(course)){ optionalList.add(course); notifySubscribers(Events.ADD_OPTIONAL, course); } } public void removeRequired(String course){ if(requiredList.contains(course)){ requiredList.remove(course); notifySubscribers(Events.REMOVE_REQUIRED, course); } } public void removeOptional(String course){ if(optionalList.contains(course)){ optionalList.remove(course); notifySubscribers(Events.REMOVE_OPTIONAL, course); } } public List<String> getRequiredList(){ return requiredList; } public List<String> getOptionalList(){ return optionalList; } }
C#
UTF-8
1,343
2.890625
3
[]
no_license
using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; namespace FileServer { public class FileController : ApiController { private string _dataFolder = @"D:\Users\Jeroen\TA-Advanced\Data"; [Route("files/{fileName}", Name="FileRoute")] public HttpResponseMessage Get(string fileName) { var path = Path.Combine(_dataFolder, fileName); if (!File.Exists(path)) return new HttpResponseMessage(HttpStatusCode.NotFound); var result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; } [Route("list")] public MyFileInfo[] Get() { return new DirectoryInfo(_dataFolder).GetFiles().Select(x => new MyFileInfo{fileName = x.Name, size = x.Length, url = Url.Link("FileRoute", new{fileName=x.Name})}).ToArray(); } } public class MyFileInfo { public string fileName { get; set; } public long size { get; set; } public string url { get; set; } } }
C#
UTF-8
3,839
4.125
4
[ "MIT" ]
permissive
using System; /* Problem 13. Solve tasks Write a program that can solve these tasks: Reverses the digits of a number Calculates the average of a sequence of integers Solves a linear equation a * x + b = 0 Create appropriate methods. Provide a simple text-based menu for the user to choose which task to solve. Validate the input data: The decimal number should be non-negative The sequence should not be empty a should not be equal to 0 */ class SolveТasks { static void Main() { do { Console.WriteLine("*-----------------------------------------------------*"); Console.WriteLine("1.Reverses the digits of a number."); Console.WriteLine("2.Calculates the average of a sequence of integers."); Console.WriteLine("3.Solves a linear equation a * x + b = 0"); Console.WriteLine("4.Exit"); Console.Write("Enter your choice: "); int choice = int.Parse(Console.ReadLine()); switch (choice) { case 1: Console.Write("Enter number to reverse: "); int number = int.Parse(Console.ReadLine()); if (number >= 0) { Console.WriteLine("Reverse number is: {0}", ReverseNumber(number)); } else { Console.WriteLine("You enter a wrong number!"); } break; case 2: Console.Write("How many number you want? - "); int n = int.Parse(Console.ReadLine()); if (n != 0) { int[] numbers = new int[n]; for (int i = 0; i < n; i++) { numbers[i] = int.Parse(Console.ReadLine()); } Average(numbers); } else { Console.WriteLine("You should have 1 number less!"); } break; case 3: Console.Write("Enter a: "); int a = int.Parse(Console.ReadLine()); if (a != 0) { Console.Write("Enter b: "); int b = int.Parse(Console.ReadLine()); SolvesLinearEquation(a, b); } else { Console.WriteLine("a should be a!=0 !"); } break; case 4: return; default: Console.WriteLine("Wrong choice"); break; } } while (true); } static string ReverseNumber(int number) { int temp = 0; string reverseNumber = ""; while (number != 0) { temp = number % 10; reverseNumber += temp.ToString(); number /= 10; } return reverseNumber; } static void Average(int[] numbers) { double average = 0; Console.Write("Average sum of: "); for (int i = 0; i < numbers.Length; i++) { average += numbers[i]; Console.Write(" {0} ", numbers[i]); } average = average / numbers.Length; Console.Write("is: {0:0.00}", average); Console.WriteLine(); } static void SolvesLinearEquation(int a, int b) { double x; x = -(b / (double)a); Console.WriteLine("x = {0}", x); } }
Ruby
UTF-8
1,339
2.59375
3
[]
no_license
module ApisHelper # This method is for encoding the JWT before sending it out def encodeJWT(creator, exp=48.hours.from_now) # add the expire to the payload, as an integer payload = { creators_id: creator.id } payload[:exp] = exp.to_i # Encode the payload whit the application secret, and a more advanced hash method (creates header with JWT gem) JWT.encode( payload, Rails.application.secrets.secret_key_base, "HS512") end # When we get a call we have to decode it - Returns the payload if good otherwise false def decodeJWT(token) # puts token payload = JWT.decode(token, Rails.application.secrets.secret_key_base, "HS512") # puts payload if payload[0]['exp'] >= Time.now.to_i payload else puts 'time expired on login' false end # catch the error if token is wrong rescue => error puts error nil end def create_error_types {developerMessage: :'Need to include type_ids as array to your event object.EX: event:{event_ids:[1,2]}', userMessage: :'You need to add what type of saving it is'} end def create_error_message {developerMessage: :'', userMessage: :'Error when saving.'} end def get_error_message {developerMessage: :"Could not find resource: #{params[:id]}", userMessage: :"Could not find any #{params[:id]}"} end end
Markdown
UTF-8
3,040
2.765625
3
[]
no_license
# Business Continuity and Disaster Recovery ## Design Considerations - Consider Recovery Point Objective (RPO) and Recovery Time Objective(RTO) requirements, as those will dictate if App Gateway needs to be deployed in: - Single or Multi Region - Active-Active or Active-Standby Configuration - Do we need a single point of entry or multiple entry points based on from where the requests are coming? This will facilitate decision for Traffic Manager or Front Door - Is cost a concern? - Is latency or an extra hop a concern? - Any third-party solution used to direct traffic to App Gateway? - Backup of App Gateway configuration – Only ARM Template? Where is it stored and how it’ll be utilized – Manually or through automation e.g., ADO pipelines? ### Multi-Tenanted: - If your application needs to be redundant across regions, deploy the solution in more than one region and use Traffic Manager or Azure Front Door to balance load between these deployments. - If uses of your application span geographies, consider deploying to single regions in each applicable geography and use Traffic Manager or Azure Front Door to provide geography-based routing. This will provide enhanced performance and increased redundancy. - If you need to recover from a disaster, consider if redeploying the application from a CI/CD process would be adequate. Also consider that a web app is a component in a larger solution, and you will need to consider the DR processes for the other components in the solution. ### App Service Environment: - Guidance on architecting an ASE-based solution for [high availability within a region](https://docs.microsoft.com/en-us/azure/architecture/reference-architectures/enterprise-integration/ase-high-availability-deployment). - Guidance on [geographic redundancy](https://docs.microsoft.com/en-us/azure/app-service/environment/app-service-app-service-environment-geo-distributed-scale). ## Design Recommendations ### Multi-Tenanted: - Deploy your App Service solution to at least 2 regions, and possibly to multiple geographies, if required. - Utilize Azure Front Door to provide load balancing and WAF capabilities between the different deployments. - Modify your CI/CD processes so that changes to the solution are deployed to each target region. - Ensure that your CI/CD processes are setup to re-deploy the solution in case a disaster impacts one or more of the deployments. ### App Service Environment: - Deploy one instance of the ASE in 2 separate Availability Zones in the same region, or in 2 different regions if cross-regional HA is required. - Where your ASE instances are deployed across Availability Zones in the same region, use Azure Application Gateway to provide load balancing and WAF capabilities between the instances. - Where cross-regional HA is required, utilize Azure Front Door to provide load balancing and WAF capabilities between the different instances. - Modify your CI/CD processes so that changes to the solution are deployed to each target ASE instance.
Java
UTF-8
1,032
2.78125
3
[]
no_license
package DataModel; /** * * @author Fresh */ public class ProductReport { private String tagID, tagName, status, identifyingAntenna; public ProductReport(String tagID,String tagName,String status,String identifyingAntenna){ this.tagID = tagID; this.tagName = tagName; this.status = status; this.identifyingAntenna = identifyingAntenna; } public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTagID() { return tagID; } public void setTagID(String tagID) { this.tagID = tagID; } public String getIdentifyingAntenna() { return identifyingAntenna; } public void setIdentifyingAntenna(String identifyingAntenna) { this.identifyingAntenna = identifyingAntenna; } }
C#
UTF-8
2,520
2.546875
3
[ "MIT" ]
permissive
using Core.Models; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BNetLib.Ribbit.Models; namespace Core.Services { public interface ICDNs { Task<Manifest<CDN[]>> Latest(string code); Task<Manifest<CDN[]>> Previous(string code); Task<List<Manifest<CDN[]>>> Take(string code, int amount); Task<Manifest<CDN[]>> Single(string code, int? seqn); Task<List<SeqnType>> Seqn(string code); Task<List<Manifest<CDN[]>>> MultiBySeqn(List<int> toList); } public class CDNs : ICDNs { private readonly DBContext _dbContext; public CDNs(DBContext dbContext) { _dbContext = dbContext; } public async Task<Manifest<CDN[]>> Latest(string code) { return await _dbContext.CDN.AsNoTracking().Include(x => x.Config).OrderByDescending(x => x.Seqn).Where(x => x.Code.ToLower() == code.ToLower()).FirstOrDefaultAsync(); } public async Task<Manifest<CDN[]>> Previous(string code) { return await _dbContext.CDN.AsNoTracking().Include(x => x.Config).OrderByDescending(x => x.Seqn).Where(x => x.Code.ToLower() == code.ToLower()).Skip(1).Take(1).FirstOrDefaultAsync(); } public async Task<List<SeqnType>> Seqn(string code) { var data = await _dbContext.CDN.AsNoTracking().Select(x => new { x.Seqn, x.Code, x.Indexed }).OrderByDescending(x => x.Seqn).Where(x => x.Code.ToLower() == code.ToLower()).ToListAsync(); return data.Select(x => new SeqnType(x.Code, x.Seqn, x.Indexed)).ToList(); } public async Task<List<Manifest<CDN[]>>> MultiBySeqn(List<int> seqns) { return await _dbContext.CDN.AsNoTracking().Include(x => x.Config).Where(x => seqns.Contains(x.Seqn)).ToListAsync(); } public async Task<Manifest<CDN[]>> Single(string code, int? seqn) { return await _dbContext.CDN.AsNoTracking().Include(x => x.Config).OrderByDescending(x => x.Seqn).Where(x => (seqn == null || x.Seqn == seqn) && x.Code.ToLower() == code.ToLower()).FirstOrDefaultAsync(); } public async Task<List<Manifest<CDN[]>>> Take(string code, int amount) { return await _dbContext.CDN.AsNoTracking().Include(x => x.Config).OrderByDescending(x => x.Seqn).Where(x => x.Code.ToLower() == code.ToLower()).Take(amount).ToListAsync(); } } }