text
stringlengths
1
1.05M
# Want to train with wordnet hierarchy? Just set `--hierarchy=wordnet` below. # This script is for networks that DO come with a pretrained checkpoint provided either by a model zoo or by the NBDT utility itself. model=wrn28_10_cifar10 dataset=CIFAR10 weight=1 # 1. generate hieararchy nbdt-hierarchy --dataset=${dataset} --arch=${model} # 2. train with soft tree supervision loss python main.py --lr=0.01 --dataset=${dataset} --model=${model} --hierarchy=induced-${model} --pretrained --loss=SoftTreeSupLoss --tree-supervision-weight=${weight} # 3. evaluate with soft then hard inference for analysis in SoftEmbeddedDecisionRules HardEmbeddedDecisionRules; do python main.py --dataset=${dataset} --model=${model} --hierarchy=induced-${model} --loss=SoftTreeSupLoss --eval --resume --analysis=${analysis} --tree-supervision-weight=${weight} done
<filename>router/todoRouter.go package router import ( "github.com/gin-gonic/gin" ) func InitToDoRouter(Router *gin.RouterGroup) { ToDoRouter := Router.Group("todo") { // 添加代办 ToDoRouter.POST("/todo", func(c *gin.Context) { }) // 查看所有代办 ToDoRouter.GET("todo", func(c *gin.Context) { }) // 查看某一个代办事项 ToDoRouter.GET("todo/:id", func(c *gin.Context) { }) ToDoRouter.GET("todo", func(c *gin.Context) { }) ToDoRouter.GET("todo", func(c *gin.Context) { }) } }
#!/bin/bash set -e environmentName="prod" apiPort=8080 filename="${environmentName}-data-service.properties" function getProperty() { property=$1 cat ${propertiesFile} | grep ${property} | awk '{print $2}' } while getopts ":dp:" opt do case $opt in d) debugMode=true echo "Option set to start API in debug mode." debugFlags="-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001 -Djava.compiler=NONE" ;; p) apiPort=$OPTARG echo "Option set run API on port ${apiPort}" ;; help|\?) echo -e "Usage: [-d] [-p <port>]" echo -e "\t d - debug. Starts the API in debug mode, which an IDE can attach to on port 8001" echo -e "\t p <port> - Starts the API on a specific port (default 8080)" exit 0 ;; esac done echo "Please enter a username under which to set up the id-gen tunnel: " read tunnelUserName propertiesFile="`pwd`/../data-service/target/classes/${filename}" if [ -f "$propertiesFile" ]; then # Check if tunnel is already established before running echo "Checking for existing tunnel and killing if found" ps -ef | grep ssh | grep $(getProperty target_hostname) | awk '{print $2}' | xargs kill command="ssh -L $(getProperty local_port):$(getProperty target_hostname):$(getProperty target_port) $(getProperty tunnel_proxy) -l ${tunnelUserName}" echo "Running tunnelling command: ${command}" ${command} & # Give the user time to enter their password for this connection sleep 20 echo 'Building API webapp (skipping tests)..' sleep 1 mvn -f ../pom.xml clean install -Dapple.awt.UIElement='true' -DskipTests=true echo echo "Starting API webapp using $environmentName environment on port ${apiPort}." echo sleep 1 java ${debugFlags} -Xmx4g -DENV_NAME=$(whoami) -jar target/exec-api.jar -DdataServicePropertiesPath="file://${propertiesFile}" -httpPort=${apiPort} else echo "You don't have access to the $environmentName environment." echo exit 1 fi
declare type int = number; declare var zone: any; declare var Zone: any; declare module "angular2/change_detection" { class ChangeDetectorRef {} class Pipe { supports(obj: any): boolean; onDestroy(): void; transform(value: any): any; } class PipeFactory { supports(obs: any): boolean; create(cdRef: any): Pipe; } class NullPipeFactory {} class PipeRegistry { constructor(pipes: any); get(type: string, obj: any, cdRef: ChangeDetectorRef): Pipe; } class JitChangeDetection {} class ChangeDetection {} class DynamicChangeDetection {} var defaultPipes: any; } declare module "angular2/pipes" { class PipeFactory { } class Pipe { } class CollectionChangeRecord { currentIndex: int; previousIndex: int; item: any; _nextPrevious: CollectionChangeRecord; _prev: CollectionChangeRecord; _next: CollectionChangeRecord; _prevDup: CollectionChangeRecord; _nextDup: CollectionChangeRecord; _prevRemoved: CollectionChangeRecord; _nextRemoved: CollectionChangeRecord; _nextAdded: CollectionChangeRecord; _nextMoved: CollectionChangeRecord; constructor(item: any); toString(): string; } class KeyValueChangesFactory extends PipeFactory { constructor(); supports(obj: any): boolean; create(cdRef: any): Pipe; } class KeyValueChanges extends Pipe { private _records; private _mapHead; private _previousMapHead; private _changesHead; private _changesTail; private _additionsHead; private _additionsTail; private _removalsHead; private _removalsTail; constructor(); static supportsObj(obj: any): boolean; supports(obj: any): boolean; transform(map: any): any; isDirty: boolean; forEachItem(fn: Function): void; forEachPreviousItem(fn: Function): void; forEachChangedItem(fn: Function): void; forEachAddedItem(fn: Function): void; forEachRemovedItem(fn: Function): void; check(map: any): boolean; _reset(): void; _truncate(lastRecord: KVChangeRecord, record: KVChangeRecord): void; _isInRemovals(record: KVChangeRecord): boolean; _addToRemovals(record: KVChangeRecord): void; _removeFromSeq(prev: KVChangeRecord, record: KVChangeRecord): void; _removeFromRemovals(record: KVChangeRecord): void; _addToAdditions(record: KVChangeRecord): void; _addToChanges(record: KVChangeRecord): void; toString(): string; _forEach(obj: any, fn: Function): void; } class KVChangeRecord { key: any; previousValue: any; currentValue: any; _nextPrevious: KVChangeRecord; _next: KVChangeRecord; _nextAdded: KVChangeRecord; _nextRemoved: KVChangeRecord; _prevRemoved: KVChangeRecord; _nextChanged: KVChangeRecord; constructor(key: any); toString(): string; } class IterableChangesFactory extends PipeFactory { constructor(); supports(obj: any): boolean; create(cdRef: any): Pipe; } class IterableChanges extends Pipe { private _collection; private _length; private _linkedRecords; private _unlinkedRecords; private _previousItHead; private _itHead; private _itTail; private _additionsHead; private _additionsTail; private _movesHead; private _movesTail; private _removalsHead; private _removalsTail; constructor(); static supportsObj(obj: any): boolean; supports(obj: any): boolean; collection: any; length: int; forEachItem(fn: Function): void; forEachPreviousItem(fn: Function): void; forEachAddedItem(fn: Function): void; forEachMovedItem(fn: Function): void; forEachRemovedItem(fn: Function): void; transform(collection: any): any; check(collection: any): boolean; isDirty: boolean; _reset(): void; _mismatch(record: CollectionChangeRecord, item: any, index: int): CollectionChangeRecord; _verifyReinsertion(record: CollectionChangeRecord, item: any, index: int): CollectionChangeRecord; _truncate(record: CollectionChangeRecord): void; _reinsertAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: int): CollectionChangeRecord; _moveAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: int): CollectionChangeRecord; _addAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: int): CollectionChangeRecord; _insertAfter(record: CollectionChangeRecord, prevRecord: CollectionChangeRecord, index: int): CollectionChangeRecord; _remove(record: CollectionChangeRecord): CollectionChangeRecord; _unlink(record: CollectionChangeRecord): CollectionChangeRecord; _addToMoves(record: CollectionChangeRecord, toIndex: int): CollectionChangeRecord; _addToRemovals(record: CollectionChangeRecord): CollectionChangeRecord; toString(): string; } } declare module "angular2/src/core/zone/ng_zone" { class NgZone { runOutsideAngular(func: Function): any; } } declare module 'angular2/src/services/url_resolver' { class UrlResolver {} } declare module "angular2/src/facade/lang" { function isPresent(obj: any): boolean; function isBlank(obj: any): boolean; function isString(obj: any): boolean; function isFunction(obj: any): boolean; function isType(obj: any): boolean; function stringify(token: any): string; class StringWrapper { static fromCharCode(code: int): string; static charCodeAt(s: string, index: int): number; static split(s: string, regExp: any): string[]; static equals(s: string, s2: string): boolean; static replace(s: string, from: string, replace: string): string; static replaceAll(s: string, from: RegExp, replace: string): string; static toUpperCase(s: string): string; static toLowerCase(s: string): string; static startsWith(s: string, start: string): boolean; static substring(s: string, start: int, end?: int): string; static replaceAllMapped(s: string, from: RegExp, cb: Function): string; static contains(s: string, substr: string): boolean; } } declare module "angular2/src/facade/async" { class Observable {} class EventEmitter { next(val:any); return(val:any); throw(val:any); } } declare module "angular2/src/render/dom/shadow_dom/style_url_resolver" { class StyleUrlResolver {} } declare module "angular2/src/core/life_cycle/life_cycle" { class LifeCycle { tick(): any; } } declare module "zone.js" { var zone: any; var Zone: any; } declare module "angular2/directives" { function NgSwitch(): void; function NgSwitchWhen(): void; function NgSwitchDefault(): void; function NgNonBindable(): void; function NgIf(): void; function NgFor(): void; var formDirectives: any; var coreDirectives: any; } declare module "angular2/forms" { var formDirectives: any; class FormBuilder { group(controls: any): any; } class Control { constructor(controls: any); updateValidity(): void; updateValueAndValidity(value: any): void; updateValue(value: any); _valueChanges: any; valueChanges: any; errors: any; pristine: boolean; touched: boolean; valid: boolean; } class ControlArray { removeAt(index: any); push(item: any); } class ControlGroup { constructor(controls: any); updateValidity(): void; updateValueAndValidity(value: any): void; controls: any; valueChanges: any; errors: any; pristine: boolean; touched: boolean; valid: boolean; } class Validators { static required: any; } } declare module "angular2/render" { interface List<T> { } class RenderViewRef {} class RenderElementRef { renderView: RenderViewRef; boundElementIndex: number; } class Renderer { setElementProperty(location: any, propertyName: string, propertyValue: any); setElementAttribute(location: any, attributeName: string, attributeValue: string); setElementClass(location: any, className: string, isAdd: boolean); setElementStyle(location: any, styleName: string, styleValue: string); invokeElementMethod(location: any, methodName: string, args: List<any>); } class EmulatedScopedShadowDomStrategy { constructor(styleInliner: any, styleUrlResolver: any, styleHost: any); } class EmulatedUnscopedShadowDomStrategy { constructor(styleUrlResolver: any, styleHost: any); } class NativeShadowDomStrategy { constructor(styleUrlResolver: any); } class ShadowDomStrategy {} } declare module "angular2/src/facade/browser" { var __esModule: boolean; var win: any; var document: any; var location: any; var gc: () => void; var Event: any; var MouseEvent: any; var KeyboardEvent: any; } declare module "angular2/src/router/browser_location" { class BrowserLocation { path(): string; } } declare module "angular2/src/router/location" { class Location { normalize(url: string): string; path(): string; } } declare module "angular2/src/facade/collection" { interface List<T> { } interface StringMap<K, V> { } function isListLikeIterable(obj: any): boolean; function iterateListLike(obj: any, fn: Function): void; class ListWrapper { static create(): List<any>; static createFixedSize(size: any): List<any>; static get(m: any, k: any): any; static set(m: any, k: any, v: any): void; static clone(array: List<any>): any[]; static map(array: any, fn: any): any; static forEach(array: List<any>, fn: Function): void; static push(array: any, el: any): void; static first(array: any): any; static last(array: any): any; static find(list: List<any>, pred: Function): any; static indexOf(array: List<any>, value: any, startIndex?: number): number; static reduce<T, E>(list: List<T>, fn: (accumValue: E, currentValue: T, currentIndex: number, array: T[]) => E, init: E): E; static filter(array: any, pred: Function): any; static any(list: List<any>, pred: Function): boolean; static contains(list: List<any>, el: any): boolean; static reversed(array: any): any[]; static concat(a: any, b: any): any; static isList(list: any): boolean; static insert(list: any, index: int, value: any): void; static removeAt(list: any, index: int): any; static removeAll(list: any, items: any): void; static removeLast<T>(list: List<T>): T; static remove(list: any, el: any): boolean; static clear(list: any): void; static join(list: any, s: any): any; static isEmpty(list: any): boolean; static fill(list: List<any>, value: any, start?: int, end?: int): void; static equals(a: List<any>, b: List<any>): boolean; static slice<T>(l: List<T>, from?: int, to?: int): List<T>; static splice<T>(l: List<T>, from: int, length: int): List<T>; static sort<T>(l: List<T>, compareFn?: (a: T, b: T) => number): void; } class StringMapWrapper { static create(): StringMap<any, any>; static contains(map: StringMap<string, any>, key: string): boolean; static get<V>(map: StringMap<string, V>, key: string): V; static set<V>(map: StringMap<string, V>, key: string, value: V): void; static keys(map: StringMap<string, any>): List<string>; static isEmpty(map: StringMap<string, any>): boolean; static delete(map: StringMap<string, any>, key: string): void; static forEach<K, V>(map: StringMap<string, V>, callback: Function): void; static merge<V>(m1: StringMap<string, V>, m2: StringMap<string, V>): StringMap<string, V>; static equals<V>(m1: StringMap<string, V>, m2: StringMap<string, V>): boolean; } } declare module "angular2/router" { interface Promise<T> {} class Instruction {} class Router { parent: Router; navigate(url: string): Promise<any>; config(config: any): Promise<any>; deactivate(): Promise<any>; activate(instruction: Instruction): Promise<any>; recognize(url: string): Instruction; recognize(url: string): Instruction; renavigate(): Promise<any>; generate(name:string, params:any): string; subscribe(onNext: Function): void; } class RouterOutlet { constructor(elementRef: any, _loader: any, _parentRouter: any, _injector: any, nameAttr: any); _loader: any; _parentRouter: any; _injector: any; _childRouter: any; _componentRef: any; _elementRef: any; _currentInstruction: any; /** * Given an instruction, update the contents of this viewport. */ activate(instruction: any): any; deactivate(): any; canDeactivate(instruction: any): any; } var RouterLink: any; var RouteParams: any; var routerInjectables: any; var RouteConfigAnnotation: any; var RouteConfig: any; } declare module "angular2/src/dom/browser_adapter" { class BrowserDomAdapter { static makeCurrent(): void; logError(error: any): void; attrToPropMap: any; query(selector: string): any; querySelector(el: any, selector: string): Node; querySelectorAll(el: any, selector: string): any; on(el: any, evt: any, listener: any): void; onAndCancel(el: any, evt: any, listener: any): Function; dispatchEvent(el: any, evt: any): void; createMouseEvent(eventType: string): MouseEvent; createEvent(eventType: any): Event; getInnerHTML(el: any): any; getOuterHTML(el: any): any; nodeName(node: Node): string; nodeValue(node: Node): string; type(node: HTMLInputElement): string; content(node: Node): Node; firstChild(el: any): Node; nextSibling(el: any): Node; parentElement(el: any): any; childNodes(el: any): any; childNodesAsList(el: any): any; clearNodes(el: any): void; appendChild(el: any, node: any): void; removeChild(el: any, node: any): void; replaceChild(el: Node, newChild: any, oldChild: any): void; remove(el: any): any; insertBefore(el: any, node: any): void; insertAllBefore(el: any, nodes: any): void; insertAfter(el: any, node: any): void; setInnerHTML(el: any, value: any): void; getText(el: any): any; setText(el: any, value: string): void; getValue(el: any): any; setValue(el: any, value: string): void; getChecked(el: any): any; setChecked(el: any, value: boolean): void; createTemplate(html: any): HTMLElement; createElement(tagName: any, doc?: Document): HTMLElement; createTextNode(text: string, doc?: Document): Text; createScriptTag(attrName: string, attrValue: string, doc?: Document): HTMLScriptElement; createStyleElement(css: string, doc?: Document): HTMLStyleElement; createShadowRoot(el: HTMLElement): DocumentFragment; getShadowRoot(el: HTMLElement): DocumentFragment; getHost(el: HTMLElement): HTMLElement; clone(node: Node): Node; hasProperty(element: any, name: string): boolean; getElementsByClassName(element: any, name: string): any; getElementsByTagName(element: any, name: string): any; classList(element: any): any; addClass(element: any, classname: string): void; removeClass(element: any, classname: string): void; hasClass(element: any, classname: string): any; setStyle(element: any, stylename: string, stylevalue: string): void; removeStyle(element: any, stylename: string): void; getStyle(element: any, stylename: string): any; tagName(element: any): string; attributeMap(element: any): any; hasAttribute(element: any, attribute: string): any; getAttribute(element: any, attribute: string): any; setAttribute(element: any, name: string, value: string): void; removeAttribute(element: any, attribute: string): any; templateAwareRoot(el: any): any; createHtmlDocument(): Document; defaultDoc(): Document; getBoundingClientRect(el: any): any; getTitle(): string; setTitle(newTitle: string): void; elementMatches(n: any, selector: string): boolean; isTemplateElement(el: any): boolean; isTextNode(node: Node): boolean; isCommentNode(node: Node): boolean; isElementNode(node: Node): boolean; hasShadowRoot(node: any): boolean; isShadowRoot(node: any): boolean; importIntoDoc(node: Node): Node; isPageRule(rule: any): boolean; isStyleRule(rule: any): boolean; isMediaRule(rule: any): boolean; isKeyframesRule(rule: any): boolean; getHref(el: Element): string; getEventKey(event: any): string; getGlobalEventTarget(target: string): EventTarget; getHistory(): History; getLocation(): Location; getBaseHref(): any; } } declare module "angular2/di" { function bind(token: any): any; class Injector { resolveAndCreateChild(bindings: [any]): Injector; } var Binding: any; var ResolvedBinding: any; var Dependency: any; var Key: any; var KeyRegistry: any; var TypeLiteral: any; var NoBindingError: any; var AbstractBindingError: any; var AsyncBindingError: any; var CyclicDependencyError: any; var InstantiationError: any; var InvalidBindingError: any; var NoAnnotationError: any; var OpaqueToken: any; var ___esModule: any; var InjectAnnotation: any; var InjectPromiseAnnotation: any; var InjectLazyAnnotation: any; var OptionalAnnotation: any; var InjectableAnnotation: any; var DependencyAnnotation: any; var Inject: any; var InjectPromise: any; var InjectLazy: any; var Optional: any; var Injectable: any; }
"use strict"; /** * Since only a single constructor is being exported as module.exports this comment isn't documented. * The class and module are the same thing, the contructor comment takes precedence. * @module RandomStaryBackgroundContext */ var paper = require('paper/dist/paper-core.js'); /** * The constructor of a context object to generate a random stary background. * This is an example context with methods to draw and update the background of a hexBoard * Drawing a starry background, since I'm personally interested in making a space game. * However, you could draw water or clouds if doing an ocean or flight game * @implements {Context} * @constructor * @todo This context is a bit hard coded for the demo, needs to be made more useful */ module.exports = function RandomStaryBackgroundContext() { //Protect the constructor from being called as a normal method if (!(this instanceof RandomStaryBackgroundContext)) { return new RandomStaryBackgroundContext(); } var context = this; // Documentation inherited from Context#init this.init = function(backgroundGroup) { //Create a stationary background of dimmer, denser stars var farLayer = context.createStarGroup(0.5, 1.1, paper.view.size.width, paper.view.size.height, 1000); backgroundGroup.addChild(farLayer); //Create a parallax background of fewer, brighter stars. Make it 4 times the view window in size var nearLayer = context.createStarGroup(1, 2.1, 4*paper.view.size.width, 4*paper.view.size.height, 1000); nearLayer.position.x = -0.5*paper.view.size.width; nearLayer.position.y = -0.5*paper.view.size.height; backgroundGroup.addChild(nearLayer); context.nearLayer = nearLayer; }; // Documentation inherited from Context#updatePosition this.updatePosition = function(dx, dy) { //Scroll more slowly than the grid, and cap out position. Don't want to bother generating an infinite star field, most of the action will be in the middle if (dx > 0) { context.nearLayer.position.x = Math.min( -0.5*paper.view.size.width + dx / 10, 0); } else { context.nearLayer.position.x = Math.max( -0.5*paper.view.size.width + dx / 10, -paper.view.size.width); } if (dy > 0) { context.nearLayer.position.y = Math.min( -0.5*paper.view.size.height + dy / 10, 0); } else { context.nearLayer.position.y = Math.max( -0.5*paper.view.size.height + dy / 10, -paper.view.size.height); } }; this.reDraw = function(screenResized, mapRotated, mapScaled) { //Eh, don't do anything yet. Only screen resized implemented which this context doesn't care about }; }; /** * Helper method for generating a random number * @param {integer} min - The minimum number to generate * @param {integer} max - The maximum number to generate */ module.exports.prototype.random = function (min, max) { return Math.round((Math.random() * (max - min)) + min); }; module.exports.prototype.STAR_COLOURS = ["#ffffff", "#ffe9c4", "#d4fbff"]; /** * Heleper method to create the star group with some variables * @ param {integer} maxBrightness - Controls how bright the stars can be * @ param {integer} maxBrightness - Controls how large the stars can be * @ param {integer} width - The width of the rectangle to generate stars for * @ param {integer} height - The height of the rectangle to generate stars for * @ param {integer} star_number - The number of stars to generate */ module.exports.prototype.createStarGroup = function( maxBrightness, maxRadius, width, height, star_number) { var starGroup = new paper.Group(); starGroup.pivot = new paper.Point(0, 0); var x, // x position of the star y; // y position of the star for (var i = 0; i < star_number; i++) { x = Math.random() * width; // random x position y = Math.random() * height; // random y position var star = new paper.Shape.Circle(new paper.Point(x, y), Math.random() * maxRadius); star.fillColor = this.STAR_COLOURS[this.random(0,this. STAR_COLOURS.length)]; starGroup.addChild(star); } var starRaster = starGroup.rasterize(); starGroup.remove(); starRaster.pivot = new paper.Point(0 - starRaster.position.x, 0 - starRaster.position.y); return starRaster; }; // Documentation inherited from Context#mouseDown module.exports.prototype.mouseDown = function( x, y) { //This is nothing to click, always return false return false; }; // Documentation inherited from Context#mouseDragged module.exports.prototype.mouseDragged = function( x, y, dx, dy) { //We never claim mouseDown, so this actually will never be called }; // Documentation inherited from Context#mouseReleased module.exports.prototype.mouseReleased = function(wasDrag) { //We never claim mouseDown, so this actually will never be called };
<filename>Logic/Stage/preprocessor/preprocess.cpp<gh_stars>0 /* Preprocessor 0.5 Copyright (c) 2005 <NAME> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. The original version of this library can be located at: http://www.angelcode.com/angelscript/ under addons & utilities or at http://www.omnisu.com <NAME> <EMAIL> */ #pragma warning(disable:4786) #include "lex.h" #include "preprocess.h" #include "lexem_list.h" #include "define_table.h" #include <list> #include <map> #include <string> #include <vector> #include <fstream> #include <iostream> #include <sstream> using namespace Preprocessor; namespace { DefineTable application_specified; OutStream* error_stream; typedef std::map<std::string,PragmaCallback*> PragmaMap; typedef PragmaMap::iterator PragmaIterator; PragmaMap registered_pragmas; LineNumberTranslator::Table* LNT; std::string root_file; std::string current_file; unsigned int current_line; unsigned int lines_this_file; unsigned int number_of_errors; void PrintErrorMessage(const std::string& errmsg) { (*error_stream) << current_file << " (" << lines_this_file << ") Error : " << errmsg << "\n"; ++number_of_errors; } void PrintWarningMessage(const std::string& errmsg) { (*error_stream) << current_file << " (" << lines_this_file << ") Warning : " << errmsg << "\n"; } std::string removeQuotes(const std::string& in) { return in.substr(1,in.size()-2); } class CleanUpPragmas { public: ~CleanUpPragmas() { PragmaIterator I = registered_pragmas.begin(); for (; I != registered_pragmas.end(); ++I) { delete I->second; } } }; CleanUpPragmas nasty_little_hack_this_is; } void Preprocessor::register_pragma(const std::string& name, Preprocessor::PragmaCallback* pc) { if (pc == 0) return; PragmaIterator I = registered_pragmas.find(name); if (I != registered_pragmas.end()) { delete I->second; //registered_pragmas.erase(I); } registered_pragmas[name] = pc; } static void callPragma(const std::string& name, const Preprocessor::PragmaInstance& parms) { PragmaIterator I = registered_pragmas.find(name); if (I == registered_pragmas.end()) { PrintErrorMessage("Unknown pragma command."); return; } if (I->second) I->second->pragma(parms); } class Preprocessor::LineNumberTranslator::Table { public: struct Entry { std::string file; unsigned int start_line; unsigned int offset; }; std::vector<Entry> lines; //Assuming blocks were entered in the proper order. Entry& search(unsigned int linenumber) { for (size_t i = 1; i < lines.size(); ++i) { if (linenumber < lines[i].start_line) { //Found the first block after our line. return lines[i-1]; } } return lines[lines.size()-1]; //Line must be in last block. } void AddLineRange(const std::string& file, unsigned int start_line, unsigned int offset) { Entry e; e.file = file; e.start_line = start_line; e.offset = offset; lines.push_back(e); } }; std::string Preprocessor::LineNumberTranslator::ResolveOriginalFile(unsigned int linenumber) { if (!pimple) return "ERROR"; return pimple->search(linenumber).file; } unsigned int Preprocessor::LineNumberTranslator::ResolveOriginalLine(unsigned int linenumber) { if (!pimple) return 0; return linenumber - pimple->search(linenumber).offset; } Preprocessor::LineNumberTranslator::LineNumberTranslator() : pimple(0) {} Preprocessor::LineNumberTranslator::~LineNumberTranslator() { delete pimple; } void Preprocessor::LineNumberTranslator::SetTable(Preprocessor::LineNumberTranslator::Table *t) { delete pimple; pimple = t; } static LLITR findLexem(LLITR ITR, LLITR END, LexemType type) { while(ITR != END && ITR->type != type) { ++ITR; } return ITR; } static LLITR parseStatement(LLITR ITR, LLITR END, LexemList& dest) { int depth = 0; while (ITR != END) { if (ITR->value == "," && depth == 0) return ITR; if (ITR->type == CLOSE && depth == 0) return ITR; if (ITR->type == SEMICOLON && depth == 0) return ITR; dest.push_back(*ITR); if (ITR->type == OPEN) ++depth; if (ITR->type == CLOSE) { if (depth == 0) PrintErrorMessage("Mismatched braces while parsing statement."); --depth; } ++ITR; } return ITR; } static LLITR parseDefineArguments(LLITR ITR, LLITR END, LexemList& lexems, std::vector<LexemList>& args) { if (ITR == END || ITR->value != "(") { PrintErrorMessage("Expected argument list."); return ITR; } LLITR begin_erase = ITR; ++ITR; while (ITR != END) { LexemList argument; ITR = parseStatement(ITR,END,argument); args.push_back(argument); if (ITR == END) { PrintErrorMessage("0x0FA1 Unexpected end of file."); return ITR; } if (ITR->value == ",") { ++ITR; if (ITR == END) { PrintErrorMessage("0x0FA2 Unexpected end of file."); return ITR; } continue; } if (ITR->value == ")") { ++ITR; break; } } return lexems.erase(begin_erase,ITR); } static LLITR expandDefine(LLITR ITR, LLITR END, LexemList& lexems, DefineTable& define_table) { DefineTable::iterator define_entry = define_table.find(ITR->value); if (define_entry == define_table.end()) return ++ITR; ITR = lexems.erase(ITR); if (define_entry->second.arguments.size() == 0) { lexems.insert(ITR, define_entry->second.lexems.begin(), define_entry->second.lexems.end()); return ITR; } //define has arguments. std::vector<LexemList> arguments; ITR = parseDefineArguments(ITR,END,lexems,arguments); if (define_entry->second.arguments.size() != arguments.size()) { PrintErrorMessage("Didn't supply right number of arguments to define."); return ITR; } LexemList temp_list(define_entry->second.lexems.begin(),define_entry->second.lexems.end()); LLITR TLI = temp_list.begin(); while (TLI != temp_list.end()) { ArgSet::iterator arg = define_entry->second.arguments.find(TLI->value); if (arg == define_entry->second.arguments.end()) { ++TLI; continue; } TLI = temp_list.erase(TLI); temp_list.insert(TLI,arguments[arg->second].begin(),arguments[arg->second].end()); } lexems.insert(ITR,temp_list.begin(),temp_list.end()); return ITR; //expand arguments in templist. } static void parseDefine(DefineTable& define_table, LexemList& def_lexems) { def_lexems.pop_front(); //remove #define directive if (def_lexems.empty()) { PrintErrorMessage("Define directive without arguments."); return; } Lexem name = *def_lexems.begin(); if (name.type != IDENTIFIER) { PrintErrorMessage("Define's name was not an identifier."); return; } def_lexems.pop_front(); DefineEntry def; if (!def_lexems.empty()) { if (def_lexems.begin()->type == PREPROCESSOR && def_lexems.begin()->value == "#") { //Macro has arguments def_lexems.pop_front(); if (def_lexems.empty()) { PrintErrorMessage("Expected arguments."); return; } if (def_lexems.begin()->value != "(") { PrintErrorMessage("Expected arguments."); return; } def_lexems.pop_front(); int num_args = 0; while(!def_lexems.empty() && def_lexems.begin()->value != ")") { if (def_lexems.begin()->type != IDENTIFIER) { PrintErrorMessage("Expected identifier."); return; } def.arguments[def_lexems.begin()->value] = num_args; def_lexems.pop_front(); if (!def_lexems.empty() && def_lexems.begin()->value == ",") { def_lexems.pop_front(); } ++num_args; } if (!def_lexems.empty()) { if (def_lexems.begin()->value != ")") { PrintErrorMessage("Expected closing parantheses."); return; } def_lexems.pop_front(); } else { PrintErrorMessage("0x0FA3 Unexpected end of line."); return; } } LLITR DLB = def_lexems.begin(); while (DLB != def_lexems.end()) { DLB = expandDefine(DLB,def_lexems.end(),def_lexems,define_table); } } def.lexems = def_lexems; define_table[name.value] = def; } static LLITR parseIfDef(LLITR ITR, LLITR END) { int depth = 0; int newlines = 0; bool found_end = false; while (ITR != END) { if (ITR->type == NEWLINE) ++newlines; else if (ITR->type == PREPROCESSOR) { if (ITR->value == "#endif" && depth == 0) { ++ITR; found_end = true; break; } if (ITR->value == "#ifdef" || ITR->value == "#ifndef") ++depth; if (ITR->value == "#endif" && depth > 0) --depth; } ++ITR; } if (ITR == END && !found_end) { PrintErrorMessage("0x0FA4 Unexpected end of file."); return ITR; } while (newlines > 0) { --ITR; ITR->type = NEWLINE; ITR->value = "\n"; --newlines; } return ITR; } static void parseIf(LexemList& directive, std::string& name_out) { directive.pop_front(); if (directive.empty()) { PrintErrorMessage("Expected argument."); return; } name_out = directive.begin()->value; directive.pop_front(); if (!directive.empty()) PrintErrorMessage("Too many arguments."); } static std::string addPaths(const std::string& first, const std::string& second) { std::string result; size_t slash_pos = first.find_last_of('/'); if (slash_pos == 0 || slash_pos >= first.size()) return second; result = first.substr(0,slash_pos+1); result += second; return result; } static void parsePragma(LexemList& args) { args.pop_front(); if (args.empty()) { PrintErrorMessage("Pragmas need arguments."); return; } std::string p_name = args.begin()->value; args.pop_front(); std::string p_args; if (!args.empty()) { if (args.begin()->type != STRING) PrintErrorMessage("Pragma parameter should be a string literal."); p_args = removeQuotes(args.begin()->value); args.pop_front(); } if (!args.empty()) PrintErrorMessage("Too many parameters to pragma."); Preprocessor::PragmaInstance PI; PI.text = p_args; PI.current_file = current_file; PI.current_file_line = lines_this_file; PI.root_file = root_file; PI.global_line = current_line; callPragma(p_name,PI); } static void setLineMacro(DefineTable& define_table, unsigned int line) { DefineEntry def; Lexem l; l.type = NUMBER; std::stringstream sstr; sstr << line; sstr >> l.value; def.lexems.push_back(l); define_table["__LINE__"] = def; } static void setFileMacro(DefineTable& define_table, const std::string& file) { DefineEntry def; Lexem l; l.type = STRING; l.value = std::string("\"")+file+"\""; def.lexems.push_back(l); define_table["__FILE__"] = def; } static void recursivePreprocess( std::string filename, FileSource& file_source, LexemList& lexems, DefineTable& define_table) { std::vector<char> data; unsigned int start_line = current_line; lines_this_file = 0; current_file = filename; setFileMacro(define_table,current_file); setLineMacro(define_table,lines_this_file); bool loaded = file_source.LoadFile(filename,data); if (!loaded) { PrintErrorMessage(std::string("Could not open file ")+filename); return; } if (data.size() == 0) return; char* d_end = &data[data.size()-1]; ++d_end; lex(&data[0],d_end,lexems); LexemList::iterator ITR = lexems.begin(); LexemList::iterator END = lexems.end(); while ( ITR != END ) { if (ITR->type == NEWLINE) { ++current_line; ++lines_this_file; ++ITR; setLineMacro(define_table,lines_this_file); } else if (ITR->type == PREPROCESSOR) { LLITR start_of_line = ITR; LLITR end_of_line = findLexem(ITR,END,NEWLINE); LexemList directive(start_of_line,end_of_line); ITR = lexems.erase(start_of_line,end_of_line); std::string value = directive.begin()->value; if (value == "#define") { parseDefine(define_table,directive); } else if (value == "#ifdef") { std::string def_name; parseIf(directive,def_name); DefineTable::iterator DTI = define_table.find(def_name); if (DTI == define_table.end()) { LLITR splice_to = parseIfDef(ITR,END); ITR = lexems.erase(ITR,splice_to); } } else if (value == "#ifndef") { std::string def_name; parseIf(directive,def_name); DefineTable::iterator DTI = define_table.find(def_name); if (DTI != define_table.end()) { LLITR splice_to = parseIfDef(ITR,END); ITR = lexems.erase(ITR,splice_to); } } else if (value == "#endif") { //ignore } else if (value == "#include") { if (LNT) LNT->AddLineRange(filename,start_line,current_line-lines_this_file); unsigned int save_lines_this_file = lines_this_file; std::string file_name; parseIf(directive,file_name); LexemList next_file; recursivePreprocess( addPaths(filename,removeQuotes(file_name)), file_source, next_file, define_table); lexems.splice(ITR,next_file); start_line = current_line; lines_this_file = save_lines_this_file; current_file = filename; setFileMacro(define_table,current_file); setLineMacro(define_table,lines_this_file); } else if (value == "#pragma") { parsePragma(directive); } else if (value == "#warning") { std::string msg; parseIf(directive,msg); PrintWarningMessage(msg); } else { PrintErrorMessage("Unknown directive."); } } else if (ITR->type == IDENTIFIER) { ITR = expandDefine(ITR,END,lexems,define_table); } else { ++ITR; } } if (LNT) LNT->AddLineRange(filename,start_line,current_line-lines_this_file); } int Preprocessor::preprocess( std::string source_file, FileSource& file_source, OutStream& destination, OutStream& err, LineNumberTranslator* trans) { if (trans) LNT = new LineNumberTranslator::Table; else LNT = 0; current_file = "ERROR"; current_line = 0; DefineTable define_table = application_specified; LexemList lexems; error_stream = &err; number_of_errors = 0; root_file = source_file; recursivePreprocess(source_file,file_source,lexems,define_table); printLexemList(lexems,destination); if (trans) { trans->SetTable(LNT); LNT = 0; } return number_of_errors; } void Preprocessor::define(const std::string& str) { if (str.length() == 0) return; std::string data = "#define "; data += str; char* d_end = &data[data.length()-1]; ++d_end; LexemList lexems; lex(&data[0],d_end,lexems); ::parseDefine(application_specified,lexems); }
<filename>react-client/src/Deaths.js import React, { useEffect, useRef } from 'react' // deaths: // { // text: Harnus was just struck down // time: 2020-01-25T22:36:07.919Z // } export default function Deaths({ deaths, sendCommand }) { const deathsEndRef = useRef(null) const scrollToBottom = () => deathsEndRef.current.scrollIntoView() useEffect(scrollToBottom, [deaths]); return ( <div> <h3>Deaths</h3> <div style={{ height: 120, overflowY: "auto" }}> <table> <thead> <tr> <td>Text</td> <td>Time</td> </tr> </thead> <tbody> {deaths.map((death, i) => ( <Death key={i} death={death} sendCommand={sendCommand} /> ))} </tbody> </table> <div ref={deathsEndRef} /> </div> </div> ) } function Death({ death, sendCommand }) { const { text, time } = death const playerName = death.match(/(.+) was just struck down/)[1] const deathDateTime = new Date(time) const clickable = playerName.length ? true : false return ( <tr> <td className={clickable ? "clickable" : "unavailable"} onClick={() => { clickable && sendCommand(`profile ${playerName}`) }}> {text} </td> <td nowrap="true">{deathDateTime.toLocaleDateString('en-us', { hc: "h24", timeStyle: "short" })}</td> </tr> ) }
import random import string def generate_migration_password(): password_length = 10 characters = string.ascii_letters + string.digits return ''.join(random.choice(characters) for _ in range(password_length))
package com.honyum.elevatorMan.net; import com.honyum.elevatorMan.net.base.RequestBean; import java.io.Serializable; /** * Created by star on 2018/4/9. */ public class EditPersonRequest extends RequestBean { private EditPersonRequestBody body; public EditPersonRequestBody getBody() { return body; } public void setBody(EditPersonRequestBody body) { this.body = body; } public class EditPersonRequestBody implements Serializable { private String reDistributeType; private String branchId; private String orderId; private String assistantId; private String assistantName; private String workId; private String workName; public String getBranchId() { return branchId; } public void setBranchId(String branchId) { this.branchId = branchId; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getAssistantId() { return assistantId; } public void setAssistantId(String assistantId) { this.assistantId = assistantId; } public String getAssistantName() { return assistantName; } public void setAssistantName(String assistantName) { this.assistantName = assistantName; } public String getWorkId() { return workId; } public void setWorkId(String workId) { this.workId = workId; } public String getWorkName() { return workName; } public void setWorkName(String workName) { this.workName = workName; } public String getReDistributeType() { return reDistributeType; } public void setReDistributeType(String reDistributeType) { this.reDistributeType = reDistributeType; } } }
#!/bin/bash # Copyright 2018-present Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Always run this script from the root of the Buck project directory. # # Remove any residual files that could derail build and publication. # cd "$(git rev-parse --show-toplevel)" || exit ant clean cd "$(git rev-parse --show-toplevel)/docs" || exit buck run //docs:generate_buckconfig_aliases exec java -jar plovr-81ed862.jar soyweb --port 9814 --dir . --globals globals.json
#!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" PATH=$(cd ${DIR} && npm bin):$PATH POSTMAN_DIR="${DIR}/.." NEWMAN_REQUEST_DELAY=${NEWMAN_REQUEST_DELAY:=100} newman run \ --delay-request=${NEWMAN_REQUEST_DELAY} \ --folder='Add parties to DFSP backends' \ ${POSTMAN_DIR}/PISP.postman_collection.json.postman_collection.json
<filename>app/controllers/index.js const RestController = require('./RestController'); const SocketController = require('./SocketController'); const TrayController = require('./TrayController'); module.exports = { RestController, SocketController, TrayController, };
<reponame>Adrian-Garcia/Algorithms #include <iostream> // El Tesoro de la Tortuga // Matricula: A01351166 // Nombre: <NAME> using namespace std; #define MAX 100 int turtle(int mat[MAX][MAX], int n, int m){ // Primera Fila for (int i=1; i<n; i++) { mat[i][0]+=mat[i-1][0]; } // Primera Columna for (int i=1; i<m; i++) { mat[0][i]+=mat[0][i-1]; } // Hacemos cuadrado interno for (int i=1; i<n; i++) { for (int j=1; j<m; j++) { mat[i][j] += max(mat[i-1][j], mat[i][j-1]); } } // Regresamos ultimo valor de la matriz return mat[n-1][m-1]; } void print(int mat[MAX][MAX], int n, int m){ for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ cout << mat[i][j]<< " "; } cout << endl; } } int main(){ int n, m; int mat[MAX][MAX]; cin >> n >> m; for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ cin >> mat[i][j]; } } // print(mat, n, m); cout << turtle(mat, n, m)<<endl; return 0; }
<reponame>moizKachwala/PollingApp<gh_stars>0 package com.example.polls.validators; import com.example.polls.payload.user.UserDto; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; @Component public class UserValidator implements Validator { public static final int USERNAME_MAX_LIMIT = 50; private static final String USER_EMAIL_EMPTY = "user.email.empty"; private static final String USER_USERNAME_EMPTY = "user.username.empty"; private static final String USER_PASSWORD_EMPTY = "<PASSWORD>"; private static final String USER_USERNAME_MAX_LIMIT = "user.username.max.length"; private static final String USER_ROLES_EMPTY = "user.role.empty"; private static final String USER_EMAIL_INVALID = "user.email.invalid"; private static final String USER_PASSWORD_MAX_LENGTH = "<PASSWORD>.password.<PASSWORD>"; @Override public boolean supports(Class<?> aClass) { return UserDto.class.equals(aClass); } @Override public void validate(Object o, Errors errors) { UserDto user = (UserDto)o; String username = user.getUsername(); String email = user.getEmail(); String password = <PASSWORD>(); Long id = user.getId(); boolean isNew = id == null; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", USER_EMAIL_EMPTY, USER_EMAIL_EMPTY); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", USER_USERNAME_EMPTY, USER_USERNAME_EMPTY); if(isNew) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", USER_PASSWORD_EMPTY, USER_PASSWORD_EMPTY); } if(!StringUtils.isEmpty(username) && username.length() > USERNAME_MAX_LIMIT) { errors.rejectValue("username", USER_USERNAME_MAX_LIMIT, new Object[]{}, USER_USERNAME_MAX_LIMIT); } if(user.getRoles().size() < 0) { errors.rejectValue("username", USER_ROLES_EMPTY, new Object[]{}, USER_ROLES_EMPTY); } if(!StringUtils.isEmpty(email) && !email.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")){ errors.rejectValue("email",USER_EMAIL_INVALID, new Object[]{}, USER_EMAIL_INVALID); } if(isNew) { if (!StringUtils.isEmpty(password) && password.length() < 8) { errors.rejectValue("password", USER_PASSWORD_MAX_LENGTH, new Object[]{}, USER_PASSWORD_MAX_LENGTH); } } } }
<reponame>bamboolife/PanelSwitchHelper<filename>app/src/main/java/com/example/demo/scene/chat/ChatActivity.java package com.example.demo.scene.chat; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Toast; import com.effective.R; import com.effective.android.panel.PanelSwitchHelper; import com.effective.android.panel.interfaces.ContentScrollMeasurer; import com.effective.android.panel.interfaces.listener.OnPanelChangeListener; import com.effective.android.panel.view.panel.IPanelView; import com.effective.android.panel.view.panel.PanelView; import com.effective.databinding.CommonChatLayoutBinding; import com.example.demo.Constants; import com.example.demo.anno.ChatPageType; import com.example.demo.scene.chat.adapter.ChatAdapter; import com.example.demo.scene.chat.adapter.ChatInfo; import com.example.demo.scene.chat.emotion.EmotionPagerView; import com.example.demo.scene.chat.emotion.Emotions; import com.example.demo.systemui.StatusbarHelper; import com.example.demo.util.DisplayUtils; import com.rd.PageIndicatorView; import org.jetbrains.annotations.NotNull; /** * Created by yummyLau on 18-7-11 * Email: <EMAIL> * blog: yummylau.com */ public class ChatActivity extends AppCompatActivity { public static void start(Context context, @ChatPageType int type) { Intent intent = new Intent(context, ChatActivity.class); intent.putExtra(Constants.KEY_PAGE_TYPE, type); context.startActivity(intent); } private CommonChatLayoutBinding mBinding; private PanelSwitchHelper mHelper; private ChatAdapter mAdapter; private LinearLayoutManager mLinearLayoutManager; private static final String TAG = ChatActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int type = getIntent().getIntExtra(Constants.KEY_PAGE_TYPE, ChatPageType.DEFAULT); switch (type) { case ChatPageType.TITLE_BAR: { mBinding = DataBindingUtil.setContentView(this, R.layout.common_chat_layout); mBinding.getRoot().setBackgroundColor(ContextCompat.getColor(this, R.color.common_page_bg_color)); getSupportActionBar().setTitle("Activity-有标题栏"); break; } case ChatPageType.COLOR_STATUS_BAR: { mBinding = DataBindingUtil.setContentView(this, R.layout.common_chat_layout); StatusbarHelper.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorPrimary)); mBinding.statusBar.setVisibility(View.VISIBLE); getSupportActionBar().setTitle("Activity-有标题栏,状态栏着色"); mBinding.getRoot().setBackgroundColor(ContextCompat.getColor(this, R.color.common_page_bg_color)); break; } case ChatPageType.DEFAULT: { supportRequestWindowFeature(Window.FEATURE_NO_TITLE); mBinding = DataBindingUtil.setContentView(this, R.layout.common_chat_layout); mBinding.getRoot().setBackgroundColor(ContextCompat.getColor(this, R.color.common_page_bg_color)); break; } case ChatPageType.CUS_TITLE_BAR: { supportRequestWindowFeature(Window.FEATURE_NO_TITLE); mBinding = DataBindingUtil.setContentView(this, R.layout.common_chat_layout); mBinding.cusTitleBar.setVisibility(View.VISIBLE); mBinding.title.setText("Activity-自定义标题栏"); mBinding.getRoot().setBackgroundColor(ContextCompat.getColor(this, R.color.common_page_bg_color)); break; } case ChatPageType.TRANSPARENT_STATUS_BAR: { supportRequestWindowFeature(Window.FEATURE_NO_TITLE); mBinding = DataBindingUtil.setContentView(this, R.layout.common_chat_layout); mBinding.statusBar.setVisibility(View.VISIBLE); StatusbarHelper.setStatusBarColor(this, Color.TRANSPARENT); mBinding.getRoot().setBackgroundResource(R.drawable.bg_gradient); break; } case ChatPageType.TRANSPARENT_STATUS_BAR_DRAW_UNDER: { supportRequestWindowFeature(Window.FEATURE_NO_TITLE); mBinding = DataBindingUtil.setContentView(this, R.layout.common_chat_layout); StatusbarHelper.setStatusBarColor(this, Color.TRANSPARENT); mBinding.getRoot().setBackgroundResource(R.drawable.bg_gradient); break; } } initView(); } private void initView() { mLinearLayoutManager = new LinearLayoutManager(this); mBinding.recyclerView.setLayoutManager(mLinearLayoutManager); mAdapter = new ChatAdapter(this, 4); mBinding.recyclerView.setAdapter(mAdapter); mBinding.send.setOnClickListener(v -> { String content = mBinding.editText.getText().toString(); if (TextUtils.isEmpty(content)) { Toast.makeText(ChatActivity.this, "当前没有输入", Toast.LENGTH_SHORT).show(); return; } mAdapter.insertInfo(ChatInfo.CREATE(content)); mBinding.editText.setText(null); scrollToBottom(); }); } private void scrollToBottom() { mBinding.getRoot().post(() -> mLinearLayoutManager.scrollToPosition(mAdapter.getItemCount() - 1)); } @Override protected void onStart() { super.onStart(); if (mHelper == null) { mHelper = new PanelSwitchHelper.Builder(this) //可选 .addKeyboardStateListener((visible, height) -> Log.d(TAG, "系统键盘是否可见 : " + visible + " 高度为:" + height)) .addEditTextFocusChangeListener((view, hasFocus) -> { Log.d(TAG, "输入框是否获得焦点 : " + hasFocus); if (hasFocus) { scrollToBottom(); } }) //可选 .addViewClickListener(view -> { switch (view.getId()) { case R.id.edit_text: case R.id.add_btn: case R.id.emotion_btn: { scrollToBottom(); } } Log.d(TAG, "点击了View : " + view); }) //可选 .addPanelChangeListener(new OnPanelChangeListener() { @Override public void onKeyboard() { Log.d(TAG, "唤起系统输入法"); mBinding.emotionBtn.setSelected(false); scrollToBottom(); } @Override public void onNone() { Log.d(TAG, "隐藏所有面板"); mBinding.emotionBtn.setSelected(false); } @Override public void onPanel(IPanelView view) { Log.d(TAG, "唤起面板 : " + view); if (view instanceof PanelView) { mBinding.emotionBtn.setSelected(((PanelView) view).getId() == R.id.panel_emotion ? true : false); scrollToBottom(); } } @Override public void onPanelSizeChange(IPanelView panelView, boolean portrait, int oldWidth, int oldHeight, int width, int height) { if (panelView instanceof PanelView) { switch (((PanelView) panelView).getId()) { case R.id.panel_emotion: { EmotionPagerView pagerView = mBinding.getRoot().findViewById(R.id.view_pager); int viewPagerSize = height - DisplayUtils.dip2px(ChatActivity.this, 30f); pagerView.buildEmotionViews( (PageIndicatorView) mBinding.getRoot().findViewById(R.id.pageIndicatorView), mBinding.editText, Emotions.getEmotions(), width, viewPagerSize); break; } case R.id.panel_addition: { //auto center,nothing to do break; } } } } }) .addContentScrollMeasurer(new ContentScrollMeasurer() { @Override public int getScrollDistance(int defaultDistance) { return defaultDistance - unfilledHeight; } @Override public int getScrollViewId() { return R.id.recycler_view; } }) .logTrack(true) //output log .build(); mBinding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof LinearLayoutManager) { int childCount = recyclerView.getChildCount(); if (childCount > 0) { View lastChildView = recyclerView.getChildAt(childCount - 1); int bottom = lastChildView.getBottom(); int listHeight = mBinding.recyclerView.getHeight() - mBinding.recyclerView.getPaddingBottom(); unfilledHeight = listHeight - bottom; } } } }); } mBinding.recyclerView.setPanelSwitchHelper(mHelper); } private int unfilledHeight = 0; @Override public void onBackPressed() { if (mHelper != null && mHelper.hookSystemBackByPanelSwitcher()) { return; } super.onBackPressed(); } }
<gh_stars>1-10 package endpoint import ( "crypto/x509" "encoding/json" "encoding/pem" "github.com/emilhauk/identity-api/model" "github.com/emilhauk/identity-api/store" "github.com/sirupsen/logrus" "net/http" ) func PublicKeyHandler(w http.ResponseWriter, r *http.Request, keyStore *store.RSAKeyStore) { if r.Method != http.MethodGet { w.WriteHeader(http.StatusMethodNotAllowed) return } keys := map[string]string{} for keyId, keyPair := range keyStore.GetAllKeyPairs() { publicKey := &pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(keyPair.Public)} keys[keyId] = string(pem.EncodeToMemory(publicKey)) } response, err := json.Marshal(model.PublicKeysResponse{ keys, []model.Error{}, }) if err != nil { logrus.Errorln("Error marshalling PublicKeysResponse", err) w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(response) }
#!/bin/bash dieharder -d 16 -g 4 -S 2973139744
#!/bin/bash # Handles checking of file after picking extention # Call using file_checker file_checker () { break_line cd $first total_files=$(ls -1q * | wc -l) echo "Total file/s in the directory: $total_files" ext_files=$(ls -1q *."$ext" | wc -l) || echo "No .$ext file exists in the directory." echo "Total .$ext file/s in the directory: $ext_files" cd .. if [ $total_files != $ext_files ] then handle_error_extention_compactibility else : fi }
<filename>tests/controller/channel/PubSubTest.java //package controller.channel; // //import controller.channel.messages.Message; //import controller.channel.messages.VariableUpdate; //import interpreter.core.elements.Value; //import org.junit.jupiter.api.Test; // //import static org.junit.jupiter.api.Assertions.*; // //class PubSubTest { // @Test // void publish() { // PubSub pubsub = new PubSub(); // pubsub.subscribe(PubSub.Channel.VARIABLE_UPDATE, (msg)->{ // VariableUpdate message = (VariableUpdate) msg; // System.out.println(msg); // }); // } // // @Test // void publishSync() { // PubSub pubsub = new PubSub(); // pubsub.subscribeSync(PubSub.Channel.VARIABLE_UPDATE, this::lambda); // System.out.println(pubsub.publishSync(PubSub.Channel.VARIABLE_UPDATE, new VariableUpdate("sfs", "4"))); // } // // Value lambda(Message msg) { // return null; // } //}
clear echo "==================================================================" echo "== B E N C H M A R K O B J E C T S ==" echo "== ==" echo "== G C C C O M P I L E R ==" echo "==================================================================" echo "." echo "C O M P I L I N G . . . . . . . . . . ." g++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -s -o file_generator g++ ./benchmark_objects.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -pthread -s -lpthread -o benchmark_objects echo "." echo "R U N N I N G . . . . . . . . . . ." echo "( The time needed is around 60 minutes depending of your machine )" ./file_generator input.bin 125000000 echo "." date ./benchmark_objects date rm input.bin rm file_generator rm benchmark_objects echo "." echo "." echo "E N D" echo "."
package com.boot.controller; import com.boot.constant.Constant; import com.boot.pojo.BlackList; import com.boot.service.BlackListService; import com.github.pagehelper.PageHelper; import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping(path = "/feign/blacklist") @Api("黑名单Api") public class BlackListController { @Autowired private BlackListService blackListService; @ResponseBody @GetMapping(path = "/selectBlackList") public List<BlackList> selectBlackList(@RequestParam(value = "page") int page, @RequestParam(value = "limit") int limit){ PageHelper.startPage(page, limit); List<BlackList> blackLists = blackListService.selectBlackList(); return blackLists; } @ResponseBody @GetMapping(path = "/selectBlackCount") public int selectBlackCount(){ int count = blackListService.selectBlackCount(); return count; } @ResponseBody @GetMapping(path = "/deleteBlackListByIp") public String deleteBlackListByIp(@RequestParam("ip") String ip){ blackListService.deleteBlackListByIp(ip); return Constant.OK; } @ResponseBody @PostMapping(path = "/addBlackList") public String addBlackList(@RequestBody BlackList blackList){ blackListService.addBlackList(blackList); return Constant.OK; } @ResponseBody @PostMapping(path = "/updateBlackIp") public String updateBlackIp(@RequestParam("oldIp") String oldIp, @RequestParam("newIp") String newIp){ blackListService.updateBlackIp(oldIp,newIp); return Constant.OK; } }
<filename>script.js $(document).ready(function(){ $(".line_outer").on("click", function(){ if($("ul.nav").hasClass("display-flex")){ $("ul.nav").addClass("display-none"); $("ul.nav").removeClass("display-flex"); } else{ $("ul.nav").addClass("display-flex"); $("ul.nav").removeClass("display-none"); } }) });
<reponame>tcmRyan/OpenOLAT /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.upgrade; import java.io.File; import java.nio.file.Paths; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.Logger; import org.olat.admin.layout.LayoutModule; import org.olat.basesecurity.Group; import org.olat.basesecurity.GroupMembership; import org.olat.basesecurity.GroupRoles; import org.olat.basesecurity.SecurityGroup; import org.olat.basesecurity.SecurityGroupMembershipImpl; import org.olat.basesecurity.manager.GroupDAO; import org.olat.basesecurity.model.GroupImpl; import org.olat.basesecurity.model.GroupMembershipImpl; import org.olat.core.commons.persistence.DB; import org.olat.core.logging.Tracing; import org.olat.core.util.StringHelper; import org.olat.core.util.WebappHelper; import org.olat.properties.Property; import org.olat.properties.PropertyManager; import org.olat.resource.OLATResource; import org.olat.upgrade.model.BGResourceRelation; import org.olat.upgrade.model.BusinessGroupUpgrade; import org.olat.upgrade.model.InvitationUpgrade; import org.olat.upgrade.model.RepositoryEntryUpgrade; import org.olat.upgrade.model.RepositoryEntryUpgradeToGroupRelation; import org.springframework.beans.factory.annotation.Autowired; /** * * Initial date: 27.02.2014<br> * @author srosse, <EMAIL>, http://www.frentix.com * */ public class OLATUpgrade_10_0_0 extends OLATUpgrade { private static final Logger log = Tracing.createLoggerFor(OLATUpgrade_10_0_0.class); private static final int BATCH_SIZE = 50; private static final String TASK_BUSINESS_GROUPS = "Upgrade business groups"; private static final String TASK_REPOENTRIES = "Upgrade repository entries"; private static final String TASK_REPOENTRY_TO_BUSINESSGROUP = "Upgrade relation business groups to repository entries"; private static final String TASK_INVITATION = "Upgrade invitations"; private static final String TASK_LOGO = "Upgrade custom logo"; private static final String VERSION = "OLAT_10.0.0"; private static final String PROPERTY_CATEGORY = "_o3_"; private static final String PNAME_LOGOURI = "customizing.img.uri"; private static final String PNAME_LOGOALT = "customizing.img.alt"; private static final String PNAME_LINKURI = "customizing.link.uri"; private static final String PNAME_FOOTERLINE = "customizing.footer.text"; @Autowired private DB dbInstance; @Autowired private GroupDAO groupDao; @Autowired private PropertyManager propertyManager; @Autowired private LayoutModule layoutModule; public OLATUpgrade_10_0_0() { super(); } @Override public String getVersion() { return VERSION; } @Override public boolean doPostSystemInitUpgrade(UpgradeManager upgradeManager) { UpgradeHistoryData uhd = upgradeManager.getUpgradesHistory(VERSION); if (uhd == null) { // has never been called, initialize uhd = new UpgradeHistoryData(); } else if (uhd.isInstallationComplete()) { return false; } boolean allOk = true; allOk &= upgradeLogo(upgradeManager, uhd); allOk &= upgradeBusinessGroups(upgradeManager, uhd); allOk &= upgradeRepositoryEntries(upgradeManager, uhd); allOk &= upgradeRelationsRepoToBusinessGroups(upgradeManager, uhd); allOk &= upgradeInvitation(upgradeManager, uhd); uhd.setInstallationComplete(allOk); upgradeManager.setUpgradesHistory(uhd, VERSION); if(allOk) { log.info(Tracing.M_AUDIT, "Finished OLATUpgrade_10_0_0 successfully!"); } else { log.info(Tracing.M_AUDIT, "OLATUpgrade_10_0_0 not finished, try to restart OpenOLAT!"); } return allOk; } private boolean upgradeLogo(UpgradeManager upgradeManager, UpgradeHistoryData uhd) { if (!uhd.getBooleanDataValue(TASK_LOGO)) { try { Property pLogoUri = propertyManager.findProperty(null, null, null, PROPERTY_CATEGORY, PNAME_LOGOURI); if(pLogoUri != null && StringHelper.containsNonWhitespace(pLogoUri.getStringValue())) { String filename = pLogoUri.getStringValue(); layoutModule.setLogoFilename(filename); File currentFile = Paths.get(WebappHelper.getUserDataRoot(), "system", "logo", filename).toFile(); if(currentFile.exists()) { File target = Paths.get(WebappHelper.getUserDataRoot(), "customizing", "logo", filename).toFile(); FileUtils.copyFile(currentFile, target); } } Property pLogoAlt = propertyManager.findProperty(null, null, null, PROPERTY_CATEGORY, PNAME_LOGOALT); if(pLogoAlt != null && StringHelper.containsNonWhitespace(pLogoAlt.getStringValue())) { layoutModule.setLogoAlt(pLogoAlt.getStringValue()); } Property pLinkUri = propertyManager.findProperty(null, null, null, PROPERTY_CATEGORY, PNAME_LINKURI); if(pLinkUri != null && StringHelper.containsNonWhitespace(pLinkUri.getStringValue())) { layoutModule.setLogoLinkUri(pLinkUri.getStringValue()); } Property pFooterLine = propertyManager.findProperty(null, null, null, PROPERTY_CATEGORY, PNAME_FOOTERLINE); if(pFooterLine != null && StringHelper.containsNonWhitespace(pFooterLine.getTextValue())) { layoutModule.setFooterLine(pFooterLine.getTextValue()); } uhd.setBooleanDataValue(TASK_LOGO, true); upgradeManager.setUpgradesHistory(uhd, VERSION); } catch (Exception e) { log.error("", e); return false; } } return true; } private boolean upgradeBusinessGroups(UpgradeManager upgradeManager, UpgradeHistoryData uhd) { if (!uhd.getBooleanDataValue(TASK_BUSINESS_GROUPS)) { int counter = 0; List<BusinessGroupUpgrade> businessGroups; do { businessGroups = findBusinessGroups(counter, BATCH_SIZE); for(BusinessGroupUpgrade businessGroup:businessGroups) { processBusinessGroup(businessGroup); } counter += businessGroups.size(); log.info(Tracing.M_AUDIT, "Business groups processed: " + businessGroups.size() + ", total processed (" + counter + ")"); dbInstance.commitAndCloseSession(); } while(businessGroups.size() == BATCH_SIZE); uhd.setBooleanDataValue(TASK_BUSINESS_GROUPS, true); upgradeManager.setUpgradesHistory(uhd, VERSION); } return true; } private BusinessGroupUpgrade processBusinessGroup(BusinessGroupUpgrade businessGroup) { Group baseGroup = businessGroup.getBaseGroup(); if(baseGroup != null && baseGroup.getKey() != null) { return businessGroup; } Group group = groupDao.createGroup(); //update tutors processSecurityGroup(group, GroupRoles.coach.name(), businessGroup.getOwnerGroup()); //update participants processSecurityGroup(group, GroupRoles.participant.name(), businessGroup.getPartipiciantGroup()); //update waiting processSecurityGroup(group, GroupRoles.waiting.name(), businessGroup.getWaitingGroup()); dbInstance.commit(); businessGroup.setBaseGroup(group); businessGroup = dbInstance.getCurrentEntityManager().merge(businessGroup); dbInstance.commit(); return businessGroup; } private boolean upgradeRepositoryEntries(UpgradeManager upgradeManager, UpgradeHistoryData uhd) { if (!uhd.getBooleanDataValue(TASK_REPOENTRIES)) { int counter = 0; List<RepositoryEntryUpgrade> repoEntries; do { repoEntries = findRepositoryEntries(counter, BATCH_SIZE); for(RepositoryEntryUpgrade repoEntry:repoEntries) { processRepositoryEntry(repoEntry); } counter += repoEntries.size(); log.info(Tracing.M_AUDIT, "Repository entries processed: " + repoEntries.size() + ", total processed (" + counter + ")"); dbInstance.commitAndCloseSession(); } while(repoEntries.size() == BATCH_SIZE); uhd.setBooleanDataValue(TASK_REPOENTRIES, true); upgradeManager.setUpgradesHistory(uhd, VERSION); } return true; } private void processRepositoryEntry(RepositoryEntryUpgrade repoEntry) { if(isDefaultGroupOk(repoEntry)) return; Group group = groupDao.createGroup(); //update owners processSecurityGroup(group, GroupRoles.owner.name(), repoEntry.getOwnerGroup()); //update tutors processSecurityGroup(group, GroupRoles.coach.name(), repoEntry.getTutorGroup()); //update participants processSecurityGroup(group, GroupRoles.participant.name(), repoEntry.getParticipantGroup()); dbInstance.commit(); RepositoryEntryUpgradeToGroupRelation relation = create(repoEntry, group, true); Set<RepositoryEntryUpgradeToGroupRelation> relations = new HashSet<>(2); relations.add(relation); repoEntry.setGroups(relations); dbInstance.commit(); } public RepositoryEntryUpgradeToGroupRelation create(RepositoryEntryUpgrade entry, Group group, boolean defaultRelation) { RepositoryEntryUpgradeToGroupRelation rel = new RepositoryEntryUpgradeToGroupRelation(); rel.setCreationDate(new Date()); rel.setDefaultGroup(defaultRelation); rel.setGroup(group); rel.setEntry(entry); dbInstance.getCurrentEntityManager().persist(rel); return rel; } private boolean isDefaultGroupOk(RepositoryEntryUpgrade repoEntry) { if(repoEntry.getGroups() == null || repoEntry.getGroups().isEmpty()) { return false; } for(RepositoryEntryUpgradeToGroupRelation rel:repoEntry.getGroups()) { if(rel.isDefaultGroup()) { return true; } } return false; } private boolean upgradeRelationsRepoToBusinessGroups(UpgradeManager upgradeManager, UpgradeHistoryData uhd) { if (!uhd.getBooleanDataValue(TASK_REPOENTRY_TO_BUSINESSGROUP)) { int counter = 0; List<BusinessGroupUpgrade> businessGroups; do { businessGroups = findBusinessGroups(counter, BATCH_SIZE); for(BusinessGroupUpgrade businessGroup:businessGroups) { processRelationToRepo(businessGroup); } counter += businessGroups.size(); log.info(Tracing.M_AUDIT, "Business groups relations processed: " + businessGroups.size() + ", total processed (" + counter + ")"); dbInstance.commitAndCloseSession(); } while(businessGroups.size() == BATCH_SIZE); uhd.setBooleanDataValue(TASK_REPOENTRY_TO_BUSINESSGROUP, true); upgradeManager.setUpgradesHistory(uhd, VERSION); } return true; } private void processRelationToRepo(BusinessGroupUpgrade businessGroup) { try { List<BGResourceRelation> relationsToRepo = findRelations(businessGroup); if(relationsToRepo.size() > 0) { Group refGroup = businessGroup.getBaseGroup(); for(BGResourceRelation relationToRepo:relationsToRepo) { RepositoryEntryUpgrade entry = lookupRepositoryEntry(relationToRepo.getResource()); if(entry == null) { continue; } boolean found = false; Set<RepositoryEntryUpgradeToGroupRelation> groupRelations = entry.getGroups(); for(RepositoryEntryUpgradeToGroupRelation groupRelation:groupRelations) { if(groupRelation.getGroup().equals(refGroup)) { found = true; } } if(!found) { create(entry, refGroup, false); } } } dbInstance.commit(); } catch (Exception e) { log.error("", e); throw e; } } private List<BGResourceRelation> findRelations(BusinessGroupUpgrade group) { StringBuilder sb = new StringBuilder(); sb.append("select rel from ").append(BGResourceRelation.class.getName()).append(" as rel ") .append(" where rel.group.key=:groupKey"); return dbInstance.getCurrentEntityManager().createQuery(sb.toString(), BGResourceRelation.class) .setParameter("groupKey", group.getKey()) .getResultList(); } private boolean upgradeInvitation(UpgradeManager upgradeManager, UpgradeHistoryData uhd) { if (!uhd.getBooleanDataValue(TASK_INVITATION)) { int counter = 0; List<InvitationUpgrade> invitations; do { invitations = findInvitations(counter, BATCH_SIZE); for(InvitationUpgrade invitation:invitations) { if(invitation.getBaseGroup() == null) { processInvitation(invitation); } } counter += invitations.size(); log.info(Tracing.M_AUDIT, "Invitations processed: " + invitations.size() + ", total processed (" + counter + ")"); dbInstance.commitAndCloseSession(); } while(invitations.size() == BATCH_SIZE); uhd.setBooleanDataValue(TASK_INVITATION, true); upgradeManager.setUpgradesHistory(uhd, VERSION); } return true; } private List<InvitationUpgrade> findInvitations(int firstResult, int maxResult) { String sb = "select invitation from invitationupgrade as invitation order by invitation.key"; return dbInstance.getCurrentEntityManager() .createQuery(sb, InvitationUpgrade.class) .setFirstResult(firstResult) .setMaxResults(maxResult) .getResultList(); } private void processInvitation(InvitationUpgrade invitation) { if(invitation.getBaseGroup() == null) { Group invitationGroup = groupDao.createGroup(); invitation.setBaseGroup(invitationGroup); dbInstance.getCurrentEntityManager().merge(invitation); } } private void processSecurityGroup(Group group, String role, SecurityGroup secGroup) { if(secGroup == null) return; List<SecurityGroupMembershipImpl> oldMemberships = getMembershipsOfSecurityGroup(secGroup); for(SecurityGroupMembershipImpl oldMembership:oldMemberships) { GroupMembershipImpl membership = new GroupMembershipImpl(); membership.setCreationDate(oldMembership.getCreationDate()); membership.setLastModified(oldMembership.getLastModified()); membership.setGroup(group); membership.setIdentity(oldMembership.getIdentity()); membership.setRole(role); dbInstance.getCurrentEntityManager().persist(membership); Set<GroupMembership> members = ((GroupImpl)group).getMembers(); if(members == null) { members = new HashSet<>(); ((GroupImpl)group).setMembers(members); } members.add(membership); } } private List<SecurityGroupMembershipImpl> getMembershipsOfSecurityGroup(SecurityGroup secGroup) { StringBuilder sb = new StringBuilder(); sb.append("select membership from ").append(SecurityGroupMembershipImpl.class.getName()).append(" as membership") .append(" where membership.securityGroup=:secGroup"); return dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), SecurityGroupMembershipImpl.class) .setParameter("secGroup", secGroup) .getResultList(); } private List<BusinessGroupUpgrade> findBusinessGroups(int firstResult, int maxResults) { StringBuilder sb = new StringBuilder(); sb.append("select businessgroup from ").append(BusinessGroupUpgrade.class.getName()).append(" businessgroup") .append(" left join fetch businessgroup.baseGroup as baseGroup") .append(" left join fetch businessgroup.ownerGroup as ownerGroup") .append(" left join fetch businessgroup.partipiciantGroup as partipiciantGroup") .append(" left join fetch businessgroup.waitingGroup as waitingGroup") .append(" left join fetch businessgroup.resource as resource") .append(" order by businessgroup.key"); return dbInstance.getCurrentEntityManager().createQuery(sb.toString(), BusinessGroupUpgrade.class) .setFirstResult(firstResult) .setMaxResults(maxResults) .getResultList(); } private List<RepositoryEntryUpgrade> findRepositoryEntries(int firstResult, int maxResults) { StringBuilder sb = new StringBuilder(); sb.append("select v from ").append(RepositoryEntryUpgrade.class.getName()).append(" v") .append(" inner join fetch v.olatResource as ores") .append(" left join fetch v.ownerGroup as ownerGroup") .append(" left join fetch v.participantGroup as participantGroup") .append(" left join fetch v.tutorGroup as tutorGroup") .append(" order by v.key"); return dbInstance.getCurrentEntityManager().createQuery(sb.toString(), RepositoryEntryUpgrade.class) .setFirstResult(firstResult) .setMaxResults(maxResults) .getResultList(); } private RepositoryEntryUpgrade lookupRepositoryEntry(OLATResource ores) { StringBuilder sb = new StringBuilder(); sb.append("select v from ").append(RepositoryEntryUpgrade.class.getName()).append(" v ") .append(" inner join fetch v.olatResource as ores") .append(" left join fetch v.ownerGroup as ownerGroup") .append(" left join fetch v.participantGroup as participantGroup") .append(" left join fetch v.tutorGroup as tutorGroup") .append(" where ores.key = :oreskey"); List<RepositoryEntryUpgrade> result = dbInstance.getCurrentEntityManager() .createQuery(sb.toString(), RepositoryEntryUpgrade.class) .setParameter("oreskey", ores.getKey()) .getResultList(); if(result.size() > 0) { return result.get(0); } return null; } }
def sum_prime_numbers(n): if n <= 1: return 0 prime_sum = 0 for i in range(2, n): is_prime = True for j in range(2, i): if i % j == 0: is_prime = False break if is_prime: prime_sum += i return prime_sum
<filename>zeus-starter/src/main/java/com/iterlife/zeus/starter/annotation/IterLife.java package com.iterlife.zeus.starter.annotation; import java.lang.annotation.*; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; /** * @author lujie * @Desc 自定义IterBean注解 * @Version 1.0.0 * @since 2020-05-30 20:15 */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Component public @interface IterLife { String id() default "iterlife-id"; String name() default "iterlife-name"; String value() default "iterlife-value"; String desc() default "iterlife-desc"; }
// 'ignore' method. This method does nothing, but can be called // to document the reason why the exception can be ignored. public static void ignore(Throwable e, String message) { }
<reponame>dongdong1018645785/touch-air-mall package com.touch.air.mall.seckill.vo; import lombok.Data; import java.math.BigDecimal; /** * @author: bin.wang * @date: 2021/3/6 16:03 */ @Data public class SecKillRelationVo { private Long id; /** * 活动id */ private Long promotionId; /** * 活动场次id */ private Long promotionSessionId; /** * 商品id */ private Long skuId; /** * 秒杀价格 */ private BigDecimal seckillPrice; /** * 秒杀总量 */ private BigDecimal seckillCount; /** * 每人限购数量 */ private BigDecimal seckillLimit; /** * 排序 */ private Integer seckillSort; }
#!/bin/bash setup_git_hooks() { chmod u+x ./scripts/commit-msg ln -s ../../scripts/commit-msg .git/hooks/commit-msg } setup_git_hooks
<reponame>FourLeafTec/RTSPtoWebRTC package main import ( "crypto/rand" "encoding/json" "fmt" "io/ioutil" "log" "sync" "time" "github.com/deepch/vdk/codec/h264parser" "github.com/deepch/vdk/av" ) //Config global var Config = loadConfig() //ConfigST struct type ConfigST struct { mutex sync.RWMutex Server ServerST `json:"server"` Streams map[string]StreamST `json:"streams"` } //ServerST struct type ServerST struct { HTTPPort string `json:"http_port"` ICEServers []string `json:"ice_servers"` WebRTCPortMin uint16 `json:"webrtc_port_min"` WebRTCPortMax uint16 `json:"webrtc_port_max"` } //StreamST struct type StreamST struct { URL string `json:"url"` Status bool `json:"status"` OnDemand bool `json:"on_demand"` DisableAudio bool `json:"disable_audio"` Debug bool `json:"debug"` RunLock bool `json:"-"` Codecs []av.CodecData Cl map[string]viewer } type viewer struct { c chan av.Packet } func (element *ConfigST) RunIFNotRun(uuid string) { element.mutex.Lock() defer element.mutex.Unlock() if tmp, ok := element.Streams[uuid]; ok { if tmp.OnDemand && !tmp.RunLock { tmp.RunLock = true element.Streams[uuid] = tmp go RTSPWorkerLoop(uuid, tmp.URL, tmp.OnDemand, tmp.DisableAudio, tmp.Debug) } } } func (element *ConfigST) RunUnlock(uuid string) { element.mutex.Lock() defer element.mutex.Unlock() if tmp, ok := element.Streams[uuid]; ok { if tmp.OnDemand && tmp.RunLock { tmp.RunLock = false element.Streams[uuid] = tmp } } } func (element *ConfigST) HasViewer(uuid string) bool { element.mutex.Lock() defer element.mutex.Unlock() if tmp, ok := element.Streams[uuid]; ok && len(tmp.Cl) > 0 { return true } return false } func (element *ConfigST) GetICEServers() []string { element.mutex.Lock() defer element.mutex.Unlock() return element.Server.ICEServers } func (element *ConfigST) GetWebRTCPortMin() uint16 { element.mutex.Lock() defer element.mutex.Unlock() return element.Server.WebRTCPortMin } func (element *ConfigST) GetWebRTCPortMax() uint16 { element.mutex.Lock() defer element.mutex.Unlock() return element.Server.WebRTCPortMax } func loadConfig() *ConfigST { var tmp ConfigST data, err := ioutil.ReadFile("config.json") if err != nil { log.Fatalln(err) } err = json.Unmarshal(data, &tmp) if err != nil { log.Fatalln(err) } for i, v := range tmp.Streams { v.Cl = make(map[string]viewer) tmp.Streams[i] = v } return &tmp } func (element *ConfigST) cast(uuid string, pck av.Packet) { element.mutex.Lock() defer element.mutex.Unlock() for _, v := range element.Streams[uuid].Cl { if len(v.c) < cap(v.c) { v.c <- pck } } } func (element *ConfigST) ext(suuid string) bool { element.mutex.Lock() defer element.mutex.Unlock() _, ok := element.Streams[suuid] return ok } func (element *ConfigST) coAd(suuid string, codecs []av.CodecData) { element.mutex.Lock() defer element.mutex.Unlock() t := element.Streams[suuid] t.Codecs = codecs element.Streams[suuid] = t } func (element *ConfigST) coGe(suuid string) []av.CodecData { for i := 0; i < 100; i++ { element.mutex.RLock() tmp, ok := element.Streams[suuid] element.mutex.RUnlock() if !ok { return nil } if tmp.Codecs != nil { //TODO Delete test for _, codec := range tmp.Codecs { if codec.Type() == av.H264 { codecVideo := codec.(h264parser.CodecData) if codecVideo.SPS() != nil && codecVideo.PPS() != nil && len(codecVideo.SPS()) > 0 && len(codecVideo.PPS()) > 0 { //ok //log.Println("Ok Video Ready to play") } else { //video codec not ok log.Println("Bad Video Codec SPS or PPS Wait") time.Sleep(50 * time.Millisecond) continue } } } return tmp.Codecs } time.Sleep(50 * time.Millisecond) } return nil } func (element *ConfigST) clAd(suuid string) (string, chan av.Packet) { element.mutex.Lock() defer element.mutex.Unlock() cuuid := pseudoUUID() ch := make(chan av.Packet, 100) element.Streams[suuid].Cl[cuuid] = viewer{c: ch} return cuuid, ch } func (element *ConfigST) list() (string, []string) { element.mutex.Lock() defer element.mutex.Unlock() var res []string var fist string for k := range element.Streams { if fist == "" { fist = k } res = append(res, k) } return fist, res } func (element *ConfigST) clDe(suuid, cuuid string) { element.mutex.Lock() defer element.mutex.Unlock() delete(element.Streams[suuid].Cl, cuuid) } func pseudoUUID() (uuid string) { b := make([]byte, 16) _, err := rand.Read(b) if err != nil { fmt.Println("Error: ", err) return } uuid = fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) return }
require 'spec_helper' describe 'newrelic::agent::php', :type => :class do let(:facts) do { 'os' => { 'family' => 'RedHat', 'name' => 'CentOS', 'release' => { 'major' => '7' } }, 'operatingsystem' => 'Centos', 'path' => '/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/puppetlabs/bin:/opt/puppetlabs/puppet/bin:/root/.local/bin:/root/bin' } end let(:params) do { :license_key => '1234567890qwerty', :conf_dir => '/opt/rh/php54/root/etc/php.d', } end it { is_expected.to compile } it { should contain_class('newrelic::params') } it { should contain_class('newrelic::repo::legacy') } it { should contain_package('newrelic-php5') } it { should contain_package('php-cli') } it { should contain_file('/etc/newrelic/newrelic.cfg') } it { should contain_file('/opt/rh/php54/root/etc/php.d/newrelic.ini') } it { should contain_exec('newrelic install') } it { should contain_exec('newrelic_kill') } context 'startup_mode => external' do let(:params) do super().merge({ 'startup_mode' => 'external' }) end it { should contain_service('newrelic-daemon') } end end
<filename>app/workers/list_sync/error_handling.rb module ListSync module ErrorHandling extend ActiveSupport::Concern def capture_sync_errors(linked_account, pending_logs) yield rescue ListSync::NotFoundError error! pending_logs, 'No equivalent' rescue ListSync::AuthenticationError linked_account.update!(sync_to: false, disabled_reason: 'Login failed') error! pending_logs, 'Login failed' rescue ListSync::RemoteError => e error! pending_logs, e.message raise rescue StandardError error! pending_logs, 'Unknown Error' raise end private def error!(logs, message) changes = { error_message: message, sync_status: :error } logs.each { |log| log.update!(changes) } end end end
import sanitizeHex from '../sanitizeHex'; import { HEX_BLACK } from './data/colors'; /** * Sanitize Hex String */ describe('sanitizeHex', () => { test('sanitizeHex - clean input', () => { const validHex = '#ffffff'; const sanitizedHex = sanitizeHex(validHex); expect(sanitizedHex).toStrictEqual(validHex); }); test('sanitizeHex - empty', () => { const empty = ''; const sanitizedHex = sanitizeHex(empty); expect(sanitizedHex).toStrictEqual(HEX_BLACK); }); test('sanitizeHex - 1 character', () => { const one = '1'; const sanitizedHex = sanitizeHex(one); expect(sanitizedHex).toStrictEqual('#111111'); }); test('sanitizeHex - 2 characters', () => { const two = '12'; const sanitizedHex = sanitizeHex(two); expect(sanitizedHex).toStrictEqual('#111222'); }); test('sanitizeHex - 3 characters', () => { const three = '123'; const sanitizedHex = sanitizeHex(three); expect(sanitizedHex).toStrictEqual('#112233'); }); test('sanitizeHex - 4 characters', () => { const four = '1234'; const sanitizedHex = sanitizeHex(four); expect(sanitizedHex).toStrictEqual('#112233'); }); test('sanitizeHex - > 6 characters', () => { const tooLong = '#cedefffffffffe123'; const sanitizedHex = sanitizeHex(tooLong); expect(sanitizedHex).toStrictEqual('#cedeff'); }); test('sanitizeHex - invalid chars', () => { const invalidAtStart = 'Z`*(;3#%^21|/"32&1'; const sanitizedHex = sanitizeHex(invalidAtStart); expect(sanitizedHex).toStrictEqual('#321321'); }); });
def delete(node, key): if not node: return None # If key to be deleted is smaller # than the root's key, then it lies # in left subtree if key < node.key: node.left = delete(node.left, key) # If the key to be deleted is greater # than the root's key, then it lies # in right subtree elif key > node.key: node.right = delete(node.right, key) # If key is same as root's key, then # this is the node to be deleted else: # Node with only one child or no child if node.left is None : temp = node.right node = None return temp elif node.right is None : temp = node.left node = None return temp # Node with two children: Get the inorder # successor (smallest in the right subtree) temp = minValueNode(node.right) # Copy the inorder successor's content # to this node node.key = temp.key # Delete the inorder successor node.right = delete(node.right, temp.key) return node
package vcoclient type FirewallData struct { FirewallEnabled bool `json:"firewall_enabled"` InboundLoggingEnabled *bool `json:"inboundLoggingEnabled,omitempty"` StatefulFirewallEnabled *bool `json:"stateful_firewall_enabled,omitempty"` FirewallLoggingEnabled *bool `json:"firewall_logging_enabled,omitempty"` SyslogForwarding *bool `json:"syslog_forwarding,omitempty"` Inbound []FirewallInboundRule `json:"inbound,omitempty"` StatefulFirewallSettings *FirewallStatefulFirewallSettings `json:"statefulFirewallSettings,omitempty"` NetworkProtectionSettings *FirewallNetworkProtectionSettings `json:"networkProtectionSettings,omitempty"` Segments []FirewallSegment `json:"segments,omitempty"` Services *FirewallServices `json:"services,omitempty"` }
/* * Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.effect; import javafx.beans.property.DoubleProperty; import javafx.beans.property.DoublePropertyBase; /** * An effect that renders a reflected version of the input below the * actual input content. * <p> * Note that the reflection of a {@code Node} with a {@code Reflection} * effect installed will not respond to mouse events or the containment * methods on the {@code Node}. * * <p> * Example: * <pre>{@code * Reflection reflection = new Reflection(); * reflection.setFraction(0.7); * * Text text = new Text(); * text.setX(10.0); * text.setY(50.0); * text.setCache(true); * text.setText("Reflections on JavaFX..."); * text.setFill(Color.web("0x3b596d")); * text.setFont(Font.font(null, FontWeight.BOLD, 40)); * text.setEffect(reflection); * }</pre> * <p> The code above produces the following: </p> * <p> * <img src="doc-files/reflection.png" alt="The visual effect of Reflection on text"> * </p> * @since JavaFX 2.0 */ public class Reflection implements Effect { /** * Creates a new instance of Reflection with default parameters. */ public Reflection() {} /** * Creates a new instance of Reflection with the specified topOffset, fraction, * topOpacity and bottomOpacity. * @param topOffset the distance between the bottom of the input and the top of the reflection * @param fraction the fraction of the input that is visible in the reflection * @param topOpacity the opacity of the reflection at its top extreme * @param bottomOpacity the opacity of the reflection at its bottom extreme * @since JavaFX 2.1 */ public Reflection(double topOffset, double fraction, double topOpacity, double bottomOpacity) { setBottomOpacity(bottomOpacity); setTopOffset(topOffset); setTopOpacity(topOpacity); setFraction(fraction); } /*@Override com.sun.scenario.effect.Reflection createPeer() { return new com.sun.scenario.effect.Reflection(); };*/ /** * The input for this {@code Effect}. * If set to {@code null}, or left unspecified, a graphical image of * the {@code Node} to which the {@code Effect} is attached will be * used as the input. * @defaultValue null */ /*private ObjectProperty<Effect> input; public final void setInput(Effect value) { inputProperty().set(value); } public final Effect getInput() { return input == null ? null : input.get(); } public final ObjectProperty<Effect> inputProperty() { if (input == null) { input = new EffectInputProperty("input"); } return input; }*/ /*@Override boolean checkChainContains(Effect e) { Effect localInput = getInput(); if (localInput == null) return false; if (localInput == e) return true; return localInput.checkChainContains(e); }*/ /** * The top offset adjustment, which is the distance between the * bottom of the input and the top of the reflection. * <pre> * Min: n/a * Max: n/a * Default: 0.0 * Identity: 0.0 * </pre> * @defaultValue 0.0 */ private DoubleProperty topOffset; public final void setTopOffset(double value) { topOffsetProperty().set(value); } public final double getTopOffset() { return topOffset == null ? 0 : topOffset.get(); } public final DoubleProperty topOffsetProperty() { if (topOffset == null) { topOffset = new DoublePropertyBase() { /*@Override public void invalidated() { markDirty(EffectDirtyBits.EFFECT_DIRTY); effectBoundsChanged(); }*/ @Override public Object getBean() { return Reflection.this; } @Override public String getName() { return "topOffset"; } }; } return topOffset; } /** * The top opacity value, which is the opacity of the reflection * at its top extreme. * <pre> * Min: 0.0 * Max: 1.0 * Default: 0.5 * Identity: 1.0 * </pre> * @defaultValue 0.5 */ private DoubleProperty topOpacity; public final void setTopOpacity(double value) { topOpacityProperty().set(value); } public final double getTopOpacity() { return topOpacity == null ? 0.5 : topOpacity.get(); } public final DoubleProperty topOpacityProperty() { if (topOpacity == null) { topOpacity = new DoublePropertyBase(0.5) { /*@Override public void invalidated() { markDirty(EffectDirtyBits.EFFECT_DIRTY); }*/ @Override public Object getBean() { return Reflection.this; } @Override public String getName() { return "topOpacity"; } }; } return topOpacity; } /** * The bottom opacity value, which is the opacity of the reflection * at its bottom extreme. * <pre> * Min: 0.0 * Max: 1.0 * Default: 0.0 * Identity: 1.0 * </pre> * @defaultValue 0.0 */ private DoubleProperty bottomOpacity; public final void setBottomOpacity(double value) { bottomOpacityProperty().set(value); } public final double getBottomOpacity() { return bottomOpacity == null ? 0 : bottomOpacity.get(); } public final DoubleProperty bottomOpacityProperty() { if (bottomOpacity == null) { bottomOpacity = new DoublePropertyBase() { /*@Override public void invalidated() { markDirty(EffectDirtyBits.EFFECT_DIRTY); }*/ @Override public Object getBean() { return Reflection.this; } @Override public String getName() { return "bottomOpacity"; } }; } return bottomOpacity; } /** * The fraction of the input that is visible in the reflection. * For example, a value of 0.5 means that only the bottom half of the * input will be visible in the reflection. * <pre> * Min: 0.0 * Max: 1.0 * Default: 0.75 * Identity: 1.0 * </pre> * @defaultValue 0.75 */ private DoubleProperty fraction; public final void setFraction(double value) { fractionProperty().set(value); } public final double getFraction() { return fraction == null ? 0.75 : fraction.get(); } public final DoubleProperty fractionProperty() { if (fraction == null) { fraction = new DoublePropertyBase(0.75) { /*@Override public void invalidated() { markDirty(EffectDirtyBits.EFFECT_DIRTY); effectBoundsChanged(); }*/ @Override public Object getBean() { return Reflection.this; } @Override public String getName() { return "fraction"; } }; } return fraction; } /*private float getClampedFraction() { return (float)Utils.clamp(0, getFraction(), 1); } private float getClampedBottomOpacity() { return (float)Utils.clamp(0, getBottomOpacity(), 1); } private float getClampedTopOpacity() { return (float)Utils.clamp(0, getTopOpacity(), 1); } @Override void update() { Effect localInput = getInput(); if (localInput != null) { localInput.sync(); } com.sun.scenario.effect.Reflection peer = (com.sun.scenario.effect.Reflection) getPeer(); peer.setInput(localInput == null ? null : localInput.getPeer()); peer.setFraction(getClampedFraction()); peer.setTopOffset((float)getTopOffset()); peer.setBottomOpacity(getClampedBottomOpacity()); peer.setTopOpacity(getClampedTopOpacity()); } @Override BaseBounds getBounds(BaseBounds bounds, BaseTransform tx, Node node, BoundsAccessor boundsAccessor) { bounds = getInputBounds(bounds, BaseTransform.IDENTITY_TRANSFORM, node, boundsAccessor, getInput()); bounds.roundOut(); float x1 = bounds.getMinX(); float y1 = bounds.getMaxY() + (float)getTopOffset(); float z1 = bounds.getMinZ(); float x2 = bounds.getMaxX(); float y2 = y1 + (getClampedFraction() * bounds.getHeight()); float z2 = bounds.getMaxZ(); BaseBounds ret = BaseBounds.getInstance(x1, y1, z1, x2, y2, z2); ret = ret.deriveWithUnion(bounds); return transformBounds(tx, ret); } @Override Effect copy() { Reflection ref = new Reflection(this.getTopOffset(), this.getFraction(), this.getTopOpacity(), this.getBottomOpacity()); ref.setInput(ref.getInput()); return ref; }*/ }
#! /bin/bash # --- Fixed parameters --- DATASET_DIR="./dataset" LIB_DIR="/work/lib" mkdir -p ${DATASET_DIR} # --- Prepare dataset --- # * MNIST # * CIFAR-10 dataset_dir="${DATASET_DIR}/mnist" if [ ! -e ${dataset_dir} ]; then mkdir -p ${dataset_dir} cd ${dataset_dir} wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz & wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz & wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz & wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz wait gunzip train-images-idx3-ubyte.gz & gunzip train-labels-idx1-ubyte.gz & gunzip t10k-images-idx3-ubyte.gz & gunzip t10k-labels-idx1-ubyte.gz & wait cd ../.. fi dataset_dir="${DATASET_DIR}/cifar-10-batches-py" if [ ! -e ${DATASET_DIR}/cifar-10-python.tar.gz ]; then cd ${DATASET_DIR} wget https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz tar -zxf cifar-10-python.tar.gz cd .. fi # --- Training --- # * OUTPUT_DIRで指定のトップディレクトリが存在する場合は学習しない echo `pwd` OUTPUT_DIR="./output" DATA_TYPE_LIST=("CIFAR-10") MODEL_TYPE_LIST=("SimpleResNet") DATA_AUG_LIST=("3,0.1,0.1,True") DATA_AUG_NAME_LIST=("DA3") # DA0: 10,0.2,0.2,True # DA1: 5,0.2,0.2,True # DA2: 3,0.2,0.2,True # DA3: 3,0.1,0.1,True OPTIMIZER_LIST=("momentum") BATCH_SIZE_LIST=("32") INITIALIZER_LIST=("glorot_normal" "glorot_uniform" "he_normal" "he_uniform") if [ ! -e ${OUTPUT_DIR} ]; then for DATA_TYPE in ${DATA_TYPE_LIST[@]} do if [ ${DATA_TYPE} = "MNIST" ]; then dataset_dir="${DATASET_DIR}/mnist" elif [ ${DATA_TYPE} = "CIFAR-10" ]; then dataset_dir="${DATASET_DIR}/cifar-10-batches-py" else echo "[ERROR] Unknown DATA_TYPE; ${DATA_TYPE}" exit fi for MODEL_TYPE in ${MODEL_TYPE_LIST[@]} do for _data_aug_idx in `seq ${#DATA_AUG_LIST[@]}` do data_aug_idx=`expr ${_data_aug_idx} - 1` DATA_AUG=${DATA_AUG_LIST[${data_aug_idx}]} DATA_AUG_NAME=${DATA_AUG_NAME_LIST[${data_aug_idx}]} for OPTIMIZER in ${OPTIMIZER_LIST[@]} do for BATCH_SIZE in ${BATCH_SIZE_LIST[@]} do for INITIALIZER in ${INITIALIZER_LIST[@]} do echo "[Training Conditions]" echo " * MODEL_TYPE=${MODEL_TYPE}" echo " * DATA_TYPE=${DATA_TYPE}" echo " * DATA_AUG=${DATA_AUG}" echo " * DATA_AUG_NAME=${DATA_AUG_NAME}" echo " * OPTIMIZER=${OPTIMIZER}" echo " * BATCH_SIZE=${BATCH_SIZE}" echo " * INITIALIZER=${INITIALIZER}" model_dir="${OUTPUT_DIR}/model/${MODEL_TYPE}_${DATA_TYPE}_${DATA_AUG_NAME}_OPT-${OPTIMIZER}_batch${BATCH_SIZE}_${INITIALIZER}" mkdir -p ${model_dir} python3 main.py --data_type ${DATA_TYPE} \ --dataset_dir ${dataset_dir} \ --model_type ${MODEL_TYPE} \ --data_augmentation ${DATA_AUG} \ --optimizer ${OPTIMIZER} \ --batch_size ${BATCH_SIZE} \ --initializer ${INITIALIZER} \ --result_dir ${model_dir} done done done done done done fi # --- 出力するグラフのサイズ[inch] --- fig_size="15,5" # --- モデル定義 --- source ./model.list # --- Compare models(ALL) --- metrics_list=\ "${OUTPUT_DIR}/model/${SimpleResNet_CIFAR10_DA3_OPTmomentum}/metrics/metrics.csv,"\ "${OUTPUT_DIR}/model/${SimpleResNet_CIFAR10_DA3_OPTmomentum_glorot_normal}/metrics/metrics.csv,"\ "${OUTPUT_DIR}/model/${SimpleResNet_CIFAR10_DA3_OPTmomentum_he_uniform}/metrics/metrics.csv,"\ "${OUTPUT_DIR}/model/${SimpleResNet_CIFAR10_DA3_OPTmomentum_he_normal}/metrics/metrics.csv" metrics_names=\ "${SimpleResNet_CIFAR10_DA3_OPTmomentum},"\ "${SimpleResNet_CIFAR10_DA3_OPTmomentum_glorot_normal},"\ "${SimpleResNet_CIFAR10_DA3_OPTmomentum_he_uniform},"\ "${SimpleResNet_CIFAR10_DA3_OPTmomentum_he_normal}" output_dir="${OUTPUT_DIR}/metrics_graph" python3 tools/create_metrics_graph/create_metrics_graph.py --metrics_list ${metrics_list} --metrics_names ${metrics_names} --fig_size ${fig_size} --output_dir ${output_dir}
import React from 'react'; import { Link } from 'gatsby' import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import select from '../components/utils' const DropDownMenu = (props) => { const switches = props.switches; const links = props.links; const sel = select(props.langKey); return ( <div className="navbar-item has-dropdown is-hoverable"> <Link className="navbar-link" to={props.base}> <FormattedMessage id={props.baseName} /> </Link> <div className="navbar-dropdown is-hidden-mobile is-boxed"> {switches &&( switches.map(( message ) => ( <Link className="navbar-item" key={message} to={links[message][sel]}> <FormattedMessage id={message} /> </Link> )))} </div> </div> ); }; DropDownMenu.propTypes = { keys: PropTypes.array, links: PropTypes.object, switches: PropTypes.array, langKey: PropTypes.string, baseName: PropTypes.string, }; export default DropDownMenu;
#!/bin/bash export PHP_HOME=${IROOT}/php-5.5.17 export COMPOSER_HOME=${IROOT}/php-composer fw_depends php nginx composer ${PHP_HOME}/bin/php ${COMPOSER_HOME}/composer.phar install \ --no-interaction --working-dir ${TROOT} \ --no-progress --optimize-autoloader php artisan optimize --force
#!/bin/bash export LANG=zh_CN.UTF-8 export LANGUAGE=zh_CN:zh:en_US:en export PATH=/usr/local/miniconda3/bin/:$PATH python /path/to/mmdetection/tools/train.py ./config/tp_r50_3stages_enlarge.py --gpus 8
<reponame>nightskylark/DevExtreme "use strict"; var treeListCore = require("./ui.tree_list.core"), contextMenuModule = require("../grid_core/ui.grid_core.context_menu"); treeListCore.registerModule("contextMenu", contextMenuModule);
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.math.interpolation; import java.util.List; import org.apache.commons.lang.Validate; import com.opengamma.analytics.math.function.Function1D; import com.opengamma.analytics.math.interpolation.data.InterpolatorNDDataBundle; import com.opengamma.analytics.math.interpolation.data.KrigingInterpolatorDataBundle; import com.opengamma.util.tuple.Pair; /** * */ public class KrigingInterpolatorND extends InterpolatorND { private final double _beta; public KrigingInterpolatorND(final double beta) { Validate.isTrue(beta >= 1 && beta < 2, "Beta was not in acceptable range (1 <= beta < 2"); _beta = beta; } @Override public Double interpolate(final InterpolatorNDDataBundle data, final double[] x) { validateInput(data, x); Validate.isTrue(data instanceof KrigingInterpolatorDataBundle, "KriginInterpolatorND needs a KriginInterpolatorDataBundle"); KrigingInterpolatorDataBundle krigingData = (KrigingInterpolatorDataBundle) data; final List<Pair<double[], Double>> rawData = krigingData.getData(); final Function1D<Double, Double> variogram = krigingData.getVariogram(); final double[] w = krigingData.getWeights(); final int n = rawData.size(); double sum = 0.0; double r; for (int i = 0; i < n; i++) { r = DistanceCalculator.getDistance(x, rawData.get(i).getFirst()); sum += variogram.evaluate(r) * w[i]; } sum += w[n]; return sum; } @Override public KrigingInterpolatorDataBundle getDataBundle(final double[] x, final double[] y, final double[] z, final double[] values) { return new KrigingInterpolatorDataBundle(transformData(x, y, z, values), _beta); } @Override public KrigingInterpolatorDataBundle getDataBundle(final List<Pair<double[], Double>> data) { return new KrigingInterpolatorDataBundle(data, _beta); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(_beta); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KrigingInterpolatorND other = (KrigingInterpolatorND) obj; return Double.doubleToLongBits(_beta) == Double.doubleToLongBits(other._beta); } }
<gh_stars>0 const process = require("process") const notifier = require('node-notifier') const { exec } = require("child_process"); console.log(process) console.log(exec) const ONE_SECOND = 1000 const ONE_MINUTE = 60 * ONE_SECOND const TEN_MINUTE = 10 * ONE_MINUTE var VS = 0 function checkvs() { exec("tasklist", (error, stdout, stderr) => { if (error) { console.log(`error: ${error.message}`); return; } if (stderr) { console.log(`stderr: ${stderr}`); return; } //console.log(`stdout: ${stdout}`); if (stdout.indexOf("devenv.exe") > 0) { //console.log("VS is running.") VS = 1 } else if (stdout.indexOf("devenv.exe") < 0 && VS == 1) { VS = 0 //console.log("VS has stopped running.") //console.log("Saving projects...") //git save setTimeout(() => { console.log("Projects saved!") }, ONE_SECOND) } else if (stdout.indexOf("devenv.exe") < 0) { //console.log("VS is not running.") VS = 0 } }); } setInterval(checkvs, ONE_SECOND) /* const NotificationCenter = require('node-notifier').NotificationCenter; var notifier = new NotificationCenter({ withFallback: false, // Use Growl Fallback if <= 10.8 customPath: undefined // Relative/Absolute path to binary if you want to use your own fork of terminal-notifier }); notifier.notify( { title: undefined, subtitle: undefined, message: undefined, sound: false, // Case Sensitive string for location of sound file, or use one of macOS' native sounds (see below) icon: 'Terminal Icon', // Absolute Path to Triggering Icon contentImage: undefined, // Absolute Path to Attached Image (Content Image) open: undefined, // URL to open on Click wait: false, // Wait for User Action against Notification or times out. Same as timeout = 5 seconds // New in latest version. See `example/macInput.js` for usage timeout: 5, // Takes precedence over wait if both are defined. closeLabel: undefined, // String. Label for cancel button actions: undefined, // String | Array<String>. Action label or list of labels in case of dropdown dropdownLabel: undefined, // String. Label to be used if multiple actions reply: false // Boolean. If notification should take input. Value passed as third argument in callback and event emitter. }, function (error, response, metadata) { console.log(response, metadata); } ); */ //process.on("beforeExit", (stream) => { //})
#include <stdio.h> int main() { int result = 5 * (3 + 4) - 9; printf("Result: %d\n", result); return 0; }
# OSX-only stuff. Abort if not OSX. is_osx || return 1 # Trim new lines and copy to clipboard alias c="tr -d '\n' | pbcopy" # Make 'less' more. [[ "$(type -P lesspipe.sh)" ]] && eval "$(lesspipe.sh)" # Start ScreenSaver. This will lock the screen if locking is enabled. alias ss="open /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app" # Iterm 2 shell integration test -e "${HOME}/.iterm2_shell_integration.bash" && source "${HOME}/.iterm2_shell_integration.bash" # Create a new Parallels VM from template, replacing the existing one. function vm_template() { local name="$@" local basename="$(basename "$name" ".zip")" local dest_dir="$HOME/Documents/Parallels" local dest="$dest_dir/$basename" local src_dir="$dest_dir/Templates" local src="$src_dir/$name" if [[ ! "$name" || ! -e "$src" ]]; then echo "You must specify a valid VM template from this list:"; shopt -s nullglob for f in "$src_dir"/*.pvm "$src_dir"/*.pvm.zip; do echo " * $(basename "$f")" done shopt -u nullglob return 1 fi if [[ -e "$dest" ]]; then echo "Deleting old VM" rm -rf "$dest" fi echo "Restoring VM template" if [[ "$name" == "$basename" ]]; then cp -R "$src" "$dest" else unzip -q "$src" -d "$dest_dir" && rm -rf "$dest_dir/__MACOSX" fi && \ echo "Starting VM" && \ open -g "$dest" } # Bus Pirate as FTDI Cable # https://blog.zencoffee.org/2011/07/bus-pirate-as-ftdi-cable/ # http://dangerousprototypes.com/blog/2009/08/12/bus-pirate-connecting-with-mac-osx/ buspirate_device=usbserial-A105BQH0 buspirate_baud=115200 function buspirate_init() { cat <<EOF Ensure Bus Pirate is connected to the FTDI 6-pin header like so: Pin 1 – Brown (GND) Pin 2 – NO WIRE Pin 3 – Orange (+5V) Pin 4 – Grey (MOSI) Pin 5 – Black (MISO) Pin 6 – Purple (CLK) When ready, press Enter to connect or Ctrl-C to abort. EOF read echo "Connecting to Bus Pirate..." screen -d -m -S buspirate /dev/tty.$buspirate_device $buspirate_baud sleep 1 local commands=("m3\r" "9\r" "1\r" "1\r" "1\r" "2\r" "i\r" "(3)\r" "y") for c in "${commands[@]}"; do screen -S buspirate -p 0 -X stuff $(printf "$c") sleep 0.5 done sleep 1 screen -X -S buspirate quit buspirate_log } function buspirate_log() { echo "Logging Bus Pirate output. Press Ctrl-C to abort." local device=/dev/cu.$buspirate_device stty -f $device $buspirate_baud & cat $device } # Export Localization.prefPane text substitution rules. function txt_sub_backup() { local prefs=~/Library/Preferences/.GlobalPreferences.plist local backup=$DOTFILES/conf/osx/NSUserReplacementItems.plist /usr/libexec/PlistBuddy -x -c "Print NSUserReplacementItems" "$prefs" > "$backup" && echo "File ~${backup#$HOME} written." } # Import Localization.prefPane text substitution rules. function txt_sub_restore() { local prefs=~/Library/Preferences/.GlobalPreferences.plist local backup=$DOTFILES/conf/osx/NSUserReplacementItems.plist if [[ ! -e "$backup" ]]; then echo "Error: file ~${backup#$HOME} does not exist!" return 1 fi cmds=( "Delete NSUserReplacementItems" "Add NSUserReplacementItems array" "Merge '$backup' NSUserReplacementItems" ) for cmd in "${cmds[@]}"; do /usr/libexec/PlistBuddy -c "$cmd" "$prefs"; done }
#!/usr/bin/env bats #-*- shell-script -*- # This is test script for the lab. There several different ways the # lab might be run -- starter code vs solution, local vs. remote, # devel vs. on the autograder. This file can test that they are all # functioning properly. # # It's written in bats (https://github.com/bats-core/bats-core) # #
package pl.allegro.tech.opel; enum Operator { PLUS, MINUS, MULTIPLY, DIV, GT, GTE, LT, LTE, EQUAL, NOT_EQUAL, AND, OR; public OpelNode createNode(OpelNode left, OpelNode right, ImplicitConversion implicitConversion) { switch (this) { case PLUS: return new SumOperatorExpressionNode(left, right, implicitConversion); case MINUS: return new MinusOperatorExpressionNode(left, right, implicitConversion); case MULTIPLY: return new MultiplyOperatorExpressionNode(left, right, implicitConversion); case DIV: return new DivideOperatorExpressionNode(left, right, implicitConversion); case GT: return CompareOperatorExpressionNode.greaterThen(left, right, implicitConversion); case GTE: return CompareOperatorExpressionNode.greaterOrEqual(left, right, implicitConversion); case LT: return CompareOperatorExpressionNode.lowerThen(left, right, implicitConversion); case LTE: return CompareOperatorExpressionNode.lowerOrEqual(left, right, implicitConversion); case EQUAL: return EqualOperatorExpressionNode.equalityOperator(left, right, implicitConversion); case NOT_EQUAL: return EqualOperatorExpressionNode.inequalityOperator(left, right, implicitConversion); case AND: return LogicalOperatorExpressionNode.andOperator(left, right, implicitConversion); case OR: return LogicalOperatorExpressionNode.orOperator(left, right, implicitConversion); } // Can only happen when not all operators are listed above throw new UnsupportedOperationException("Unsupported operator " + this); } }
<gh_stars>0 "use strict"; function objectToParamString(object) { var joinedParams = Object.keys(object).map(function (key) { if (key == 'orderBy') { return key + "=\"" + object[key] + "\""; } else { return key + "=" + object[key]; } }).join('&'); return joinedParams === '' ? '' : "?" + joinedParams; } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = objectToParamString;
// Function to find the largest of three numbers int largestOfThree(int num1, int num2, int num3) { int largest = 0; // Find largest number if (num1 > num2) largest = num1; else largest = num2; if (num3 > largest) largest = num3; return largest; }
SELECT category, MAX(price) FROM products GROUP BY category ORDER BY MAX(price) DESC LIMIT 5;
<div class="container"> <div class="box1">Content for box 1</div> <div class="box2">Content for box 2</div> <div class="box3">Content for box 3</div> </div> <style> .container { display: flex; } .box1 { flex: 1; background: #f4f4f4; } .box2 { flex: 2; background: #ccc; } .box3 { flex: 3; background: #eee; } </style>
#!/bin/sh # # Run a nerves_system_x86_64-based image in QEMU # # Usage: # run-qemu.sh [Path to .img file] # set -e IMAGE="$1" DEFAULT_IMAGE="example.img" help() { echo echo "Usage:" echo " run-qemu.sh [Path to .img file]" exit 1 } [ -n "$IMAGE" ] || IMAGE="$DEFAULT_IMAGE" [ -f "$IMAGE" ] || (echo "Error: can't find '$IMAGE'"; help) echo "Starting QEMU..." qemu-system-x86_64 \ -m 1G \ -drive file="$IMAGE",format=raw \ -device e1000,netdev=user.0 \ -netdev user,id=user.0,hostfwd=tcp::8989-:8989
#!/bin/bash sudo kill -9 $(ps -ef | grep AccXSim.jar | grep -v grep | awk '{print $2}')
<reponame>uw-dims/tupelo /** * Copyright © 2015, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of the University of Washington nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF * WASHINGTON BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uw.apl.tupelo.http.server; import java.util.regex.Pattern; import com.google.gson.JsonElement; import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonPrimitive; import edu.uw.apl.tupelo.model.ManagedDiskDescriptor; import edu.uw.apl.tupelo.model.Session; public class Constants { // A ManagedDiskDescriptor (diskid,session) encoded in a url path info static public final Pattern MDDPIREGEX = Pattern.compile ( "(" + ManagedDiskDescriptor.DISKIDREGEX.pattern() + ")/" + "(" + Session.SHORTREGEX.pattern() + ")" ); static public final JsonSerializer<Session> SESSIONSERIALIZER = new JsonSerializer<Session>() { // for Json output of Session objects, we just use their .format method... @Override public JsonElement serialize( Session src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive( src.format() ); } }; } // eof
require 'puppet/configurer' require 'set' require 'pp' Puppet::Type.type(:refacter).provide(:ruby) do desc <<-END This provider handles rerunning facter to reload all the known facts for the refacter type. END def initialize(hash) debug 'init refacter, save Facter values' @facts = Facter.to_hash super end # actually perform the check and (optional) reload def run Puppet.debug('reloading facter to see if facts changed') pattern = resource[:pattern] pnode = Puppet[:node_name_value] pconf = Puppet::Configurer.new fact_diff_hash = reload_facts(pattern, pconf, pnode) if fact_diff_hash.empty? Puppet.debug('facts stayed the same after reloading facter') return else Puppet.notice('facts changed after reloading facter') end @refreshed = true Puppet.alert('reloading puppet to pick up new facts') # Recompile the catalog catalog = Puppet::Resource::Catalog.indirection.find(Puppet[:node_name_value]) catalog = pconf.convert_catalog(catalog, 1) # Set up run options transaction_uuid = SecureRandom.uuid environment = Puppet[:environment] options = {} options[:report] = Puppet::Transaction::Report.new('apply', nil, environment, transaction_uuid) options[:catalog] = catalog # Apply the full catalog pconf.run(options) # Abort the first catalog run, which is using old facts Puppet::Application.stop! Puppet.alert('finished reloading puppet to pick up new facts') true end def reload_facts(pattern, _pconf, pnode) old = get_matching_facts(@facts, pattern, pnode) new = get_matching_facts(refreshed_facts, pattern, pnode) diff = diff_hashes(old, new) diff end def get_matching_facts(fact_hash, pattern, _pnode) clean_facts = fact_hash.reject { |k, _v| !k.is_a?(String) || k[0..0] == '_' } matched_facts = pattern ? clean_facts.reject { |k, _v| !pattern.match(k) } : clean_facts matched_facts end # given two hashes, this returns a "diff hash" where only the keys and # values that differ between the given hashes are listed. All values # become two-element arrays where the first element is the value from # the first hash and the second is the value from the second hash. If # a key was missing from either hash its corresponding value will be # nil. This isn't perfect, but will do for now. Speed wins. def diff_hashes(h1, h2) both_keys = Set[h1.keys] | h2.keys diff_hash = both_keys.each_with_object({}) do |k, h| h[k] = [h1[k], h2[k]] if h1[k] != h2[k]; h end # pp h1, h2, diff_hash diff_hash end def loaded_facts(pnode) Puppet::Node::Facts.indirection.find(pnode).values end def refreshed_facts Facter.clear Facter.to_hash end end
<gh_stars>100-1000 import { BaseService, Service } from "/@/core"; @Service("wechat/user/tags") class WechatTags extends BaseService { sync(data: any) { return this.request({ url: "/sync", method: "POST", data }); } tagging(data: any) { return this.request({ url: "/tagging", method: "POST", data }); } } export default WechatTags;
def reverseSentence(sentence): words = sentence.split(' ') newWords = [word[::-1] for word in words] newSentence = ' '.join(newWords) return newSentence sentence = input("Enter a sentence: ") print(reverseSentence(sentence))
import { WGSLEncoder } from "../../shaderlib"; import { ShaderMacroCollection } from "../../shader"; export class WGSLParticleNoise { execute(encoder: WGSLEncoder, macros: ShaderMacroCollection) { encoder.addFunction( "// Fast computation of x modulo 289\n" + "fn mod289Vec3(x: vec3<f32>) -> vec3<f32> {\n" + " return x - floor(x * (1.0 / 289.0)) * 289.0;\n" + "}\n" + "\n" + "fn mod289Vec4(x: vec4<f32>) -> vec4<f32> {\n" + " return x - floor(x * (1.0 / 289.0)) * 289.0;\n" + "}\n" + "\n" + "// Compute indices for the PRNG\n" + "fn permute(x: vec4<f32>, uPerlinNoisePermutationSeed: f32) -> vec4<f32> {\n" + " return mod289Vec4(((x*34.0)+1.0)*x + vec4<f32>(uPerlinNoisePermutationSeed));\n" + "}\n" + "\n" + "// Quintic interpolant\n" + "fn fadeVec2(u: vec2<f32>) -> vec2<f32> {\n" + " return u*u*u*(u*(u*6.0 - 15.0) + 10.0);\n" + " \n" + " // Original cubic interpolant (faster, but not 2nd order derivable)\n" + " //return u*u*(3.0f - 2.0f*u);\n" + "}\n" + "\n" + "fn fadeVec3(u: vec3<f32>) -> vec3<f32> {\n" + " return u*u*u*(u*(u*6.0 - 15.0) + 10.0);\n" + "}\n" + "\n" + "fn normalizeNoise(n: f32) -> f32 {\n" + " // return noise in [0, 1]\n" + " return 0.5*(2.44*n + 1.0);\n" + "}\n" + "\n" + "\n" + "///////////////////////////////////////////////////////////////////////////////////////////////////\n" + "fn pnoise_gradients(pt: vec2<f32>, uPerlinNoisePermutationSeed: f32, gradients: ptr<function, vec4<f32> >, fpt: ptr<function, vec4<f32> >) {\n" + " // Retrieve the integral part (for indexation)\n" + " var ipt = floor(pt.xyxy) + vec4<f32>(0.0, 0.0, 1.0, 1.0);\n" + " \n" + " ipt = mod289Vec4(ipt);\n" + " \n" + " // Compute the 4 corners hashed gradient indices\n" + " let ix = ipt.xzxz;\n" + " let iy = ipt.yyww;\n" + " let p = permute(permute(ix, uPerlinNoisePermutationSeed) + iy, uPerlinNoisePermutationSeed);\n" + " \n" + " // Fast version for :\n" + " // p.x = P(P(ipt.x) + ipt.y);\n" + " // p.y = P(P(ipt.x+1.0f) + ipt.y);\n" + " // p.z = P(P(ipt.x) + ipt.y+1.0f);\n" + " // p.w = P(P(ipt.x+1.0f) + ipt.y+1.0f);\n" + " \n" + " // With 'p', computes Pseudo Random Numbers\n" + " let one_over_41 = 1.0 / 41.0; //0.02439f\n" + " var gx = 2.0 * fract(p * one_over_41) - 1.0;\n" + " let gy = abs(gx) - 0.5;\n" + " let tx = floor(gx + 0.5);\n" + " gx = gx - tx;\n" + " \n" + " // Create unnormalized gradients\n" + " var g00 = vec2<f32>(gx.x,gy.x);\n" + " var g10 = vec2<f32>(gx.y,gy.y);\n" + " var g01 = vec2<f32>(gx.z,gy.z);\n" + " var g11 = vec2<f32>(gx.w,gy.w);\n" + " \n" + " // 'Fast' normalization\n" + " let dp = vec4<f32>(dot(g00, g00), dot(g10, g10), dot(g01, g01), dot(g11, g11));\n" + " let norm = inverseSqrt(dp);\n" + " g00 = g00 * norm.x;\n" + " g10 = g10 * norm.y;\n" + " g01 = g01 * norm.z;\n" + " g11 = g11 * norm.w;\n" + " \n" + " // Retrieve the fractional part (for interpolation)\n" + " *fpt = fract(pt.xyxy) - vec4<f32>(0.0, 0.0, 1.0, 1.0);\n" + " \n" + " // Calculate gradient's influence\n" + " let fx = (*fpt).xzxz;\n" + " let fy = (*fpt).yyww;\n" + " let n00 = dot(g00, vec2<f32>(fx.x, fy.x));\n" + " let n10 = dot(g10, vec2<f32>(fx.y, fy.y));\n" + " let n01 = dot(g01, vec2<f32>(fx.z, fy.z));\n" + " let n11 = dot(g11, vec2<f32>(fx.w, fy.w));\n" + "\n" + " // Fast version for :\n" + " // n00 = dot(g00, fpt + vec2(0.0f, 0.0f));\n" + " // n10 = dot(g10, fpt + vec2(-1.0f, 0.0f));\n" + " // n01 = dot(g01, fpt + vec2(0.0f,-1.0f));\n" + " // n11 = dot(g11, fpt + vec2(-1.0f,-1.0f));\n" + " \n" + " *gradients = vec4<f32>(n00, n10, n01, n11);\n" + "}\n" + "\n" + "// Classical Perlin Noise 2D\n" + "fn pnoise2D(pt: vec2<f32>, uPerlinNoisePermutationSeed: f32) -> f32 {\n" + " var g:vec4<f32>;\n" + " var fpt:vec4<f32>;\n" + " pnoise_gradients(pt, uPerlinNoisePermutationSeed, &g, &fpt);\n" + " \n" + " // Interpolate gradients\n" + " let u = fadeVec2(fpt.xy);\n" + " let n1 = mix(g.x, g.y, u.x);\n" + " let n2 = mix(g.z, g.w, u.x);\n" + " let noise = mix(n1, n2, u.y);\n" + " \n" + " return noise;\n" + "}\n" + "\n" + "// Derivative Perlin Noise 2D\n" + "fn dpnoise(pt: vec2<f32>, uPerlinNoisePermutationSeed: f32) -> vec3<f32> {\n" + " var g:vec4<f32>;\n" + " var fpt:vec4<f32>;\n" + " pnoise_gradients(pt, uPerlinNoisePermutationSeed, &g, &fpt);\n" + " \n" + " let k0 = g.x;\n" + " let k1 = g.y - g.x;\n" + " let k2 = g.z - g.x;\n" + " let k3 = g.x - g.z - g.y + g.w;\n" + " var res = vec3<f32>(0.0);\n" + " \n" + " let u = fadeVec2(fpt.xy);\n" + " res.x = k0 + k1*u.x + k2*u.y + k3*u.x*u.y;\n" + " \n" + " let dpt = 30.0*fpt.xy*fpt.xy*(fpt.xy*(fpt.xy - 2.0) + 1.0);\n" + " res.y = dpt.x * (k1 + k3*u.y);\n" + " res.z = dpt.y * (k2 + k3*u.x);\n" + " \n" + " return res;\n" + "}\n" + "\n" + "// Classical Perlin Noise fbm 2D\n" + "fn fbm_pnoise2D(pt: vec2<f32>, zoom: f32, numOctave: u32, frequency: f32, amplitude: f32, uPerlinNoisePermutationSeed: f32) -> f32 {\n" + " var sum = 0.0;\n" + " var f = frequency;\n" + " var w = amplitude;\n" + " \n" + " let v = zoom * pt;\n" + " \n" + " for (var i = 0u; i < numOctave; i = i + 1u) {\n" + " sum = sum + w * pnoise2D(f*v, uPerlinNoisePermutationSeed);\n" + " f = f * frequency;\n" + " w = f * amplitude;\n" + " }\n" + " \n" + " return sum;\n" + "}\n" + "\n" + "// Derivative Perlin Noise fbm 2D\n" + "fn fbm_pnoise_derivative(pt: vec2<f32>, zoom: f32, numOctave: u32, frequency: f32, amplitude: f32, uPerlinNoisePermutationSeed: f32) -> f32 {\n" + " var sum = 0.0;\n" + " var f = frequency;\n" + " var w = amplitude;\n" + "\n" + " var dn = vec2<f32>(0.0);\n" + " \n" + " let v = zoom * pt;\n" + " \n" + " for (var i = 0u; i < numOctave; i = i + 1u) {\n" + " let n = dpnoise(f*v, uPerlinNoisePermutationSeed);\n" + " dn = dn + n.yz;\n" + " \n" + " let crestFactor = 1.0 / (1.0 + dot(dn,dn));\n" + " \n" + " sum = sum + w * n.x * crestFactor;\n" + " f = f * frequency;\n" + " w = w * amplitude;\n" + " }\n" + " \n" + " return sum;\n" + "}\n" + "\n" + "///////////////////////////////////////////////////////////////////////////////////////////////////\n" + "// Classical Perlin Noise 3D\n" + "fn pnoise3D(pt: vec3<f32>, uPerlinNoisePermutationSeed: f32) -> f32 {\n" + " // Retrieve the integral part (for indexation)\n" + " var ipt0 = floor(pt);\n" + " var ipt1 = ipt0 + vec3<f32>(1.0);\n" + " \n" + " ipt0 = mod289Vec3(ipt0);\n" + " ipt1 = mod289Vec3(ipt1);\n" + " \n" + " // Compute the 8 corners hashed gradient indices\n" + " let ix = vec4<f32>(ipt0.x, ipt1.x, ipt0.x, ipt1.x);\n" + " let iy = vec4<f32>(ipt0.yy, ipt1.yy);\n" + " let p = permute(permute(ix, uPerlinNoisePermutationSeed) + iy, uPerlinNoisePermutationSeed);\n" + " let p0 = permute(p + ipt0.zzzz, uPerlinNoisePermutationSeed);\n" + " let p1 = permute(p + ipt1.zzzz, uPerlinNoisePermutationSeed);\n" + " \n" + " // Compute Pseudo Random Numbers\n" + " var gx0 = p0 * (1.0 / 7.0);\n" + " var gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;\n" + " gx0 = fract(gx0);\n" + " let gz0 = vec4<f32>(0.5) - abs(gx0) - abs(gy0);\n" + " let sz0 = step(gz0, vec4<f32>(0.0));\n" + " gx0 = gx0 - sz0 * (step(vec4<f32>(0.0), gx0) - 0.5);\n" + " gy0 = gy0 - sz0 * (step(vec4<f32>(0.0), gy0) - 0.5);\n" + " \n" + " var gx1 = p1 * (1.0 / 7.0);\n" + " var gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;\n" + " gx1 = fract(gx1);\n" + " let gz1 = vec4<f32>(0.5) - abs(gx1) - abs(gy1);\n" + " let sz1 = step(gz1, vec4<f32>(0.0));\n" + " gx1 = gx1 - sz1 * (step(vec4<f32>(0.0), gx1) - 0.5);\n" + " gy1 = gy1 - sz1 * (step(vec4<f32>(0.0), gy1) - 0.5);\n" + " \n" + " \n" + " // Create unnormalized gradients\n" + " var g000 = vec3<f32>(gx0.x, gy0.x, gz0.x);\n" + " var g100 = vec3<f32>(gx0.y, gy0.y, gz0.y);\n" + " var g010 = vec3<f32>(gx0.z, gy0.z, gz0.z);\n" + " var g110 = vec3<f32>(gx0.w, gy0.w, gz0.w);\n" + " var g001 = vec3<f32>(gx1.x, gy1.x, gz1.x);\n" + " var g101 = vec3<f32>(gx1.y, gy1.y, gz1.y);\n" + " var g011 = vec3<f32>(gx1.z, gy1.z, gz1.z);\n" + " var g111 = vec3<f32>(gx1.w, gy1.w, gz1.w);\n" + " \n" + " // 'Fast' normalization\n" + " var dp = vec4<f32>(dot(g000, g000), dot(g100, g100), dot(g010, g010), dot(g110, g110));\n" + " var norm = inverseSqrt(dp);\n" + " g000 = g000 * norm.x;\n" + " g100 = g100 * norm.y;\n" + " g010 = g010 * norm.z;\n" + " g110 = g110 * norm.w;\n" + " \n" + " dp = vec4<f32>(dot(g001, g001), dot(g101, g101), dot(g011, g011), dot(g111, g111));\n" + " norm = inverseSqrt(dp);\n" + " g001 = g001 * norm.x;\n" + " g101 = g101 * norm.y;\n" + " g011 = g011 * norm.z;\n" + " g111 = g111 * norm.w;\n" + " \n" + " // Retrieve the fractional part (for interpolation)\n" + " let fpt0 = fract(pt);\n" + " let fpt1 = fpt0 - vec3<f32>(1.0);\n" + " \n" + " // Calculate gradient's influence\n" + " let n000 = dot(g000, fpt0);\n" + " let n100 = dot(g100, vec3<f32>(fpt1.x, fpt0.yz));\n" + " let n010 = dot(g010, vec3<f32>(fpt0.x, fpt1.y, fpt0.z));\n" + " let n110 = dot(g110, vec3<f32>(fpt1.xy, fpt0.z));\n" + " let n001 = dot(g001, vec3<f32>(fpt0.xy, fpt1.z));\n" + " let n101 = dot(g101, vec3<f32>(fpt1.x, fpt0.y, fpt1.z));\n" + " let n011 = dot(g011, vec3<f32>(fpt0.x, fpt1.yz));\n" + " let n111 = dot(g111, fpt1);\n" + " \n" + " // Interpolate gradients\n" + " let u = fadeVec3(fpt0);\n" + " let nxy0 = mix(mix(n000, n100, u.x), mix(n010, n110, u.x), u.y);\n" + " let nxy1 = mix(mix(n001, n101, u.x), mix(n011, n111, u.x), u.y);\n" + " let noise = mix(nxy0, nxy1, u.z);\n" + " \n" + " return noise;\n" + "}\n" + "\n" + "// Classical Perlin Noise 2D + time\n" + "fn pnoise_loop(u: vec2<f32>, dt: f32, uPerlinNoisePermutationSeed: f32) -> f32 {\n" + " let pt1 = vec3<f32>(u, dt);\n" + " let pt2 = vec3<f32>(u, dt - 1.0);\n" + " \n" + " return mix(pnoise3D(pt1, uPerlinNoisePermutationSeed), pnoise3D(pt2, uPerlinNoisePermutationSeed), dt);\n" + "}\n" + "\n" + "// Classical Perlin Noise fbm 3D\n" + "fn fbm_pnoise3D(pt: vec3<f32>, zoom: f32, numOctave: u32, frequency: f32, amplitude: f32, uPerlinNoisePermutationSeed: f32) -> f32 {\n" + " var sum = 0.0;\n" + " var f = frequency;\n" + " var w = amplitude;\n" + " \n" + " let v = zoom * pt;\n" + " \n" + " for (var i = 0u; i < numOctave; i = i + 1u) {\n" + " sum = sum + w * pnoise3D(f*v, uPerlinNoisePermutationSeed);\n" + " \n" + " f = f * frequency;\n" + " w = w * amplitude;\n" + " }\n" + " \n" + " return sum;\n" + "}\n" + "\n" + "fn fbm3D(ws: vec3<f32>, uPerlinNoisePermutationSeed: f32) -> f32 {\n" + " let N = 128.0;\n" + " let zoom = 1.0 / N;\n" + " let octave = 4u;\n" + " let freq = 2.0;\n" + " let w = 0.45;\n" + " \n" + " return N * fbm_pnoise3D(ws, zoom, octave, freq, w, uPerlinNoisePermutationSeed);\n" + "}\n" ); encoder.addFunction( "fn smoothstep_2(edge0: f32, edge1: f32, x: f32) -> f32 {\n" + " let t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n" + " return t * t * t * (10.0 + t *(-15.0 + 6.0 * t));\n" + "}\n" + "\n" + "fn ramp(x: f32) -> f32 {\n" + " return smoothstep_2(-1.0, 1.0, x) * 2.0 - 1.0;\n" + "}\n" + "\n" + "fn noise3d(seed: vec3<f32>, uPerlinNoisePermutationSeed: f32) -> vec3<f32> {\n" + " return vec3<f32>(pnoise3D(seed, uPerlinNoisePermutationSeed),\n" + " pnoise3D(seed + vec3<f32>(31.416, -47.853, 12.793), uPerlinNoisePermutationSeed),\n" + " pnoise3D(seed + vec3<f32>(-233.145, -113.408, -185.31), uPerlinNoisePermutationSeed));\n" + "}\n" + "\n" + "fn match_boundary(inv_noise_scale: f32, d: f32, normal: vec3<f32>, psi: ptr<function, vec3<f32> >) {\n" + " let alpha = ramp(abs(d) * inv_noise_scale);\n" + " let dp = dot(*psi, normal);\n" + " *psi = mix(dp * normal, *psi, alpha);\n" + "}\n" + "\n" + "// [ User customized sampling function ]\n" + "fn sample_potential(p:vec3<f32>, uPerlinNoisePermutationSeed:f32)->vec3<f32> {\n" + " let num_octaves = 4u;\n" + " \n" + " // Potential\n" + " var psi = vec3<f32>(0.0);\n" + " \n" + " // Compute normal and retrieve distance from colliders.\n" + " var normal = vec3<f32>(0.0);\n" + " let distance = compute_gradient(p, &normal);\n" + " \n" + "\n" + " // let PlumeCeiling = 0.0;\n" + " // let PlumeBase = -3.0;\n" + " // let PlumeHeight = 80.0;\n" + " // let RingRadius = 10.25;\n" + " // let RingSpeed = 0.3;\n" + " // let RingsPerSecond = 0.125;\n" + " // let RingMagnitude = 10.0;\n" + " // let RingFalloff = 0.7;\n" + "\n" + " \n" + " var height_factor = 1.0;//ramp((p.y - PlumeBase)/ PlumeHeight);\n" + " \n" + " // Add turbulence octaves that respects boundaries.\n" + " var noise_gain = 1.0;\n" + " for(var i = 0u; i < num_octaves; i = i + 1u) {\n" + " // const float noise_scale = 0.42f * noise_gain;\n" + " let inv_noise_scale = 1.0 / noise_gain;\n" + " \n" + " let s = p * inv_noise_scale;\n" + " let n = noise3d(s, uPerlinNoisePermutationSeed);\n" + " \n" + " match_boundary(inv_noise_scale, distance, normal, &psi);\n" + " psi = psi + height_factor * noise_gain * n;\n" + "\n" + " noise_gain = noise_gain * 0.5;\n" + " }\n" + " \n" + " // [ add custom potentials ]\n" + " // --------\n" + " // vec3 rising_force = vec3(-p.z, 0.0f, p.x);\n" + " // \n" + " // let ring_y = PlumeCeiling;\n" + " // let d = ramp(abs(distance) / RingRadius);\n" + " // \n" + " // while (ring_y > PlumeBase) {\n" + " // float ry = p.y - ring_y;\n" + " // float rr = sqrt(dot(p.xz, p.xz));\n" + " // vec3 v = vec3(rr-RingRadius, rr+RingRadius, ry);\n" + " // float rmag = RingMagnitude / (dot(v,v) + RingFalloff);\n" + " // vec3 rpsi = rmag * rising_force;\n" + " // psi += mix(dot(rpsi, normal)*normal, psi, d);\n" + " // ring_y -= RingSpeed / RingsPerSecond;\n" + " // }\n" + " \n" + " return psi;\n" + "}\n" + "\n" + "\n" + "fn compute_curl(p: vec3<f32>, uPerlinNoisePermutationSeed: f32) -> vec3<f32> {\n" + " let eps:f32 = 1.0e-4;\n" + " \n" + " let dx = vec3<f32>(eps, 0.0, 0.0);\n" + " let dy = dx.yxy;\n" + " let dz = dx.yyx;\n" + " \n" + " let p00 = sample_potential(p + dx, uPerlinNoisePermutationSeed);\n" + " let p01 = sample_potential(p - dx, uPerlinNoisePermutationSeed);\n" + " let p10 = sample_potential(p + dy, uPerlinNoisePermutationSeed);\n" + " let p11 = sample_potential(p - dy, uPerlinNoisePermutationSeed);\n" + " let p20 = sample_potential(p + dz, uPerlinNoisePermutationSeed);\n" + " let p21 = sample_potential(p - dz, uPerlinNoisePermutationSeed);\n" + " \n" + " var v = vec3<f32>(0.0);\n" + " v.x = p11.z - p10.z - p21.y + p20.y;\n" + " v.y = p21.x - p20.x - p01.z + p00.z;\n" + " v.z = p01.y - p00.y - p11.x + p10.x;\n" + " v = v / (2.0*eps);\n" + " \n" + " return v;\n" + "}\n" ); } }
<filename>src/client/app/home/home.component.ts import { Component, ElementRef, ViewChild, Renderer, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { QueryService } from '../shared/index'; /** * This class represents the lazy loaded home Component. */ @Component({ moduleId: module.id, selector: 'sd-home', templateUrl: 'home.component.html', styleUrls: ['home.component.css'], }) export class HomeComponent implements OnInit { tagline:string = 'The search tool to find academics, staff and researchers'; /** * Routing Variables */ home_route:boolean = false; //default true results_route:boolean = false; profile_route:boolean = false; /** * Results Route Variables */ results_query:string = ''; /** * Profile Route Variables */ profile_url_id:string = ''; /** * Graph Variables */ graph_context: string = 'home'; graph_content: Object = {}; /** * View Variables */ right_open:boolean = false; @ViewChild('leftContainer') left : ElementRef; // @ViewChild('rightContainer') right : ElementRef; /** * Creates an instance of HomeComponent * @param {Renderer} renderer - injects the renderer * @param {Router} router - injects the router service * @param {ActivatedRoute} ar - injects details of the current activated route */ constructor(private renderer:Renderer, private router: Router, private ar: ActivatedRoute, private qs: QueryService) {} /** * Runs on View Init * Initialises the correct view dependant on the url */ ngOnInit() { let url:string = this.router.url; if(url.includes('/search')) { this.initResults(); } else if (url.includes('/profile')) { this.initProfile(); } else { this.initHome(); } this.openRightIfChecked(); } /** * Initialises the results components * Extracts id and query from the url */ initResults() { this.results_route = true; this.right_open = true; this.ar.params.subscribe( params => { this.results_query = params['query']; this.graph_context = 'results'; this.graph_content = {personIdx: []}; }, error => this.routeErrorRedirect(error) ); } /** * Initialises the profile components * Extracts the id from the url */ initProfile() { this.profile_route = true; this.right_open = true; this.ar.params.subscribe( params => { this.profile_url_id = params['id']; this.graph_context = 'profile'; this.graph_content = {personIdx: this.profile_url_id}; }, error => this.routeErrorRedirect(error) ); } /** * Initialises the home components * No extraction necessary */ initHome() { this.home_route = true; this.right_open = false; this.graph_context = 'home'; } submitGraphContent(e: Object) { this.graph_content = e; } /** * Opens the login Modal */ onLoginButtonPress() { this.router.navigate([{outlets: { modal: 'login' }}]); } /** * Handles the click of a point on the graph, get a person object back */ onGraphPointClick(e: any) { this.results_query = e.name; } /** * Sets the css to the correct width if the right menu is open */ openRightIfChecked() { if(this.right_open) { this.renderer.setElementStyle(this.left.nativeElement, 'width', '50%'); } else { this.renderer.setElementStyle(this.left.nativeElement, 'width', '100%'); } } /** * Any errors in routing will cause a redirect back to home page. */ routeErrorRedirect(error:any) { console.log(error); this.router.navigate(['/']); } }
<reponame>jameswilddev/noscript import Svgo from "svgo" export default { svgo(svg, onSuccess, onError) { new Svgo({ plugins: [{ cleanupAttrs: true }, { inlineStyles: true }, { removeDoctype: true }, { removeXMLProcInst: true }, { removeComments: true }, { removeMetadata: true }, { removeTitle: true }, { removeDesc: true }, { removeUselessDefs: true }, { removeXMLNS: true }, { removeEditorsNSData: true }, { removeEmptyAttrs: true }, { removeHiddenElems: true }, { removeEmptyText: true }, { removeEmptyContainers: true }, { removeViewBox: false }, { cleanupEnableBackground: true }, { minifyStyles: true }, { convertStyleToAttrs: true }, { convertColors: true }, { convertPathData: true }, { convertTransform: true }, { removeUnknownsAndDefaults: true }, { removeNonInheritableGroupAttrs: true }, { removeUselessStrokeAndFill: true }, { removeUnusedNS: true }, { cleanupIDs: true }, { cleanupNumericValues: true }, { cleanupListOfValues: { floatPrecision: 0, leadingZero: true, defaultPx: true, convertToPx: true } }, { moveElemsAttrsToGroup: true }, { moveGroupAttrsToElems: true }, { collapseGroups: true }, { removeRasterImages: true }, { mergePaths: true }, { convertShapeToPath: true }, { sortAttrs: true }, { removeDimensions: true }, { removeStyleElement: true }, { removeScriptElement: true }] }) .optimize(svg) .catch(e => onError(e)) .then(result => onSuccess(result.data)) } }
#!/usr/bin/env bash set -e docker build --squash --rm -t docker-slim -f Dockerfile ../../.. docker image prune --filter label=build-role=ca-certs -f docker image prune --filter label=app=docker-slim -f
set -ex main() { curl -sSf https://build.travis-ci.org/files/rustup-init.sh | sh -s -- --default-toolchain=nightly -y export PATH=$HOME/.cargo/bin:$PATH npm install -g webpack local target= if [ $TRAVIS_OS_NAME = linux ]; then target=x86_64-unknown-linux-musl sort=sort fi # This fetches latest stable release local tag=$(git ls-remote --tags --refs --exit-code https://github.com/japaric/cross \ | cut -d/ -f3 \ | grep -E '^v[0.1.0-9.]+$' \ | $sort --version-sort \ | tail -n1) curl -LSfs https://japaric.github.io/trust/install.sh | \ sh -s -- \ --force \ --git japaric/cross \ --tag $tag \ --target $target } main
<reponame>CeriniGaming/star-wars-rpg import React from 'react'; export default class CharacterCreator extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { alert('do the thing!'); } render() { return ( <div > <h1>Placeholder</h1> <p>Bacon ipsum dolor amet drumstick pork corned beef, tail sirloin tri-tip porchetta swine. Meatball biltong jerky ground round, andouille shoulder salami fatback sausage pig. Prosciutto andouille alcatra pork loin brisket ribeye corned beef. Bresaola picanha sirloin kielbasa. Bacon hamburger shoulder meatball swine chicken. Fatback ball tip strip steak pig beef ribs flank. Ham hock leberkas picanha andouille meatball.</p> <button onClick={this.handleClick}>Click for bacon!</button> </div> ); } }
let request = require('request'); let url = 'http://www.example.com'; request(url, function(err, response, body){ if(err){ console.log('There was an error:', err); } else { console.log('Successfully made the HTTP request!'); console.log('Response body is', body); } });
#!/bin/sh set -e # # LXD images recipe: PhpMyAdmin # # Dependencies: Composer # # Environment variables: # # - DBUSER - database user, e.g. 'drupal', default 'root' # - DBPASS - database password, e.g. 'drupal', default '' # installPhpMyAdmin() { # Fetch the variables DBUSER=${DBUSER:-"root"} DBPASS=${DBPASS:-""} # Check the dependencies command -v composer > /dev/null || (echo "installPhpMyAdmin recipe requires Composer, missing"; exit 1) # Install PhpMyAdmin composer create-project --no-dev --prefer-dist phpmyadmin/phpmyadmin /opt/phpmyadmin # Add PhpMyAdmin configuration file cp /config/phpmyadmin /opt/phpmyadmin/config.inc.php sed -i "s|youruser|${DBUSER}|g" /opt/phpmyadmin/config.inc.php sed -i "s|yourpass|${DBPASS}|g" /opt/phpmyadmin/config.inc.php }
<filename>packages/vx-glyph/src/index.js<gh_stars>0 import Glyph from './glyphs/Glyph'; import Dot from './glyphs/Dot'; export default { Glyph, Dot, }
# frozen_string_literal: true module Avatar class Avatar < ApplicationComponent delegate :avatar, :avatar?, to: :contributor, prefix: true def initialize(contributor: nil, expandable: false, **) super @contributor = contributor @expandable = expandable end private attr_reader :contributor def key contributor&.id end def url thumbnail = contributor_avatar.variant(resize_to_fit: [200, 200]) url_for(thumbnail) end def initials return '?' unless contributor initials = contributor.name.split.map { |part| part&.first } return '?' if initials.empty? initials.join end def expandable? @expandable end end end
#!/usr/bin/env bash git pull origin master echo "Setting environment variables..." source .exports echo -e "Environment variables setted.\n" press_y_to_confirm() { echo "$1(y/N)" read input if [ "$input" != "Y" ] && [ "$input" != "y" ]; then return 0 else return 1 fi } install_pkg_manager() { case `uname -s` in Darwin*) press_y_to_confirm "Install Homebrew on macOS" ret=$? if [ $ret -ne 0 ]; then /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" PATH=/usr/local/bin:/opt/homebrew/bin:$PATH else echo "Installation cannot proceed without package manager. Exiting..." exit -1 fi ;; *) echo "This script cannot handle the installation of package manager on `uname -s`, exiting..." exit -1 ;; esac } check_pkg_manager() { while [[ $PKG_MANAGER == "" ]]; do echo "Check package manager..." if [[ `which brew` ]]; then PKG_MANAGER="brew" PKG_INSTALL="brew install" PKG_UPDATE="brew update" elif [[ `which apt` ]] && [[ `uname -s` != "Darwin" ]]; then PKG_MANAGER="apt-get" PKG_INSTALL="apt-get install -y" PKG_UPDATE="apt-get update" else install_pkg_manager fi done echo "Package manager commands:" echo "- Manager $PKG_MANAGER" echo "- Install $PKG_INSTALL" echo "- Update $PKG_UPDATE" echo "Package manager checked" } prepare_pkg_manager() { echo "Prepare package manager..." echo "- Command: $PKG_UPDATE" $PKG_UPDATE echo "Package manager prepared" } install_zsh() { echo "installing zsh..." $PKG_INSTALL zsh echo "zsh installed" } install_oh_my_zsh() { if [[ ! `which zsh` ]]; then install_zsh fi sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" "" --unattended } install_gnupg() { $PKG_INSTALL gpg # reference: https://stackoverflow.com/questions/39494631/gpg-failed-to-sign-the-data-fatal-failed-to-write-commit-object-git-2-10-0 if [[ `uname -s` == "Darwin" ]]; then $PKG_MANAGER link --overwrite gnupg $PKG_INSTALL pinentry-mac GNUPGHOME="$XDG_CONFIG_HOME/gnupg" mkdir -p "$GNUPGHOME" echo "pinentry-program `which pinentry-mac`" >> "$GNUPGHOME/gpg-agent.conf" echo "# for GPG config path" >> "$HOME/.zshrc" echo "export GNUPGHOME=\"$GNUPGHOME\"" >> "$HOME/.zshrc" killall gpg-agent fi } install_git() { $PKG_INSTALL git } install_npm() { $PKG_INSTALL npm } install_commitizen() { npm install -g commitizen } setup_zshrc() { echo "Setting up ~/.zshrc..." echo "export XDG_CONFIG_HOME=\"$XDG_CONFIG_HOME\"" >> "$HOME/.zshrc" cat ".zshrc_addon" >> "$HOME/.zshrc" } copy_over_XDG() { echo "Copying over XDG Configs" /bin/cp -rv "git" "$XDG_CONFIG_HOME/" } install() { echo "Installing..." check_pkg_manager prepare_pkg_manager press_y_to_confirm "install oh-my-zsh" if [[ $? -ne 0 ]]; then install_oh_my_zsh fi press_y_to_confirm "install gnupg" if [[ $? -ne 0 ]]; then install_gnupg fi press_y_to_confirm "install git" if [[ $? -ne 0 ]]; then install_git fi press_y_to_confirm "install npm" if [[ $? -ne 0 ]]; then install_npm fi press_y_to_confirm "install commitizen (git cz)" if [[ $? -ne 0 ]]; then install_commitizen fi press_y_to_confirm "setup ~/.zshrc" if [[ $? -ne 0 ]]; then setup_zshrc fi press_y_to_confirm "copy over XDG_CONFIG_HOME files" if [[ $? -ne 0 ]]; then copy_over_XDG fi } uninstall() { echo "Uninstalling..." } parse_argument() { for argument in "$@"; do case $argument in (install) install ;; (uninstall) uninstall ;; (setup_zshrc) setup_zshrc ;; (copy_over_XDG) copy_over_XDG ;; esac done } # Run in interactive mode when no argument is specified. parse() { if [[ $# == 0 ]]; then echo "Enter a number to choose:" select action in install uninstall setup_zshrc copy_over_XDG; do parse_argument $action break done else parse_argument $@ fi } parse $@
#!/bin/bash - # by William SHANG # myAppServProj/ospf_setup.sh # completed source ./myNetCfg.conf # installing quagga and starting ospfd/zebra sudo yum install quagga sudo yum update systemctl enable zebra systemctl start zebra systemctl enable ospfd systemctl start ospfd # setting up zebra.conf; sudo mv $myZebraPath $myZebraPath.backup sudo touch $myZebraPath sudo echo "# $myZebraPath created using bash script" >> $myZebraPath sudo sed -i "\$ahostname $myRtrHostname.$myDomain\npassword $zebraPass\nenable password $zebraEnablePass\n\!\ninterface lo\n\!\nline vty\n\!\nlog file /var/log/quagga/quagga.log\n\!" $myZebraPath # creating active interface array declare -a myIfcfgArray=() for myIfcfg in $(ip a | cut -d ' ' -f2| tr ':' '\n' | awk NF) do if [ "$myIfcfg" != "lo" ]; then myIfcfgArray+=("$myIfcfg") fi done # looping to update ospfd files for active interface for anyInterface in "${myIfcfgArray[@]}" do if [[ "$(declare -p $anyInterface 2>/dev/null)" == "declare -A"* ]]; then sudo sed -i "/enable password.*/a interface $anyInterface\n\ description $anyInterface\n\ ip address ${anyInterface[IPADDR]}/${anyInterface[PREFIX]}\n\ ipv6 nd suppress-ra\n\ ip forwarding\n\!" $myZebraPath fi done systemctl restart zebra ############################################ # setting up ospfd.conf; sudo mv $myOspfdPath $myOspfdPath.backup sudo touch $myOspfdPath sudo echo "# $myOspfdPath created using bash script" >> $myOspfdPath sudo sed -i "\$ahostname $myRtrHostname.$myDomain\npassword $ospfPass\nenable password $ospfEnablePass\n\!\nrouter ospf\n\ ospf router-id ${eth0[IPADDR]}\n\!\nline vty\n\!\nlog file /var/log/quagga/ospfd.log\nlog stdout\n\!" $myOspfdPath # creating active interface array declare -a myIfcfgArray=() for myIfcfg in $(ip a | cut -d ' ' -f2| tr ':' '\n' | awk NF) do if [ "$myIfcfg" != "lo" ]; then myIfcfgArray+=("$myIfcfg") fi done # looping to update ospfd files for active interface for anyInterface in "${myIfcfgArray[@]}" do if [[ "$(declare -p $anyInterface 2>/dev/null)" == "declare -A"* ]]; then sudo sed -i "/enable password.*/a interface $anyInterface\n\!" $myOspfdPath sudo sed -i "/ospf router-id ${eth0[IPADDR]}/a \ network ${anyInterface[NETWORK]}/${anyInterface[PREFIX]} area 0" "$myOspfdPath" fi done systemctl restart ospfd systemctl restart network
#!/usr/bin/env bash # Set DISTNAME, BRANCH and MAKEOPTS to the desired settings DISTNAME=quartercoin-2.0.3 MAKEOPTS="-j4" BRANCH=master clear if [[ $EUID -ne 0 ]]; then echo "This script must be run with sudo" exit 1 fi if [[ $PWD != $HOME ]]; then echo "This script must be run from ~/" exit 1 fi if [ ! -f ~/MacOSX10.11.sdk.tar.gz ] then echo "Before executing script.sh transfer MacOSX10.11.sdk.tar.gz to ~/" exit 1 fi export PATH_orig=$PATH echo @@@ echo @@@"Installing Dependecies" echo @@@ apt install -y curl g++-aarch64-linux-gnu g++-7-aarch64-linux-gnu gcc-7-aarch64-linux-gnu binutils-aarch64-linux-gnu g++-arm-linux-gnueabihf g++-7-arm-linux-gnueabihf gcc-7-arm-linux-gnueabihf binutils-arm-linux-gnueabihf g++-7-multilib gcc-7-multilib binutils-gold git pkg-config autoconf libtool automake bsdmainutils ca-certificates python g++ mingw-w64 g++-mingw-w64 nsis zip rename librsvg2-bin libtiff-tools cmake imagemagick libcap-dev libz-dev libbz2-dev python-dev python-setuptools fonts-tuffy cd ~/ # Removes any existing builds and starts clean WARNING rm -rf ~/quartercoin ~/sign ~/release git clone https://github.com/QuarterCoin/Quarter-Coin-Wallet cd ~/quartercoin git checkout $BRANCH echo @@@ echo @@@"Building linux 64 binaries" echo @@@ mkdir -p ~/release cd ~/quartercoin/depends make HOST=x86_64-linux-gnu $MAKEOPTS cd ~/quartercoin export PATH=$PWD/depends/x86_64-linux-gnu/native/bin:$PATH ./autogen.sh CONFIG_SITE=$PWD/depends/x86_64-linux-gnu/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking --enable-glibc-back-compat --enable-reduce-exports --disable-bench --disable-gui-tests CFLAGS="-O2 -g" CXXFLAGS="-O2 -g" LDFLAGS="-static-libstdc++" make $MAKEOPTS make -C src check-security make -C src check-symbols mkdir ~/linux64 make install DESTDIR=~/linux64/$DISTNAME cd ~/linux64 find . -name "lib*.la" -delete find . -name "lib*.a" -delete rm -rf $DISTNAME/lib/pkgconfig find ${DISTNAME}/bin -type f -executable -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find ${DISTNAME}/lib -type f -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find $DISTNAME/ -not -name "*.dbg" | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/release/$DISTNAME-x86_64-linux-gnu.tar.gz cd ~/quartercoin rm -rf ~/linux64 make clean export PATH=$PATH_orig echo @@@ echo @@@"Building general sourcecode" echo @@@ cd ~/quartercoin export PATH=$PWD/depends/x86_64-linux-gnu/native/bin:$PATH ./autogen.sh CONFIG_SITE=$PWD/depends/x86_64-linux-gnu/share/config.site ./configure --prefix=/ make dist SOURCEDIST=`echo quartercoin-*.tar.gz` mkdir -p ~/quartercoin/temp cd ~/quartercoin/temp tar xf ../$SOURCEDIST find quartercoin-* | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ../$SOURCEDIST cd ~/quartercoin mv $SOURCEDIST ~/release rm -rf temp make clean export PATH=$PATH_orig echo @@@ echo @@@"Building linux 32 binaries" echo @@@ cd ~/ mkdir -p ~/wrapped/extra_includes/i686-pc-linux-gnu ln -s /usr/include/x86_64-linux-gnu/asm ~/wrapped/extra_includes/i686-pc-linux-gnu/asm for prog in gcc g++; do rm -f ~/wrapped/${prog} cat << EOF > ~/wrapped/${prog} #!/usr/bin/env bash REAL="`which -a ${prog} | grep -v $PWD/wrapped/${prog} | head -1`" for var in "\$@" do if [ "\$var" = "-m32" ]; then export C_INCLUDE_PATH="$PWD/wrapped/extra_includes/i686-pc-linux-gnu" export CPLUS_INCLUDE_PATH="$PWD/wrapped/extra_includes/i686-pc-linux-gnu" break fi done \$REAL \$@ EOF chmod +x ~/wrapped/${prog} done export PATH=$PWD/wrapped:$PATH export HOST_ID_SALT="$PWD/wrapped/extra_includes/i386-linux-gnu" cd ~/quartercoin/depends make HOST=i686-pc-linux-gnu $MAKEOPTS unset HOST_ID_SALT cd ~/quartercoin export PATH=$PWD/depends/i686-pc-linux-gnu/native/bin:$PATH ./autogen.sh CONFIG_SITE=$PWD/depends/i686-pc-linux-gnu/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking --enable-glibc-back-compat --enable-reduce-exports --disable-bench --disable-gui-tests CFLAGS="-O2 -g" CXXFLAGS="-O2 -g" LDFLAGS="-static-libstdc++" make $MAKEOPTS make -C src check-security make -C src check-symbols mkdir -p ~/linux32 make install DESTDIR=~/linux32/$DISTNAME cd ~/linux32 find . -name "lib*.la" -delete find . -name "lib*.a" -delete rm -rf $DISTNAME/lib/pkgconfig find ${DISTNAME}/bin -type f -executable -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find ${DISTNAME}/lib -type f -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find $DISTNAME/ -not -name "*.dbg" | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/release/$DISTNAME-i686-pc-linux-gnu.tar.gz cd ~/quartercoin rm -rf ~/linux32 rm -rf ~/wrapped make clean export PATH=$PATH_orig echo @@@ echo @@@ "Building linux ARM binaries" echo @@@ cd ~/quartercoin/depends make HOST=arm-linux-gnueabihf $MAKEOPTS cd ~/quartercoin export PATH=$PWD/depends/arm-linux-gnueabihf/native/bin:$PATH ./autogen.sh CONFIG_SITE=$PWD/depends/arm-linux-gnueabihf/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking --enable-glibc-back-compat --enable-reduce-exports --disable-bench --disable-gui-tests CFLAGS="-O2 -g" CXXFLAGS="-O2 -g" LDFLAGS="-static-libstdc++" make $MAKEOPTS make -C src check-security mkdir -p ~/linuxARM make install DESTDIR=~/linuxARM/$DISTNAME cd ~/linuxARM find . -name "lib*.la" -delete find . -name "lib*.a" -delete rm -rf $DISTNAME/lib/pkgconfig find ${DISTNAME}/bin -type f -executable -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find ${DISTNAME}/lib -type f -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find $DISTNAME/ -not -name "*.dbg" | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/release/$DISTNAME-arm-linux-gnueabihf.tar.gz cd ~/quartercoin rm -rf ~/linuxARM make clean export PATH=$PATH_orig echo @@@ echo @@@ "Building linux aarch64 binaries" echo @@@ cd ~/quartercoin/depends make HOST=aarch64-linux-gnu $MAKEOPTS cd ~/quartercoin export PATH=$PWD/depends/aarch64-linux-gnu/native/bin:$PATH ./autogen.sh CONFIG_SITE=$PWD/depends/aarch64-linux-gnu/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking --enable-glibc-back-compat --enable-reduce-exports --disable-bench --disable-gui-tests CFLAGS="-O2 -g" CXXFLAGS="-O2 -g" LDFLAGS="-static-libstdc++" make $MAKEOPTS make -C src check-security mkdir -p ~/linuxaarch64 make install DESTDIR=~/linuxaarch64/$DISTNAME cd ~/linuxaarch64 find . -name "lib*.la" -delete find . -name "lib*.a" -delete rm -rf $DISTNAME/lib/pkgconfig find ${DISTNAME}/bin -type f -executable -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find ${DISTNAME}/lib -type f -exec ../quartercoin/contrib/devtools/split-debug.sh {} {} {}.dbg \; find $DISTNAME/ -not -name "*.dbg" | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/release/$DISTNAME-aarch64-linux-gnu.tar.gz cd ~/quartercoin rm -rf ~/linuxaarch64 make clean export PATH=$PATH_orig echo @@@ echo @@@ "Building windows 64 binaries" echo @@@ update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix mkdir -p ~/release/unsigned/ mkdir -p ~/sign/win64 PATH=$(echo "$PATH" | sed -e 's/:\/mnt.*//g') # strip out problematic Windows %PATH% imported var cd ~/quartercoin/depends make HOST=x86_64-w64-mingw32 $MAKEOPTS cd ~/quartercoin export PATH=$PWD/depends/x86_64-w64-mingw32/native/bin:$PATH ./autogen.sh CONFIG_SITE=$PWD/depends/x86_64-w64-mingw32/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking --enable-reduce-exports --disable-bench --disable-gui-tests CFLAGS="-O2 -g" CXXFLAGS="-O2 -g" make $MAKEOPTS make -C src check-security make deploy rename 's/-setup\.exe$/-setup-unsigned.exe/' *-setup.exe cp -f quartercoin-*setup*.exe ~/release/unsigned/ mkdir -p ~/win64 make install DESTDIR=~/win64/$DISTNAME cd ~/win64 mv ~/win64/$DISTNAME/bin/*.dll ~/win64/$DISTNAME/lib/ find . -name "lib*.la" -delete find . -name "lib*.a" -delete rm -rf $DISTNAME/lib/pkgconfig find $DISTNAME/bin -type f -executable -exec x86_64-w64-mingw32-objcopy --only-keep-debug {} {}.dbg \; -exec x86_64-w64-mingw32-strip -s {} \; -exec x86_64-w64-mingw32-objcopy --add-gnu-debuglink={}.dbg {} \; find ./$DISTNAME -not -name "*.dbg" -type f | sort | zip -X@ ./$DISTNAME-x86_64-w64-mingw32.zip mv ./$DISTNAME-x86_64-*.zip ~/release/$DISTNAME-win64.zip cd ~/ rm -rf win64 cp -rf quartercoin/contrib/windeploy ~/sign/win64 cd ~/sign/win64/windeploy mkdir -p unsigned mv ~/quartercoin/quartercoin-*setup-unsigned.exe unsigned/ find . | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/sign/$DISTNAME-win64-unsigned.tar.gz cd ~/sign rm -rf win64 cd ~/quartercoin rm -rf release make clean export PATH=$PATH_orig echo @@@ echo @@@ "Building windows 32 binaries" echo @@@ update-alternatives --set i686-w64-mingw32-g++ /usr/bin/i686-w64-mingw32-g++-posix mkdir -p ~/sign/win32 PATH=$(echo "$PATH" | sed -e 's/:\/mnt.*//g') cd ~/quartercoin/depends make HOST=i686-w64-mingw32 $MAKEOPTS cd ~/quartercoin export PATH=$PWD/depends/i686-w64-mingw32/native/bin:$PATH ./autogen.sh CONFIG_SITE=$PWD/depends/i686-w64-mingw32/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking --enable-reduce-exports --disable-bench --disable-gui-tests CFLAGS="-O2 -g" CXXFLAGS="-O2 -g" make $MAKEOPTS make -C src check-security make deploy rename 's/-setup\.exe$/-setup-unsigned.exe/' *-setup.exe cp -f quartercoin-*setup*.exe ~/release/unsigned/ mkdir -p ~/win32 make install DESTDIR=~/win32/$DISTNAME cd ~/win32 mv ~/win32/$DISTNAME/bin/*.dll ~/win32/$DISTNAME/lib/ find . -name "lib*.la" -delete find . -name "lib*.a" -delete rm -rf $DISTNAME/lib/pkgconfig find $DISTNAME/bin -type f -executable -exec i686-w64-mingw32-objcopy --only-keep-debug {} {}.dbg \; -exec i686-w64-mingw32-strip -s {} \; -exec i686-w64-mingw32-objcopy --add-gnu-debuglink={}.dbg {} \; find ./$DISTNAME -not -name "*.dbg" -type f | sort | zip -X@ ./$DISTNAME-i686-w64-mingw32.zip mv ./$DISTNAME-i686-w64-*.zip ~/release/$DISTNAME-win32.zip cd ~/ rm -rf win32 cp -rf quartercoin/contrib/windeploy ~/sign/win32 cd ~/sign/win32/windeploy mkdir -p unsigned mv ~/quartercoin/quartercoin-*setup-unsigned.exe unsigned/ find . | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/sign/$DISTNAME-win32-unsigned.tar.gz cd ~/sign rm -rf win32 cd ~/quartercoin rm -rf release make clean export PATH=$PATH_orig echo @@@ echo @@@ "Building OSX binaries" echo @@@ mkdir -p ~/quartercoin/depends/SDKs cp ~/MacOSX10.11.sdk.tar.gz ~/quartercoin/depends/SDKs/MacOSX10.11.sdk.tar.gz cd ~/quartercoin/depends/SDKs && tar -xf MacOSX10.11.sdk.tar.gz rm -rf MacOSX10.11.sdk.tar.gz cd ~/quartercoin/depends make $MAKEOPTS HOST="x86_64-apple-darwin14" cd ~/quartercoin ./autogen.sh CONFIG_SITE=$PWD/depends/x86_64-apple-darwin14/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking --enable-reduce-exports --disable-bench --disable-gui-tests GENISOIMAGE=$PWD/depends/x86_64-apple-darwin14/native/bin/genisoimage make $MAKEOPTS mkdir -p ~/OSX export PATH=$PWD/depends/x86_64-apple-darwin14/native/bin:$PATH make install-strip DESTDIR=~/OSX/$DISTNAME make osx_volname make deploydir mkdir -p unsigned-app-$DISTNAME cp osx_volname unsigned-app-$DISTNAME/ cp contrib/macdeploy/detached-sig-apply.sh unsigned-app-$DISTNAME cp contrib/macdeploy/detached-sig-create.sh unsigned-app-$DISTNAME cp $PWD/depends/x86_64-apple-darwin14/native/bin/dmg $PWD/depends/x86_64-apple-darwin14/native/bin/genisoimage unsigned-app-$DISTNAME cp $PWD/depends/x86_64-apple-darwin14/native/bin/x86_64-apple-darwin14-codesign_allocate unsigned-app-$DISTNAME/codesign_allocate cp $PWD/depends/x86_64-apple-darwin14/native/bin/x86_64-apple-darwin14-pagestuff unsigned-app-$DISTNAME/pagestuff mv dist unsigned-app-$DISTNAME cd unsigned-app-$DISTNAME find . | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/sign/$DISTNAME-osx-unsigned.tar.gz cd ~/quartercoin make deploy $PWD/depends/x86_64-apple-darwin14/native/bin/dmg dmg "Quartercoin-Core.dmg" ~/release/unsigned/$DISTNAME-osx-unsigned.dmg rm -rf unsigned-app-$DISTNAME dist osx_volname dpi36.background.tiff dpi72.background.tiff cd ~/OSX find . -name "lib*.la" -delete find . -name "lib*.a" -delete rm -rf $DISTNAME/lib/pkgconfig find $DISTNAME | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ~/release/$DISTNAME-osx64.tar.gz cd ~/quartercoin rm -rf ~/OSX make clean export PATH=$PATH_orig
bool isMultiple(int n1, int n2) { return n2 % n1 == 0; } isMultiple(4, 8); // Returns true
class CheckPrime { public static void main(String[] args) { int i=10; int temp=0; for (int j=2;j<i ;j++ ) { if (i%j==0) { temp=temp+1; } } if (temp==0) { System.out.println("It is aPrime Number"); } else { System.out.println("It is not a Prime Number"); } } }
package com.leetcode; import java.util.*; public class Solution_102 { public List<List<Integer>> levelOrder(TreeNode root) { if (root == null) return Collections.emptyList(); List<List<Integer>> list = new ArrayList<>(); Deque<TreeNode> deque = new LinkedList<>(); deque.offerLast(root); while (!deque.isEmpty()) { bfs(list, deque); } return list; } private void bfs(List<List<Integer>> list, Deque<TreeNode> deque) { int size = deque.size(); List<Integer> integers = new LinkedList<>(); for (int i = 0; i < size; i++) { TreeNode treeNode = deque.pollFirst(); if (treeNode.left != null) deque.offerLast(treeNode.left); if (treeNode.right != null) deque.offerLast(treeNode.right); integers.add(treeNode.val); } list.add(integers); } }
import imaplib import poplib def get_incoming_mail_port(doc): if doc.protocol == "IMAP": doc.incoming_port = imaplib.IMAP4_SSL_PORT if doc.use_ssl else imaplib.IMAP4_PORT else: doc.incoming_port = poplib.POP3_SSL_PORT if doc.use_ssl else poplib.POP3_PORT return int(doc.incoming_port)
<reponame>xuzhijvn/spring-boot-tony-starters /* * Copyright© (2020). */ package com.tony.component.advice; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; /** * @author tony * @create 2021-12-26 * @description: */ public abstract class AbstractAfterReturningAdvisor implements Advisor { @Override public void before(JoinPoint jp) { } @Override public Object around(ProceedingJoinPoint pjp) throws Throwable { return null; } @Override public void after(JoinPoint jp) { } /** * afterReturning advice * * @param jp * @param retVal */ @Override public abstract void afterReturning(JoinPoint jp, Object retVal); @Override public void afterThrowing(JoinPoint jp, Throwable ex) { } }
#!/bin/bash echo "---> Configuring Puppetserver to accept SSL verification headers" sed -i 's/version: 1/version: 1\n allow-header-cert-info: true/' /etc/puppetlabs/puppetserver/conf.d/auth.conf
#! /bin/bash # # script.sh - Descrição sucinta # # Site: # Autor: # Manutenção: # # --------------------------------------------------------------------------- # # # Descrição: # # Uso: # script.sh [opções] parâmetro1 # # Exemplos: # $ script.sh -h -f teste # # Descrição Adicional: # Este script faz isso, desta forma, etc. # # --------------------------------------------------------------------------- # # # Histórico: # # 25/04/2021 Versão 1.0: Feito isso, isso, isso, isso # mais isso e isso e isso... # # NOTA: A nomenclatura da versão é usada pelo parâmetro -V para extrair # a versão atual automaticamente. Lembrar de ajustar caso for mudado. # # Licença: MIT # # --------------------------------------------------------------------------- # # # ---------[ Flags ]--------------------------------------------------------- # # # flag1=1 # # Sugestões de teste da flag # # 1) [ "$flag1" = 1 ] && echo "Chave Ligada" # # 2) test "$flag1" = 1 && echo "Chave Ligada" # # 3) if test "$flag1" = 1 # then # <...> # else # <...> # fi # # NOTA: Valor 1 liga chave. Qualquer outro valor desliga a chave # # ---------[ Opções de linha de comando ]------------------------------------ # # MENSAGEM_USO=" Uso: $0 [OPÇÕES] OPÇÔES: -h, --help Mostra essa ajuda e sai -V, --version Mostra a versão atual do script e sai " # Tratamento while test -n "$1" do case "$1" in -h | --help) echo "$MENSAGEM_USO" exit 0 ;; -V | --version) echo -n $(basename "$0")" " grep -E "^#\s+[0-9]+\/[0-9]+\/[0-9]+\sVersão\s+[0-9]+\.[0-9]+\:" tpt_bash.sh | tail -1 | grep -Eo "Versão\s+[0-9]+\.[0-9]+" exit 0 ;; # Opções que controlam flag # -f | --flag ) flag1=1 ;; # # Opções com argumentos: -p argumento # # -p | --parametro ) # shift # argumento="$1" # # if test -z "$argumento" # then # echo "Faltou o argumento para opção -p" #;; esac shift done # # ---------[ Declaração de variáveis ]--------------------------------------- # declare -rx SCRIPT=$(basename "$0") # ---------[ Verificação de sanidade ]--------------------------------------- # if test -z "$BASH"; then echo "$SCRIPT: erro na linha $LINENO\nNão garanto que esse script funcione em outro shell que não seja o BASH." exit 192 fi # ---------[ Início do programa ]-------------------------------------------- # echo "Hello World!" # ---------[ Fim do programa ]----------------------------------------------- # # ---------[ Limpeza ]------------------------------------------------------- # exit 0 # # #
#!/bin/bash # Dump uuids from the infoton table, including the parent flag. if [ -z $1 ]; then echo "usage: $0 <cmwell-url>" exit 1 fi source ./set-runtime.sh WORKING_DIRECTORY="dump-uuids" rm -rf "${WORKING_DIRECTORY}/infoton" $SPARK_HOME/bin/spark-submit \ --conf "spark.driver.extraJavaOptions=-XX:+UseG1GC" \ --master "${SPARK_MASTER}" --driver-memory ${SPARK_MEMORY} --conf "spark.local.dir=${SPARK_TMP}" \ --class "cmwell.analytics.main.DumpInfotonWithParentFlag" "${SPARK_ANALYSIS_JAR}" \ --out "${WORKING_DIRECTORY}/infoton-with-parent-flag" \ $@
class DonationAddStore < ActiveRecord::Migration[5.0] def up add_column :donations, :store, :string end def down remove_column :donations, :store end end
import nltk def get_synonyms(sentence): output = [] words = nltk.word_tokenize(sentence) for word in words: synonyms = [] for syn in wordnet.synsets(word): for l in syn.lemmas(): synonyms.append(l.name()) output.append(list(set(synonyms))) return output
#!/bin/bash citeurl makejs -o citeurl.js zip -r gnome-citeurl-search-provider@raindrum.github.io.zip extension.js citeurl.js logo.svg metadata.json LICENSE.md README.md screenshot.png
import React from "react"; import projects from "../utils/projects.json" import Row from "../components/Row" import 'bootstrap/dist/css/bootstrap.min.css'; import { Card, Button } from "react-bootstrap"; import Image from "react-bootstrap/Image" function Project() { return ( <Row xs={5} md={5} className="g-6"> {projects.map((project) => { return ( <Card key={project.id} className="card bg-dark"> <Image className= "w-50 rounded mx-auto d-block" variant = "card-img-top" src={project.image} alt={project.name + " screenshot"} /> <div className="text-center text-white"> <Card.Body> <Card.Title className="card-title"> {project.name} </Card.Title> <h5 className="card-text">{project.description}</h5> <h6>Using {project.tech}</h6> <h6> <Button variant="dark text-light" href={project.repo} target="_blank" rel="noreferrer"> GitHub Repository </Button> <div></div> <div></div> <Button variant="dark text-light" href={project.link} target="_blank" rel="noreferrer"> Application Link (If applicable) </Button> </h6> </Card.Body> </div> </Card> ); })} </Row> ); } export default Project;
// good enough at init // export default function(state, action) { // return state || {} // } import { combineReducers } from 'redux'; import * as actionTypes from './actionTypes' const DEFAULT_AUTH = { username: null, isPending: false } function auth(state, action) { switch(action.type) { case actionTypes.LOGIN_START: return { ...state, username: null, isPending: true } case actionTypes.LOGIN_END: return action.error ? { ...state, username: null, isPending: false } : { ...state, username: action.payload.username, isPending: false} // after dispatch the data is in payload ^^ case actionTypes.LOGOUT: return DEFAULT_AUTH default: return state || DEFAULT_AUTH } } const DEFAULT_POSTS = { posts: [], isPending: false } function projects(state, action) { switch(action.type) { case actionTypes.READ_POSTS_START: return { ...state, posts: null, isPending: true } case actionTypes.READ_POSTS_END: return action.error ? { ...state, posts: null, isPending: false } // overwrite old posts list with new fetched posts list : { ...state, posts: action.payload.posts, isPending: false} default: return state || DEFAULT_POSTS } } export default combineReducers({ auth, projects });
#!/bin/bash # # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. set -e # Check for zip if ! command -v zip &> /dev/null; then echo "zip could not be found. This script requires zip." echo "On debian based distributions you can try this to install it: sudo apt install zip" exit 1 fi
<filename>uva/00200.cc // https://uva.onlinejudge.org/external/2/200.pdf #include<bits/stdc++.h> using namespace std; using vi=vector<int>; using vvi=vector<vi>; using vs=vector<string>; int main(){ ios::sync_with_stdio(0); cin.tie(0); for(;;){ string s; getline(cin,s); if(s.empty())break; vs t; for(;;){ if(s[0]=='#')break; t.push_back(s); getline(cin,s); } vi p(128),m(128); string q; for(auto &s:t){ for(auto c:s){ p[c]++; } } int n=0; for(int i='A';i<='Z';i++) if(p[i]){ m[i]=n++; q.push_back(i); } vvi g(n); for(int i=0;i<t.size()-1;i++){ string &a=t[i],&b=t[i+1]; for(int j=0;j<min(a.size(),b.size());j++) if(a[j]!=b[j]){ g[m[a[j]]].push_back(m[b[j]]); break; } } vi w(n),x; function<void(int)>dfs=[&](int u){ w[u]=1; for(int v:g[u]) if(!w[v]) dfs(v); x.push_back(u); }; for(int i=0;i<n;i++) if(!w[i]) dfs(i); reverse(x.begin(),x.end()); for(int i=0;i<n;i++) cout<<q[x[i]]; cout<<"\n"; } }
<filename>src/tallies.ts import { parseTokenString } from "./utils"; import { TallyStats, EosioDelband, EosioVoter } from "./interfaces"; import { ForumVote } from "./interfaces_forum"; import { AuditorVote } from "./interfaces_auditor"; export function defaultAccount() { return { votes: {}, staked: 0, proxy: "", is_proxy: false, }; } export function defaultStats(block_num: number): TallyStats { return { votes: { total: 0, proxies: 0, accounts: 0, }, accounts: { 0: 0, 1: 0, total: 0, }, proxies: { 0: 0, 1: 0, total: 0, }, staked: { 0: 0, 1: 0, total: 0, }, block_num, }; } export function countStaked(delband: EosioDelband) { if (!delband) return 0; const cpu = parseTokenString(delband.cpu_weight).amount; const net = parseTokenString(delband.net_weight).amount; return cpu + net; } export function filterVotersByVotes(voters: EosioVoter[], forum_votes: ForumVote[], auditor_votes: AuditorVote[]) { const results: EosioVoter[] = []; const voted = new Set(); // Only track accounts who has casted votes for (const row of forum_votes) { voted.add(row.voter); } for (const row of auditor_votes) { voted.add(row.voter); } for (const row of voters) { const owner = row.owner; // Voter is only included if voted or proxied to a proxy who has voted if (voted.has(owner) || voted.has(row.proxy)) results.push(row); } return results; }
<reponame>2011-team-coco/quicklys-shop<filename>client/components/Cart.js<gh_stars>1-10 /* eslint-disable no-useless-constructor */ import React from 'react' import {connect} from 'react-redux' import {Grid, Paper, CardHeader, Typography, Divider} from '@material-ui/core' import CartItem from './CartItem' import CartOrder from './CartOrder' export class Cart extends React.Component { constructor(props) { super(props) } componentDidMount() {} render() { const classes = { cart: { height: '100vh', }, paper: { // height: '100vh', }, details: { paddingLeft: '24px', }, innerGrid: { paddingTop: '20px', paddingBottom: '20px', }, } return ( <div style={classes.cart}> <Grid style={classes.cart} container spacing={2}> <Grid item xs={12} sm={8}> <Paper style={classes.paper}> <CardHeader title="Shopping Cart"></CardHeader> <Divider></Divider> <Grid container style={classes.innerGrid} spacing={2}> <Grid item xs={6}> <Typography style={classes.details} variant="subtitle1"> Product Details </Typography> </Grid> <Grid item xs={2}> <Typography variant="subtitle1">Quantity</Typography> </Grid> <Grid item xs={2}> <Typography variant="subtitle1">Price</Typography> </Grid> <Grid item xs={2}> <Typography variant="subtitle1">Total</Typography> </Grid> </Grid> <Divider></Divider> {this.props.cart.order_candies.map((orderCandy) => { return ( <CartItem key={orderCandy.candy.candyId} orderCandy={orderCandy} userId={this.props.userId} isLoggedIn={this.props.isLoggedIn} ></CartItem> ) })} </Paper> </Grid> <Grid item xs={12} sm={4}> <CartOrder cart={this.props.cart} isLoggedIn={this.props.isLoggedIn} ></CartOrder> </Grid> </Grid> </div> ) } } const mapState = (state) => { return { cart: state.cart, userId: state.user.id, //coercing into boolean to see if user is logged in isLoggedIn: !!state.user.id, } } export default connect(mapState)(Cart)
import random import string random_string = ''.join(random.choice(string.ascii_uppercase) for _ in range(10)) print(random_string)
#!/bin/bash set -ev if [ "$#" -ne 1 ]; then echo "Illegal number of parameters" exit 1 fi if [ "$1" = "f710" ]; then ROOTFS=fedora-arm-artik710-rootfs-0710GC0F-44F-01QC-20170713.175433-f63a17cbfdaffd3385f23ea12388999a.tar.gz URL=https://github.com/SamsungARTIK/fedora-spin-kickstarts/releases/download/release%2FA710_os_2.2.0/$ROOTFS elif [ "$1" = "f530" ]; then ROOTFS=fedora-arm-artik530-rootfs-0530GC0F-44F-01Q4-20170425.192021-1e007ebbf12d9c7499be3a4b9e9d8e6a.tar.gz URL=https://github.com/SamsungARTIK/fedora-spin-kickstarts/releases/download/release%2FA530_os_2.0.0/$ROOTFS elif [ "$1" = "f520" ]; then ROOTFS=fedora-arm-artik5-rootfs-0520GC0F-3AF-01Q6-20160928.203457-0e632fcf9ee1badf5724751af6bd0670.tar.gz URL=https://github.com/SamsungARTIK/fedora-spin-kickstarts/releases/download/release%2FA520_os_2.0.0/$ROOTFS else echo "Not supported target: $1" exit 1 fi if [ "$1" = "f520" ]; then # 520 not support artik.repo SCRIPT="wget $URL \ && fed-artik-host-init-buildsys -I $ROOTFS \ && fed-artik-init-buildsys \ && rm $ROOTFS \ && sudo -H chroot_fedora /home/work/FED_ARTIK_ROOT/BUILDROOT \"dnf update -y\"" else SCRIPT="wget $URL \ && fed-artik-host-init-buildsys -I $ROOTFS \ && fed-artik-init-buildsys \ && rm $ROOTFS \ && sudo sed -i 's/#baseurl/baseurl/' /home/work/FED_ARTIK_ROOT/BUILDROOT/etc/yum.repos.d/artik.repo \ && sudo -H chroot_fedora /home/work/FED_ARTIK_ROOT/BUILDROOT \"dnf update -y\"" fi echo $SCRIPT docker pull webispy/artik_devenv # The "--privileged" option is required because we should run the # "mount --bind" command inside the container. docker run -t --privileged --name $1 webispy/artik_devenv bash -c "$SCRIPT" # Create a docker image using container docker commit --change='CMD ["zsh"]' $1 webispy/artik_devenv_$1 # Remove container docker rm $1
interface Metadata { color?: string; x?: string | number; y?: string | number; label?: string; file?: { url: string; md5: string; path: string; }; icon?: string; fixed_position?: { [key: string]: { color: string; icon: string; value: string; x: string; y: string; }; }; sentValues?: [{ label: string; value: string | number | boolean }]; [key: string]: any; } interface Data { id?: string; variable: string; value?: string | number | boolean | void; location?: { lat: number; lng: number }; metadata?: Metadata; serie?: string; unit?: string; origin: string; time: Date; created_at?: Date; } interface TagsObj { key: string; value: string; } type RecursivePartial<T> = { [P in keyof T]?: T[P] extends (infer U)[] ? RecursivePartial<U>[] : T[P] extends object ? RecursivePartial<T[P]> : T[P]; }; interface Query<T, U> { /** * Page of list starting from 1 */ page?: number; /** * Amount of items will return. */ amount?: number; /** * Array of field names. */ fields?: (keyof T)[]; /** * Filter object. */ filter?: RecursivePartial<T>; /** * Tuple with a field and an order */ orderBy?: [Extract<keyof T, U>, "asc" | "desc"]; } /** * ID used on TagoIO, string with 24 character */ type GenericID = string; /** * Token used on TagoIO, string with 36 characters */ type GenericToken = string; type Base64 = string; type PermissionOption = "write" | "read" | "full" | "deny"; type ExpireTimeOption = "never" | Date; type ExportOption = "csv" | "json" | "xml"; type Conditionals = "<" | ">" | "=" | "!" | "><" | "*"; type RunTypeOptions = "node" | "python"; type TokenCreateResponse = { token: GenericToken; expire_date: ExpireTimeOption; permission: PermissionOption }; type RefType = "dashboard"; interface TokenDataList { token: GenericToken; name: string; type: string; permission: PermissionOption; serie_number: string | null; last_authorization: Date | null; verification_code: string | null; expire_time: ExpireTimeOption; ref_id: string; created_at: Date; created_by: string | null; } interface TokenData { /** * A name for the token. */ name: string; /** * The time for when the token should expire. * It will be randomly generated if not included. * Accepts “never” as value. */ expire_time?: ExpireTimeOption; /** * Token permission should be 'write', 'read' or 'full'. */ permission: PermissionOption; /** * [optional] The serial number of the device. */ serie_number?: string; /** * [optional] Verification code to validate middleware requests. */ verification_code?: string; /** * [optional] Middleware or type of the device that will be added. */ middleware?: string; } interface ListTokenQuery extends Query<TokenDataList, "name" | "permission" | "serie_number" | "verification_code" | "created_at"> {} export { Data, TagsObj, Query, Base64, GenericID, GenericToken, PermissionOption, ExpireTimeOption, ExportOption, Conditionals, TokenCreateResponse, RunTypeOptions, RefType, ListTokenQuery, TokenData, TokenDataList, RecursivePartial, };
import pytest from nbstripout._utils import pop_recursive def testdict(): return {'a': {'b': 1, 'c': 2, 'd.e': 3, 'f': {'g': 4}}} def testdata(default=None): return [ ('a.c', 2, {'a': {'b': 1, 'd.e': 3, 'f': {'g': 4}}}), ('a.d.e', 3, {'a': {'b': 1, 'c': 2, 'f': {'g': 4}}}), ('a.f', {'g': 4}, {'a': {'b': 1, 'c': 2, 'd.e': 3}}), ('a.f.g', 4, {'a': {'b': 1, 'c': 2, 'd.e': 3, 'f': {}}}), ('a', {'b': 1, 'c': 2, 'd.e': 3, 'f': {'g': 4}}, {}), ('notfound', default, testdict()), ('a.notfound', default, testdict()), ('a.b.notfound', default, testdict()), ] @pytest.fixture def d(): return testdict() @pytest.mark.parametrize(('key', 'res', 'remainder'), testdata()) def test_pop_recursive(d, key, res, remainder): assert pop_recursive(d, key) == res assert d == remainder @pytest.mark.parametrize(('key', 'res', 'remainder'), testdata(default=0)) def test_pop_recursive_default(d, key, res, remainder): assert pop_recursive(d, key, default=0) == res assert d == remainder
class VersionControlSystem: def __init__(self): self._version_number_objects = {} def _object_has_version(self, key, version_number): if version_number not in self._version_number_objects: self._version_number_objects[version_number] = set() self._version_number_objects[version_number].add(key)
#!/bin/bash set -o nounset set -o errexit set -o pipefail set -x # This value serves as a default when the parameters are not set, which should # only happen in rehearsals. Production jobs should always set the OO_* variable. REHEARSAL_BUNDLE="brew.registry.redhat.io/rh-osbs-stage/e2e-e2e-test-operator-bundle-container:8.0-3" OO_BUNDLE="${OO_BUNDLE:-$REHEARSAL_BUNDLE}" OPENSHIFT_AUTH="${OPENSHIFT_AUTH:-/var/run/brew-pullsecret/.dockerconfigjson}" SCORECARD_CONFIG="${SCORECARD_CONFIG:-/tmp/config/scorecard-basic-config.yml}" # Steps for running the basic operator-sdk scorecard test # Expects the standard Prow environment variables to be set and # the brew proxy registry credentials to be mounted NAMESPACE=$(grep "install_namespace:" "${SHARED_DIR}"/oo_deployment_details.yaml | cut -d ':' -f2 | xargs) pushd "${ARTIFACT_DIR}" OPERATOR_DIR="test-operator-basic" echo "Starting the basic operator-sdk scorecard test for ${OO_BUNDLE}" echo "Extracting the operator bundle image into the operator directory" mkdir -p "${OPERATOR_DIR}" pushd "${OPERATOR_DIR}" oc image extract "${OO_BUNDLE}" --confirm -a "${OPENSHIFT_AUTH}" chmod -R go+r ./ popd echo "Extracted the following bundle data:" tree "${OPERATOR_DIR}" echo "Running the operator-sdk scorecard test using the basic configuration, json output and storing it in the artifacts directory" operator-sdk scorecard --config "${SCORECARD_CONFIG}" \ --namespace "${NAMESPACE}" \ --kubeconfig "${KUBECONFIG}" \ --output json \ "${OPERATOR_DIR}" > "${ARTIFACT_DIR}"/scorecard-output-basic.json || true
import React, { useState } from 'react'; const SentenceGenerator = () => { const inputArray = ["hello","world","this","is","a","test"]; const [sentence, setSentence] = useState(""); const generateSentence = () => { let sentenceArr = []; for (let i = 0; i < 4; i++) { let randomIndex = Math.floor(Math.random()*inputArray.length); sentenceArr.push(inputArray[randomIndex]); } let sentenceString = sentenceArr.join(" "); setSentence(sentenceString); } return ( <div> <h2>Random Sentence Generator</h2> <button onClick={generateSentence}>Generate Sentence</button> <p>{sentence}</p> </div> ); }; export default SentenceGenerator;
#!/bin/sh set -e SOURCES_DIR=/tmp/artifacts/ DISTRO_NAME=standard-controller # unpack { unzip "${SOURCES_DIR}/standard-controller.zip" -d / }
'use strict'; // Configuring the Articles module angular.module('logos').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'Logos', 'logos', 'dropdown', '/logos(/create)?'); Menus.addSubMenuItem('topbar', 'logos', 'List Logos', 'logos'); Menus.addSubMenuItem('topbar', 'logos', 'New Logo', 'logos/create'); } ]);
#!/bin/bash ## script for 内存泄露检查 # ========== macOS ========== # https://github.com/LouisBrunner/valgrind-macos # brew tap LouisBrunner/valgrind # brew install --HEAD LouisBrunner/valgrind/valgrind # ========== linux ========== # https://www.valgrind.org/ # apt install valgrind NUM_THREADS=1 echo "Setting the Number of Threads=$NUM_THREADS Using an OpenMP Environment Variable" set OMP_NUM_THREADS=$NUM_THREADS ##### run test on MacOS or Linux valgrind --trace-children=yes --tool=memcheck --leak-check=full --leak-resolution=med --track-origins=yes --vgdb=no --log-file=valgrind-memcheck.txt \ java -Djava.library.path=. -jar BaiPiaoOcrOnnxJvm.jar models \ ch_ppocr_server_v2.0_det_infer.onnx \ ch_ppocr_mobile_v2.0_cls_infer.onnx \ ch_ppocr_server_v2.0_rec_infer.onnx \ ppocr_keys_v1.txt \ images/1.jpg \ $NUM_THREADS \ 0 \ 1024 \ 0.5 \ 0.3 \ 1.6 \ 1 \ 0 #models #det #cls #rec #keys #image #numThread #padding #maxSideLen #boxScoreThresh #boxThresh #unClipRatio #doAngle #mostAngle
<reponame>WernerStruis/Naval-Robocode-Source package robocode; import robocode.naval.*; import robocode.naval.Components.ComponentBase; import robocode.naval.interfaces.componentInterfaces.IComponent; import robocode.robotinterfaces.peer.IBasicShipPeer; /** * @author <NAME>. /<NAME> (contributor naval) * @version 0.3 * @since 1.8.3.0 Alpha 1 */ public abstract class CarrierShip<SLOT1 extends IComponent, SLOT2 extends IComponent, SLOT3 extends IComponent, SLOT4 extends IComponent> extends Ship { //method to get user defined component types for all slots private void initSlots() { setSlot(ComponentManager.SLOT1, setSlot1()); setSlot(ComponentManager.SLOT2, setSlot2()); setSlot(ComponentManager.SLOT3, setSlot3()); setSlot(ComponentManager.SLOT4, setSlot4()); } //method to set all user defined component types private void setSlot(int slotIndex, IComponent component) { if (peer != null) { ((IBasicShipPeer) peer).setSlot(slotIndex, (ComponentBase) component); } else { uninitializedException(); } } //method to get all user defined component types private ComponentBase getSlot(int slotIndex){ if (peer != null) { return ((IBasicShipPeer) peer).getSlot(slotIndex); } else { uninitializedException(); } return null; } //set the different component types for every slot public abstract SLOT1 setSlot1(); public abstract SLOT2 setSlot2(); public abstract SLOT3 setSlot3(); public abstract SLOT4 setSlot4(); //get the diffrent component at slots; public final SLOT1 slot1(){ return (SLOT1) getSlot(ComponentManager.SLOT1) ; } //get the diffrent component at slots; public final SLOT2 slot2(){ return (SLOT2) getSlot(ComponentManager.SLOT2) ; } //get the diffrent component at slots; public final SLOT3 slot3(){ return (SLOT3) getSlot(ComponentManager.SLOT3) ; } //get the diffrent component at slots; public final SLOT4 slot4(){ return (SLOT4) getSlot(ComponentManager.SLOT4) ; } /** * Ship methods */ @Override public final double getXMiddle() { return getX() + (ShipType.CRUISER.getProwOffset() * Math.cos(getBodyHeadingRadians() + Math.PI/2)); } @Override public final double getYMiddle() { return getY() - (ShipType.CRUISER.getProwOffset() * Math.sin(getBodyHeadingRadians() + Math.PI/2)); } /** * This is the method you have to override to create your own ship. * super.run(); */ public void run() { super.run(); initSlots(); } }
class PropertyListing: def __init__(self, address, name, owner, kind, note): self.address = address self.name = name self.owner = owner self.kind = kind self.note = note def __str__(self): data = [self.address, self.name, self.owner, self.kind, self.note] return ';'.join(data) # Test the implementation property1 = PropertyListing("123 Main St", "Cozy Cottage", "John Doe", "House", "Near the lake") print(property1) # Output: "123 Main St;Cozy Cottage;John Doe;House;Near the lake"
if [ $# -eq 0 ] || [ $1 = "all" ] then make -f make_tc.log all make -f make_tc.log.tests all elif [ $1 = "clean" ] then make -f make_tc.log clean make -f make_tc.log.tests clean else echo "Use $0 or $0 all or $0 clean" fi
<reponame>ic-labs/glamkit-sponsors # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import icekit.validators class Migration(migrations.Migration): dependencies = [ ('icekit_plugins_image', '0006_auto_20160309_0453'), ] operations = [ migrations.CreateModel( name='Sponsor', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('url', models.CharField(help_text='It must start with `http://`, `https://` or be a relative URL starting with `/`', max_length=255, validators=[icekit.validators.RelativeURLValidator()], blank=True, verbose_name=b'URL')), ('logo', models.ForeignKey(to='icekit_plugins_image.Image')), ], ), ]