text
stringlengths
1
1.05M
<reponame>miyasiii/d3force-firestore<filename>public/js/ForceSimulationParameter.js export class ForceSimulationParameter{ constructor() { this._center = { x: 0.5, y: 0.5, strength: 1 } this._collide = { radius: 1, strength: 1, iterations: 1 } this._link = { distance: 30, // strength: 0.1, iterations: 1 } this._manyBody = { strength: -30, theta: 0.9, distanceMin: 1, distanceMax: Infinity } this._x = { x:0, strength: 0.1 } this._y = { y:0, strength: 0.1 } this.parametersDiv = d3.select("body").append("div").attr('id', "forceParameters"); this.centerDiv = this.parametersDiv.append("div").classed("force", true); this.centerDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("center"); this.centerDivXLabel = this.centerDiv.append("div").append("label").html("x:"); this.centerDivXOutput = this.centerDivXLabel.append("output").html(this.center.x); this.centerDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1.0) .attr("step", 0.1) .attr("value", this.center.x) .classed("range", true) .attr('id', "centerXValue") .on("input", ()=>{this.update()}); this.centerDivYLabel = this.centerDiv.append("div").append("label").html("y:"); this.centerDivYOutput = this.centerDivYLabel.append("output").html(this.center.y); this.centerDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1.0) .attr("step", 0.1) .attr("value", this.center.y) .classed("range", true) .attr('id', "centerYValue") .on("input", ()=>{this.update()}); this.centerDivStrengthLabel = this.centerDiv.append("div").append("label").html("strength:"); this.centerDivStrengthOutput = this.centerDivStrengthLabel.append("output").html(this.center.strength); this.centerDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1.0) .attr("step", 0.01) .attr("value", this.center.strength) .classed("range", true) .attr('id', "centerStrengthValue") .on("input", ()=>{this.update()}); this.collideDiv = this.parametersDiv.append("div").classed("force", true); this.collideDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("collide"); this.collideDivStrengthLabel = this.collideDiv.append("div").append("label").html("strength:"); this.collideDivStrengthOutput = this.collideDivStrengthLabel.append("output").html(this.collide.strength); this.collideDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 2) .attr("step", 0.1) .attr("value", this.collide.strength) .classed("range", true) .attr('id', "collideStrengthValue") .on("input", ()=>{this.update()}); this.collideDivRadiusLabel = this.collideDiv.append("div").append("label").html("radius:"); this.collideDivRadiusOutput = this.collideDivRadiusLabel.append("output").html(this.collide.radius); this.collideDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 100) .attr("step", 1) .attr("value", this.collide.radius) .classed("range", true) .attr('id', "collideRadiusValue") .on("input", ()=>{this.update()}); this.collideDivIterationsLabel = this.collideDiv.append("div").append("label").html("iterations:"); this.collideDivIterationsOutput = this.collideDivIterationsLabel.append("output").html(this.collide.iterations); this.collideDiv.append("input") .attr('type', "range") .attr("min", 1) .attr("max", 10) .attr("step", 1) .attr("value", this.collide.iterations) .classed("range", true) .attr('id', "collideIterationsValue") .on("input", ()=>{this.update()}); this.linkDiv = this.parametersDiv.append("div").classed("force", true); this.linkDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("link"); this.linkDivDistanceLabel = this.linkDiv.append("div").append("label").html("distance:"); this.linkDivDistanceOutput = this.linkDivDistanceLabel.append("output").html(this.link.distance); this.linkDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 100) .attr("step", 1) .attr("value", this.link.distance) .classed("range", true) .attr('id', "linkDistanceValue") .on("input", ()=>{this.update()}); this.linkDivIterationsLabel = this.linkDiv.append("div").append("label").html("iterations:"); this.linkDivIterationsOutput = this.linkDivIterationsLabel.append("output").html(this.link.iterations); this.linkDiv.append("input") .attr('type', "range") .attr("min", 1) .attr("max", 10) .attr("step", 1) .attr("value", this.link.iterations) .classed("range", true) .attr('id', "linkIterationsValue") .on("input", ()=>{this.update()}); this.manyBodyDiv = this.parametersDiv.append("div").classed("force", true); this.manyBodyDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("manyBody"); this.manyBodyDivStrengthLabel = this.manyBodyDiv.append("div").append("label").html("strength:"); this.manyBodyDivStrengthOutput = this.manyBodyDivStrengthLabel.append("output").html(this.manyBody.strength); this.manyBodyDiv.append("input") .attr('type', "range") .attr("min", -200) .attr("max", 200) .attr("step", 1) .attr("value", this.manyBody.strength) .classed("range", true) .attr('id', "manyBodyStrengthValue") .on("input", ()=>{this.update()}); this.manyBodyDivThetaLabel = this.manyBodyDiv.append("div").append("label").html("theta:"); this.manyBodyDivThetaOutput = this.manyBodyDivThetaLabel.append("output").html(this.manyBody.theta); this.manyBodyDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1) .attr("step", 0.1) .attr("value", this.manyBody.theta) .classed("range", true) .attr('id', "manyBodyThetahValue") .on("input", ()=>{this.update()}); this.manyBodyDivDistanceMinLabel = this.manyBodyDiv.append("div").append("label").html("distanceMin:"); this.manyBodyDivDistanceMinOutput = this.manyBodyDivDistanceMinLabel.append("output").html(this.manyBody.distanceMin); this.manyBodyDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 50) .attr("step", 0.1) .attr("value", this.manyBody.distanceMin) .classed("range", true) .attr('id', "manyBodyDistanceMinValue") .on("input", ()=>{this.update()}); this.manyBodyDivDistanceMaxLabel = this.manyBodyDiv.append("div").append("label").html("distanceMax:"); this.manyBodyDivDistanceMaxOutput = this.manyBodyDivDistanceMaxLabel.append("output").html(this.manyBody.distanceMax); this.manyBodyDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 2000) .attr("step", 0.1) .attr("value", this.manyBody.distanceMax) .classed("range", true) .attr('id', "manyBodyDistanceMaxValue") .on("input", ()=>{this.update()}); this.xDiv = this.parametersDiv.append("div").classed("force", true); this.xDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("x"); this.xDivXLabel = this.xDiv.append("div").append("label").html("x:"); this.xDivXOutput = this.xDivXLabel.append("output").html(this.x.x); this.xDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1) .attr("step", 0.01) .attr("value", this.x.x) .classed("range", true) .attr('id', "xXValue") .on("input", ()=>{this.update()}); this.xDivStrengthLabel = this.xDiv.append("div").append("label").html("strength:"); this.xDivStrengthOutput = this.xDivStrengthLabel.append("output").html(this.x.strength); this.xDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1) .attr("step", 0.01) .attr("value", this.x.strength) .classed("range", true) .attr('id', "xStrengthValue") .on("input", ()=>{this.update()}); this.yDiv = this.parametersDiv.append("div").classed("force", true); this.yDiv.append("div").style("text-align", "center").style("background-color", "#bbb").html("y"); this.yDivYLabel = this.yDiv.append("div").append("label").html("y:"); this.yDivYOutput = this.yDivYLabel.append("output").html(this.y.y); this.yDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1) .attr("step", 0.01) .attr("value", this.y.y) .classed("range", true) .attr('id', "yYValue") .on("input", ()=>{this.update()}); this.yDivStrengthLabel = this.yDiv.append("div").append("label").html("strength:"); this.yDivStrengthOutput = this.yDivStrengthLabel.append("output").html(this.y.strength); this.yDiv.append("input") .attr('type', "range") .attr("min", 0) .attr("max", 1) .attr("step", 0.01) .attr("value", this.y.strength) .classed("range", true) .attr('id', "yStrengthValue") .on("input", ()=>{this.update()}); } update(){ this.center = { x: d3.select("#centerXValue").property("value"), y: d3.select("#centerYValue").property("value"), strength: d3.select("#centerStrengthValue").property("value") } this.collide = { radius: d3.select("#collideRadiusValue").property("value"), strength: d3.select("#collideStrengthValue").property("value"), iterations: d3.select("#collideIterationsValue").property("value") } this.link = { distance: d3.select("#linkDistanceValue").property("value"), // strength: 0.1, iterations: d3.select("#linkIterationsValue").property("value") } this.manyBody = { strength: d3.select("#manyBodyStrengthValue").property("value"), theta: d3.select("#manyBodyThetahValue").property("value"), distanceMin: d3.select("#manyBodyDistanceMinValue").property("value"), distanceMax: d3.select("#manyBodyDistanceMaxValue").property("value") === "2000" ? Infinity : d3.select("#manyBodyDistanceMaxValue").property("value") === "1000" ? Infinity : d3.select("#manyBodyDistanceMaxValue").property("value") } this.x = { x: d3.select("#xXValue").property("value"), strength: d3.select("#xStrengthValue").property("value") } this.y = { y: d3.select("#yYValue").property("value"), strength: d3.select("#yStrengthValue").property("value") } this.centerDivXOutput.html(this.center.x); this.centerDivYOutput.html(this.center.y); this.centerDivStrengthOutput.html(this.center.strength); this.collideDivStrengthOutput.html(this.collide.strength); this.collideDivRadiusOutput.html(this.collide.radius); this.collideDivIterationsOutput.html(this.collide.iterations); this.linkDivDistanceOutput.html(this.link.distance); this.linkDivIterationsOutput.html(this.link.iterations); this.manyBodyDivStrengthOutput.html(this.manyBody.strength); this.manyBodyDivThetaOutput.html(this.manyBody.theta); this.manyBodyDivDistanceMinOutput.html(this.manyBody.distanceMin); this.manyBodyDivDistanceMaxOutput.html(this.manyBody.distanceMax); this.xDivXOutput.html(this.x.x); this.xDivStrengthOutput.html(this.x.strength); this.yDivYOutput.html(this.y.y); this.yDivStrengthOutput.html(this.y.strength); } get center(){ return this._center; } set center(value){ this._center.x = value.x; this._center.y = value.y; this._center.strength = value.strength; } get collide(){ return this._collide; } set collide(value){ this._collide.radius = value.radius; this._collide.strength = value.strength; this._collide.iterations = value.iterations; } get link(){ return this._link; } set link(value){ this._link.distance = value.distance; this._link.iterations = value.iterations; } get manyBody(){ return this._manyBody; } set manyBody(value){ this._manyBody.strength = value.strength; this._manyBody.theta = value.theta; this._manyBody.distanceMin = value.distanceMin; this._manyBody.distanceMax = value.distanceMax; } get x(){ return this._x; } set x(value){ this._x.x = value.x; this._x.strength = value.strength; } get y(){ return this._y; } set y(value){ this._y.y = value.y; this._y.strength = value.strength; } }
<filename>world.js let process = require('process'); let fs = require('fs').promises; let termkit = require('terminal-kit'); async function loadMap(mapFile) { console.log(mapFile); let map = await fs.readFile(mapFile, 'utf8'); return map.trim().split('\n').map(s => Array.from(s)); } function color(term, text, dist) { // This was supposed to be "brick red" but...it's not brick // let red = Math.floor(0xCB * (1 - dist)); // let green = Math.floor(0x41 * (1 - dist)); // let blue = Math.floor(0x54 * (1 - dist)); let red = Math.floor(0xFF * (1 - dist)); let green = Math.floor(0xFF * (1 - dist)); let blue = Math.floor(0xFF * (1 - dist)); return term.colorRgb.str(red, green, blue, text); } function isRayOutOfBounds(rayX, rayY, mapWidth, mapHeight) { return rayX < 0 || rayX >= mapWidth || rayY < 0 || rayY >= mapHeight; } function mapIsWall(map, mapWidth, x, y) { return map[x][y] === '#'; } function renderScreen(term, screen) { term.moveTo(1, 1); term(makeScreen(screen)); } async function main(mapFile) { let term = termkit.terminal; term.fullscreen(); term.hideCursor(); term.grabInput(true); let screenWidth = term.width; let screenHeight = term.height; let playerX = 16.0; let playerY = 16.0; let playerAngle = 0.0; let fovAngle = Math.PI / 3; let renderDepth = 28.0; let mapHeight = 32; let mapWidth = 32; if (!mapFile) { console.error('Error: No map file supplied'); process.exit(1); } term.on('key', (name, matches, data) => { if (name === 'CTRL_C') { term.processExit(); } else if (name === 'a') { playerAngle -= 0.03; } else if (name === 'd') { playerAngle += 0.03; } else if (name === 'w') { playerX += Math.sin(playerAngle) * 0.25; playerY += Math.cos(playerAngle) * 0.25; } else if (name === 's') { playerX -= Math.sin(playerAngle) * 0.25; playerY -= Math.cos(playerAngle) * 0.25; } }); let map = await loadMap(mapFile); let screen = Array(screenHeight).fill(undefined).map(() => Array(screenHeight).fill('%')); setInterval(() => { // For each column of text, cast out a ray for (let x = 0; x < screenWidth; x++) { let rayAngle = (playerAngle - fovAngle / 2.0) + (x / screenWidth) * fovAngle; let distanceToWall = 0.0; let hasHitWall = false; let isBoundary = false; let eyeX = Math.sin(rayAngle); let eyeY = Math.cos(rayAngle); let stepSize = 0.005; // Slowly increment the length of the ray until we either // hit a wall or reach the render depth while (!hasHitWall && distanceToWall < renderDepth) { distanceToWall += stepSize; let testX = Math.floor(playerX + eyeX * distanceToWall); let testY = Math.floor(playerY + eyeY * distanceToWall); if (isRayOutOfBounds(testX, testY, mapWidth, mapHeight)) { hasHitWall = true; distanceToWall = renderDepth; } else if (mapIsWall(map, mapWidth, testX, testY)) { hasHitWall = true; // Detect edges/corners/boundaries of walls and render them with a // different character. This makes it easier to see the border // between wall panels that are visible but at different distances let corners = []; for (let tx = 0; tx < 2; tx++) { for (let ty = 0; ty < 2; ty++) { let vy = testY + ty - playerY; let vx = testX + tx - playerX; let d = Math.sqrt(vx ** 2 + vy ** 2); let dot = (eyeX * vx / d) + (eyeY * vy / d); corners.push([d, dot]); } } corners.sort(([x, _a], [y, _b]) => x - y); let cornerBound = 0.005; if (Math.acos(corners[0][1]) < cornerBound || Math.acos(corners[1][1]) < cornerBound || Math.acos(corners[2][1]) < cornerBound) { isBoundary = true; } } } // Get distance of projection to avoid fisheye effect let projectedDistanceToWall = distanceToWall * Math.cos(rayAngle - playerAngle); // If a wall is "infinitely" far away, we want half the screen to be sky // and half the screen to be ground. let bottomSkyPosition = Math.floor(screenHeight / 2 - screenHeight / projectedDistanceToWall); let bottomWallPosition = screenHeight - bottomSkyPosition; // Determine the character or each row in this column for (let y = 0; y < screenHeight; y++) { if (y < bottomSkyPosition) { let skyDist = 1.0 - ((screenHeight / 2 - y) / (screenHeight / 2)); let red = Math.floor(0x75 * (1 - skyDist)); let green = Math.floor(0xDA * (1 - skyDist)); let blue = Math.floor(0xFF * (1 - skyDist)); screen[y][x] = term.colorRgb.str(red, green, blue, '~'); // screen[y][x] = ' '; } else if (y <= bottomWallPosition) { let wallTile; // wallTile = color(term, '█', dist); if (isBoundary) { wallTile = '·'; } else if (distanceToWall <= renderDepth / 4) { wallTile = '█'; // color(term, '█', dist); } else if (distanceToWall < renderDepth / 3) { wallTile = '▓'; // '▓'; } else if (distanceToWall <= renderDepth / 2) { wallTile = '▒'; // '▒'; } else if (distanceToWall <= renderDepth) { wallTile = '░'; // '░'; } else { wallTile = ' '; } wallTile = color(term, wallTile, distanceToWall / renderDepth); screen[y][x] = wallTile; } else { let floorTile; let floorDist = 1.0 - ((y - screenHeight / 2) / (screenHeight / 2)); // We use the same character for every floor tile here, but // we were experimenting with changing the floor tile depending // on the distance from the camera let shade = Math.floor(0xFF * (1 - floorDist ** 0.35)); if (floorDist < 0.25) { floorTile = '·'; } else if (floorDist < 0.5) { floorTile = '·'; } else if (floorDist < 0.75) { floorTile = '·'; } else if (floorDist < 0.9) { floorTile = '·'; } else { floorTile = ' '; } screen[y][x] = term.colorRgb.str(0x00, shade, 0x00, floorTile); } } } renderScreen(term, screen); }, 50); } function makeScreen(screen) { return screen.map(s => s.join('')).join('\n'); } let userArgs = process.argv.slice(2); main(...userArgs);
<reponame>shrishankit/prisma package com.prisma.deploy.migration.validation.directives import com.prisma.deploy.migration.DataSchemaAstExtensions._ import com.prisma.deploy.migration.validation.{DeployError, PrismaSdl} import com.prisma.shared.models.ConnectorCapabilities import com.prisma.utils.boolean.BooleanUtils import sangria.ast._ trait DirectiveBase extends BooleanUtils with SharedDirectiveValidation { def name: String def postValidate(dataModel: PrismaSdl, capabilities: ConnectorCapabilities): Vector[DeployError] = Vector.empty } object TypeDirective { val all = Vector(TypeDbDirective, EmbeddedDirective, RelationTableDirective) } trait TypeDirective[T] extends DirectiveBase { def validate( document: Document, typeDef: ObjectTypeDefinition, directive: sangria.ast.Directive, capabilities: ConnectorCapabilities ): Vector[DeployError] def value( document: Document, typeDef: ObjectTypeDefinition, capabilities: ConnectorCapabilities ): Option[T] } trait FieldDirective[T] extends DirectiveBase { def requiredArgs(capabilities: ConnectorCapabilities): Vector[DirectiveArgument[_]] def optionalArgs(capabilities: ConnectorCapabilities): Vector[DirectiveArgument[_]] // gets called if the directive was found. Can return an error message def validate( document: Document, typeDef: ObjectTypeDefinition, fieldDef: FieldDefinition, directive: sangria.ast.Directive, capabilities: ConnectorCapabilities ): Vector[DeployError] def value( document: Document, typeDef: ObjectTypeDefinition, fieldDef: FieldDefinition, capabilities: ConnectorCapabilities ): Option[T] } object FieldDirective { val behaviour = Vector(IdDirective, CreatedAtDirective, UpdatedAtDirective, ScalarListDirective) val all = Vector(DefaultDirective, RelationDirective, UniqueDirective, FieldDbDirective, SequenceDirective) ++ behaviour } case class ArgumentRequirement(name: String, validate: sangria.ast.Value => Option[String]) trait DirectiveArgument[T] extends SharedDirectiveValidation with BooleanUtils { def name: String def validate(value: sangria.ast.Value): Option[String] def value(directive: Directive): Option[T] = directive.argument(name).map(arg => value(arg.value)) def value(value: sangria.ast.Value): T } object DirectiveArgument extends SharedDirectiveValidation { def apply[T](name: String, validate: sangria.ast.Value => Option[String], value: sangria.ast.Value => T) = { val (nameArg, validateArg, valueArg) = (name, validate, value) new DirectiveArgument[T] { override def name = nameArg override def value(value: Value) = valueArg(value) override def validate(value: Value) = validateArg(value) } } def string(name: String): DirectiveArgument[String] = DirectiveArgument(name, validateStringValue, _.asString) }
package blocks; import core.Block; import core.Type; import tokenizer.Token; /** * @author <NAME> * @email <EMAIL> */ public class ClassBlock extends Block<Token> implements Type { public ClassBlock extendClass = null; public boolean isClosed = false; private String className; public ClassBlock(String name, String line, int lineNumber) { super(null, line, lineNumber); this.className = name; } public ClassBlock getExtendClass() { return extendClass; } public boolean isSubclassOf(ClassBlock classBlock) { ClassBlock currentClassBlock = this; String className = currentClassBlock.getClassName(); while (null != currentClassBlock) { if (className.equals(currentClassBlock.getClassName())) { return true; } currentClassBlock = currentClassBlock.getParentClass(); } return false; } public String getClassName() { return this.className; } @Override public Token run() { // execute constructor method return null; } }
import React, { useState, useRef } from 'react'; import { action } from '@storybook/addon-actions'; import Popover, { PurePopover } from '@ichef/gypcrete/src/Popover'; import Button from '@ichef/gypcrete/src/Button'; import List from '@ichef/gypcrete/src/List'; import ListRow from '@ichef/gypcrete/src/ListRow'; export default { title: '@ichef/gypcrete|Popover', component: PurePopover, subcomponents: { 'renderToLayer(closable(anchored(Popover))': Popover, }, }; export function BasicExample() { function ButtonRow(props) { return ( <ListRow> <Button minified={false} {...props} /> </ListRow> ); } function DemoList() { return ( <List> <ButtonRow basic="Row 1" onClick={action('click.1')} /> <ButtonRow basic="Row 2" onClick={action('click.2')} /> <ButtonRow basic="Row 3" onClick={action('click.3')} /> <ButtonRow basic="Link row" tagName="a" href="https://apple.com" /> </List> ); } return ( <div> <PurePopover> <DemoList /> </PurePopover> <div style={{ height: 50 }} /> <PurePopover placement="top"> <DemoList /> </PurePopover> </div> ); } export function AnchoredPopover() { function ButtonRow(props) { return ( <ListRow> <Button minified={false} {...props} /> </ListRow> ); } function DemoList() { return ( <List> <ButtonRow basic="Row 1" onClick={action('click.1')} /> <ButtonRow basic="Row 2" onClick={action('click.2')} /> <ButtonRow basic="Row 3" onClick={action('click.3')} /> <ButtonRow basic="Link row" tagName="a" href="https://apple.com" /> </List> ); } const [popoverOpen, setPopoverOpen] = useState(false); const btnRef = useRef(); const btn = btnRef.current; const handlePopoverOpen = () => { setPopoverOpen(true); }; const handlePopoverClose = () => { setPopoverOpen(false); }; const anchorStyle = { display: 'inline-block', }; const showPopover = popoverOpen && (btnRef.current); return ( <div> <span style={anchorStyle} ref={btnRef} > <Button basic="Open popover" onClick={handlePopoverOpen} /> </span> {showPopover && ( <Popover anchor={btn} placement="top" onClose={handlePopoverClose} > <DemoList /> </Popover> )} </div> ); } AnchoredPopover.story = { parameters: { docs: { storyDescription: 'placed to a specified DOM element', }, }, };
<reponame>hengxin/jepsen-in-java<gh_stars>1-10 package example.cassandra.read_write_client; import core.client.Client; import core.client.ClientCreator; import core.db.Node; public class ReadAndWriteDoubleClientCreator implements ClientCreator { @Override public Client Create(Node node) { return new ReadAndWriteDoubleClient(1000); } }
#include "image_io/jpeg/jpeg_segment.h" #include <cctype> #include <iomanip> #include <sstream> #include <string> namespace photos_editing_formats { namespace image_io { using std::string; using std::stringstream; /// Finds the character allowing it to be preceded by whitespace characters. /// @param segment The segment in which to look for the character. /// @param start_location The location at which to start looking. /// @param value The character value to look for. /// @return The location of the character or segment.GetEnd() if not found, /// of non whitespace characters are found first. static size_t SkipWhiteSpaceFindChar(const JpegSegment& segment, size_t start_location, char value) { for (size_t location = start_location; location < segment.GetEnd(); ++location) { ValidatedByte validated_byte = segment.GetValidatedByte(location); if (!validated_byte.is_valid) { return segment.GetEnd(); } if (validated_byte.value == Byte(value)) { return location; } if (!std::isspace(validated_byte.value)) { return segment.GetEnd(); } } return segment.GetEnd(); } size_t JpegSegment::GetVariablePayloadSize() const { if (!GetMarker().HasVariablePayloadSize()) { return 0; } size_t payload_location = GetPayloadLocation(); ValidatedByte hi = GetValidatedByte(payload_location); ValidatedByte lo = GetValidatedByte(payload_location + 1); if (!hi.is_valid || !lo.is_valid) { return 0; } return static_cast<size_t>(hi.value) << 8 | static_cast<size_t>(lo.value); } bool JpegSegment::BytesAtLocationStartWith(size_t location, const char* str) const { while (*str && Contains(location)) { ValidatedByte validated_byte = GetValidatedByte(location++); if (!validated_byte.is_valid || Byte(*str++) != validated_byte.value) { return false; } } return *str == 0; } bool JpegSegment::BytesAtLocationContain(size_t location, const char* str) const { return Find(location, str) != GetEnd(); } size_t JpegSegment::Find(size_t location, const char* str) const { Byte byte0 = static_cast<Byte>(*str); while ((location = Find(location, byte0)) < GetEnd()) { if (BytesAtLocationStartWith(location, str)) { return location; } ++location; } return GetEnd(); } size_t JpegSegment::Find(size_t start_location, Byte value) const { if (!begin_segment_ && !end_segment_) { return GetEnd(); } size_t value_location = GetEnd(); if (begin_segment_ && !end_segment_) { value_location = begin_segment_->Find(start_location, value); } else { value_location = DataSegment::Find(start_location, value, begin_segment_, end_segment_); } return Contains(value_location) ? value_location : GetEnd(); } std::string JpegSegment::ExtractXmpPropertyValue( size_t start_location, const char* property_name) const { size_t begin_value_location = FindXmpPropertyValueBegin(start_location, property_name); if (begin_value_location != GetEnd()) { size_t end_value_location = FindXmpPropertyValueEnd(begin_value_location); if (end_value_location != GetEnd()) { DataRange data_range(begin_value_location, end_value_location); return ExtractString(data_range); } } return ""; } size_t JpegSegment::FindXmpPropertyValueBegin(size_t start_location, const char* property_name) const { size_t property_location = Find(start_location, property_name); if (property_location != GetEnd()) { size_t equal_location = SkipWhiteSpaceFindChar( *this, property_location + strlen(property_name), '='); if (equal_location != GetEnd()) { size_t quote_location = SkipWhiteSpaceFindChar(*this, equal_location + 1, '"'); if (quote_location != GetEnd()) { return quote_location + 1; } } } return GetEnd(); } size_t JpegSegment::FindXmpPropertyValueEnd(size_t start_location) const { return Find(start_location, Byte('"')); } std::string JpegSegment::ExtractString(const DataRange& data_range) const { std::string value; if (Contains(data_range.GetBegin()) && data_range.GetEnd() <= GetEnd()) { size_t start_location = data_range.GetBegin(); size_t length = data_range.GetLength(); value.resize(length, ' '); for (size_t index = 0; index < length; ++index) { ValidatedByte validated_byte = GetValidatedByte(start_location + index); if (!validated_byte.value) { // Invalid bytes have a zero value. value.resize(0); break; } value[index] = static_cast<char>(validated_byte.value); } } return value; } void JpegSegment::GetPayloadHexDumpStrings(size_t byte_count, std::string* hex_string, std::string* ascii_string) const { stringstream ascii_stream; stringstream hex_stream; hex_stream << std::hex << std::uppercase; size_t dump_count = GetMarker().IsEntropySegmentDelimiter() ? byte_count : std::min(byte_count, GetLength() - 2); for (size_t index = 0; index < dump_count; ++index) { ValidatedByte payload_byte = GetValidatedByte(GetPayloadLocation() + index); if (!payload_byte.is_valid) { break; } Byte value = payload_byte.value; hex_stream << std::setfill('0') << std::setw(2) << static_cast<int>(value); ascii_stream << (isprint(value) ? static_cast<char>(value) : '.'); } size_t current_count = ascii_stream.str().length(); for (size_t index = current_count; index < byte_count; ++index) { hex_stream << " "; ascii_stream << "."; } *hex_string = hex_stream.str(); *ascii_string = ascii_stream.str(); } } // namespace image_io } // namespace photos_editing_formats
package io.opensphere.core.collada.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; /** * A COLLADA geometry. */ @XmlAccessorType(XmlAccessType.NONE) public class Geometry { /** The id. */ @XmlAttribute(name = "id") private String myId; /** The mesh. */ @XmlElement(name = "mesh") private Mesh myMesh; /** * Get the id. * * @return The id. */ public String getId() { return myId; } /** * Get the mesh. * * @return The mesh. */ public Mesh getMesh() { return myMesh; } /** * Set the id. * * @param id The id. */ public void setId(String id) { myId = id; } }
''' 09_visualize_results.py Author: <NAME> (<EMAIL>) - Load the differential and mean current, sum, and plot them together ''' import numpy as np import matplotlib.pyplot as plt ## Flag to save plots or not save_plots = True nt = 2 # number of hours ## Load mean current data tmp = np.load('./disp/U.npy') x_m = tmp[:,0] U_m = tmp[:,1] H = np.load('./disp/U.npy')[:,1] ## Load differential current data x_d = np.load('./disp/midpts.npy') U_d = np.load('./disp/U_diff.npy') ## Interpolate onto the same grid N = 100 x = np.linspace(0,10000,N) Um = np.interp(x,x_m,U_m) U = np.zeros((nt,N)) for i in range(nt): U[i,:] = np.interp(x,x_d,U_d[:,i]) + Um ## Plot fig,ax = plt.subplots(1,1,figsize=(8,5)) ax.plot(x,U[0,:],'r',label='hour 0') ax.plot(x,U[1,:],'b',label='hour 1') ax.set_xlim([0,10000]) ax.set_xlabel('Distance (m)') ax.set_ylabel('Current velocity (m/s)') ax.legend() ax.set_title('Absolute current') ## Save if save_plots: fig.savefig('./figs/09_abs_current.png') plt.show()
package parser import ( "github.com/go-faster/errors" "github.com/ogen-go/ogen/internal/oas" ) type pathParser struct { path string // immutable params []*oas.Parameter // immutable parts []oas.PathPart // parsed parts part []rune // current part param bool // current part is param name? } func parsePath(path string, params []*oas.Parameter) ([]oas.PathPart, error) { return (&pathParser{ path: path, params: params, }).Parse() } func (p *pathParser) Parse() ([]oas.PathPart, error) { err := p.parse() return p.parts, err } func (p *pathParser) parse() error { for _, r := range p.path { switch r { case '/': if p.param { return errors.Errorf("invalid path: %s", p.path) } p.part = append(p.part, r) case '{': if p.param { return errors.Errorf("invalid path: %s", p.path) } if err := p.push(); err != nil { return err } p.param = true case '}': if !p.param { return errors.Errorf("invalid path: %s", p.path) } if err := p.push(); err != nil { return err } p.param = false default: p.part = append(p.part, r) } } if p.param { return errors.Errorf("invalid path: %s", p.path) } return p.push() } func (p *pathParser) push() error { if len(p.part) == 0 { return nil } defer func() { p.part = nil }() if !p.param { p.parts = append(p.parts, oas.PathPart{Raw: string(p.part)}) return nil } param, found := p.lookupParam(string(p.part)) if !found { return errors.Errorf("path parameter not specified: %q", string(p.part)) } p.parts = append(p.parts, oas.PathPart{Param: param}) return nil } func (p *pathParser) lookupParam(name string) (*oas.Parameter, bool) { for _, p := range p.params { if p.Name == name && p.In == oas.LocationPath { return p, true } } return nil, false }
<filename>scoreboard/frontend/src/sources/api_hooks.js import api from "./api"; import useSWR from "swr"; import _ from 'underscore'; import { useState } from "react"; const api_fetcher = (url, n_ticks=1,) => { return api.get(url, {n_ticks: n_ticks}).then(r => r.body) } const STATE_POLLING_INTERVAL = 10 * 1000; export function useGameState (n_ticks=1, swr_config={}) { var config = {refreshInterval: STATE_POLLING_INTERVAL, dedupingInterval: STATE_POLLING_INTERVAL, ...swr_config}; const { data, error } = useSWR( [`/game/state`, n_ticks], api_fetcher, config ) console.log(data, error); return { gamestate: (error || !data) ? undefined : data, isLoading: !!(!error && !data), isError: error } } export function useLatestGameState() { const {gs, loading, error} = useGameState(); let latest_dynamic = gs && gs.dynamic && gs.dynamic[0]; return {latest_dynamic, static: gs.static, loading, error} } function sortScores(scores, sortAttribute) { let sortedScores = _.chain(scores).values().sortBy(sortAttribute).reverse().value(); return sortedScores; } export function useTicksScores(n_ticks=1) { let [ticks, setTicks] = useState([]); const {gamestate, loading, error} = useGameState(n_ticks=1); var lastScores = []; var lastScoresSorted = []; if (!gamestate || gamestate.dynamic.length < 1) { return {ticks: undefined, lastScores, lastScoresSorted, loading, error} } let lastTick = ticks[ticks.length-1]; if (!lastTick || lastTick.tick.tick_id !== gamestate.dynamic[0].tick.tick_id) { let lastScores = _.values(gamestate.dynamic[0].scores); let attackMax = Math.max(_.chain(lastScores).pluck('attack_points').max().value(), 1); let serviceMax = Math.max(_.chain(lastScores).pluck('service_points').max().value(), 1); let slaMax = _.chain(lastScores).pluck('sla').max().value(); lastScores = lastScores.for(s => { s.attack_score = s.attack_points / attackMax * 100; s.service_score = s.service_points / serviceMax * 100; s.sla_score = s.sla / (slaMax === 0 ? 1 : slaMax) * 100; s.team_name = gamestate.static.teams[s.team_id] && gamestate.static.teams[s.team_id].name; return s; }); lastScoresSorted = sortScores(lastScores, 'total_points'); setTicks(ticks.concat(gamestate.dynamic)); } return {ticks, lastScores, lastScoresSorted, loading, error} } // const loadData = () => // api.get('/game/state') // .then(res => res.json() // console.log(res.body); // setDynamicData(res.body.dynamic); // setStaticData(res.body.static); // setServices(res.body.static.services); // setTeams(res.body.static.teams); // }) // .catch((e) => { // console.log("Error getting game state: " + e) // });
#!/bin/bash # This has to be a separate file from scripts/make.sh so it can be called # before menuconfig. (It's called again from scripts/make.sh just to be sure.) mkdir -p generated source scripts/portability.sh probecc() { ${CROSS_COMPILE}${CC} $CFLAGS -xc -o /dev/null $1 - } # Probe for a single config symbol with a "compiles or not" test. # Symbol name is first argument, flags second, feed C file to stdin probesymbol() { probecc $2 2>/dev/null && DEFAULT=y || DEFAULT=n rm a.out 2>/dev/null echo -e "config $1\n\tbool" || exit 1 echo -e "\tdefault $DEFAULT\n" || exit 1 } probeconfig() { > generated/cflags # llvm produces its own really stupid warnings about things that aren't wrong, # and although you can turn the warning off, gcc reacts badly to command line # arguments it doesn't understand. So probe. [ -z "$(probecc -Wno-string-plus-int <<< \#warn warn 2>&1 | grep string-plus-int)" ] && echo -Wno-string-plus-int >> generated/cflags # Probe for container support on target probesymbol TOYBOX_CONTAINER << EOF #include <linux/sched.h> int x=CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET; int main(int argc, char *argv[]) { setns(0,0); return unshare(x); } EOF probesymbol TOYBOX_FIFREEZE -c << EOF #include <linux/fs.h> #ifndef FIFREEZE #error nope #endif EOF # Work around some uClibc limitations probesymbol TOYBOX_ICONV -c << EOF #include "iconv.h" EOF probesymbol TOYBOX_FALLOCATE << EOF #include <fcntl.h> int main(int argc, char *argv[]) { return posix_fallocate(0,0,0); } EOF # Android and some other platforms miss utmpx probesymbol TOYBOX_UTMPX -c << EOF #include <utmpx.h> #ifndef BOOT_TIME #error nope #endif int main(int argc, char *argv[]) { struct utmpx *a; if (0 != (a = getutxent())) return 0; return 1; } EOF # Android is missing shadow.h probesymbol TOYBOX_SHADOW -c << EOF #include <shadow.h> int main(int argc, char *argv[]) { struct spwd *a = getspnam("root"); return 0; } EOF # Some commands are android-specific probesymbol TOYBOX_ON_ANDROID -c << EOF #ifndef __ANDROID__ #error nope #endif EOF probesymbol TOYBOX_ANDROID_SCHEDPOLICY << EOF #include <cutils/sched_policy.h> int main(int argc,char *argv[]) { get_sched_policy_name(0); } EOF # nommu support probesymbol TOYBOX_FORK << EOF #include <unistd.h> int main(int argc, char *argv[]) { return fork(); } EOF echo -e '\tdepends on !TOYBOX_MUSL_NOMMU_IS_BROKEN' probesymbol TOYBOX_PRLIMIT << EOF #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> int prlimit(pid_t pid, int resource, const struct rlimit *new_limit, struct rlimit *old_limit); int main(int argc, char *argv[]) { prlimit(0, 0, 0, 0); } EOF probesymbol TOYBOX_GETRANDOM << EOF #include <sys/random.h> int main(void) { char buf[100]; getrandom(buf, 100, 0); } EOF } genconfig() { # Reverse sort puts posix first, examples last. for j in $(ls toys/*/README | sort -s -r) do DIR="$(dirname "$j")" [ $(ls "$DIR" | wc -l) -lt 2 ] && continue echo "menu \"$(head -n 1 $j)\"" echo # extract config stanzas from each source file, in alphabetical order for i in $(ls -1 $DIR/*.c) do # Grab the config block for Config.in echo "# $i" $SED -n '/^\*\//q;/^config [A-Z]/,$p' $i || return 1 echo done echo endmenu done } probeconfig > generated/Config.probed || rm generated/Config.probed genconfig > generated/Config.in || rm generated/Config.in # Find names of commands that can be built standalone in these C files toys() { grep 'TOY(.*)' "$@" | grep -v TOYFLAG_NOFORK | grep -v "0))" | \ $SED -En 's/([^:]*):.*(OLD|NEW)TOY\( *([a-zA-Z][^,]*) *,.*/\1:\3/p' } WORKING= PENDING= toys toys/*/*.c | ( while IFS=":" read FILE NAME do [ "$NAME" == help ] && continue [ "$NAME" == install ] && continue echo -e "$NAME: $FILE *.[ch] lib/*.[ch]\n\tscripts/single.sh $NAME\n" echo -e "test_$NAME:\n\tscripts/test.sh $NAME\n" [ "${FILE/pending//}" != "$FILE" ] && PENDING="$PENDING $NAME" || WORKING="$WORKING $NAME" done && echo -e "clean::\n\trm -f $WORKING $PENDING" && echo -e "list:\n\t@echo $(echo $WORKING | tr ' ' '\n' | sort | xargs)" && echo -e "list_pending:\n\t@echo $(echo $PENDING | tr ' ' '\n' | sort | xargs)" && echo -e ".PHONY: $WORKING $PENDING" | $SED 's/ \([^ ]\)/ test_\1/g' ) > .singlemake
package gotify import ( "bytes" "log" "regexp" "strings" ) // Gotify provides "gotification" of domain specific identifier names: // underscored names translates into camel case ones. // How the translation is done: // idenitifier name is splitted into chunks and each chunk is to be lowered, samples: // abc_def -> [abc, def] // AbdDef -> [abd, def] // userId -> [user, id] // Then there are choice: // package name (just concat) // private identifiers (first chunk is kept lowered, the rest is treated as for public identifiers) // public identifiers: // Eeach chunk is looked up in provided dictionary (id -> ID translation is always here) // and is replaced with either found translation or just with titled word and then concatenated // into the string // abc_def -> AbdDef // AbdDef -> AbdDef // userId -> UserID type Gotify struct { dict map[string]string } // New constructs Gotify object func New(src map[string]string) *Gotify { if src == nil { src = map[string]string{} } src["id"] = "ID" src["http"] = "HTTP" src["ip"] = "IP" src["uuid"] = "UUID" src["uid"] = "UID" return &Gotify{ dict: src, } } // Pure чистый преобразователь без трюков func Pure() *Gotify { return &Gotify{ dict: nil, } } func acceptableHead(value byte) bool { return ('a' <= value && value <= 'z') || ('A' <= value && value <= 'Z') || value == '_' } func acceptableTail(value byte) bool { return acceptableHead(value) || ('0' <= value && value <= '9') } func filter(rawData string) string { buf := &bytes.Buffer{} rawData = strings.Replace(rawData, ".", "_", -1) data := []byte(rawData) for i, value := range data { if acceptableHead(value) { if err := buf.WriteByte(value); err != nil { log.Fatal(err) } for _, val := range data[i+1:] { if acceptableTail(val) || val == ' ' { if err := buf.WriteByte(val); err != nil { log.Fatal(err) } } } break } } return string(buf.Bytes()) } var goishMask *regexp.Regexp // split obviously splits func split(name string) []string { name = strings.Replace(strings.Replace(name, ".", " ", -1), "_", " ", -1) deserveUppercase := "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for _, letter := range deserveUppercase { name = strings.Replace(name, string(letter), " "+string(letter), -1) } res := strings.Split(name, " ") real := []string{} for _, piece := range res { if len(piece) > 0 { real = append(real, piece) } } if len(real) == 0 { real = append(real, "unrecognized", "sequence") } return real } func (g *Gotify) title(value string) string { if val, ok := g.dict[strings.ToLower(value)]; ok { return val } if len(value) == 0 { return value } i := 0 for i < len(value) && !('0' <= value[i] && value[i] <= '9') { i++ } var head string if i == len(value) { head = value value = "" } else { head = value[:i] value = value[i:] } i = 0 for i < len(value) && '0' <= value[i] && value[i] <= '9' { i++ } var tail string if i == len(value) { tail = value value = "" } else { tail = value[:i] value = value[i:] } if val, ok := g.dict[head]; ok { return val + tail + g.title(value) } else if len(head) == 0 { return tail + g.title(value) } return strings.ToUpper(head[:1]) + head[1:] + tail + g.title(value) } // Public translates identifier into Go public identifier name func (g *Gotify) Public(name string) string { splits := split(filter(name)) res := &bytes.Buffer{} for _, part := range splits { res.WriteString(g.title(part)) } return res.String() } // Private translates identifier into Go private identifier name func (g *Gotify) Private(name string) string { splits := split(filter(name)) res := &bytes.Buffer{} res.WriteString(strings.ToLower(splits[0])) for _, part := range splits[1:] { res.WriteString(g.title(part)) } return res.String() } // Package generates acceptable package name func (g *Gotify) Package(name string) string { return strings.ToLower(strings.Replace(strings.Replace(name, "_", "", -1), ".", "", -1)) } // Goimports generates directory name that can be consumed by goformat utility func (g *Gotify) Goimports(data string) string { return strings.Replace(data, "_", "-", -1) } // True checks if this a goish identifier func (g *Gotify) True(name string) bool { return goishMask.MatchString(name) } func init() { goishMask = regexp.MustCompile("^[_a-zA-Z][_a-zA-Z0-9]*$") }
curl -X POST --header "Content-Type: application/json" -d '{"build_parameters": {"CIRCLE_JOB": "deploy_stage"}}' https://circleci.com/api/v1/project/backbone/workbench/tree/develop?circle-token=$1
<reponame>bfreuden/vertx-auth<gh_stars>100-1000 /******************************************************************************** * Copyright (c) 2019 <NAME> * * This program and the accompanying materials are made available under the 2 * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 3 * * Contributors: 4 * <NAME> - initial API and implementation ********************************************************************************/ package io.vertx.ext.auth.properties; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.User; import io.vertx.ext.auth.authentication.AuthenticationProvider; import io.vertx.ext.auth.authorization.*; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.RunTestOnContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.util.function.Consumer; /** * @author <a href="http://tfox.org"><NAME></a> */ @RunWith(VertxUnitRunner.class) public class PropertyFileAuthenticationTest { @Rule public RunTestOnContext rule = new RunTestOnContext(); private AuthenticationProvider authn; private AuthorizationProvider authz; @Test public void testSimpleAuthenticate(TestContext should) { final Async test = should.async(); JsonObject authInfo = new JsonObject().put("username", "tim").put("password", "<PASSWORD>"); authn.authenticate(authInfo) .onFailure(should::fail) .onSuccess(user -> { should.assertNotNull(user); test.complete(); }); } @Test public void testSimpleAuthenticateFailWrongPassword(TestContext should) { final Async test = should.async(); JsonObject authInfo = new JsonObject().put("username", "tim").put("password", "<PASSWORD>"); authn.authenticate(authInfo) .onSuccess(user -> should.fail("Not Expected")) .onFailure(thr -> { should.assertNotNull(thr); test.complete(); }); } @Test public void testSimpleAuthenticateFailWrongUser(TestContext should) { final Async test = should.async(); JsonObject authInfo = new JsonObject().put("username", "frank").put("password", "<PASSWORD>"); authn.authenticate(authInfo) .onSuccess(user -> should.fail("Not Expected")) .onFailure(thr -> { should.assertNotNull(thr); test.complete(); }); } @Test public void testHasRole(TestContext should) { final Async test = should.async(); loginThen(should, user -> authz.getAuthorizations(user) .onFailure(should::fail) .onSuccess(v -> { should.assertTrue( RoleBasedAuthorization.create("morris_dancer").match(AuthorizationContext.create(user))); should.assertTrue( RoleBasedAuthorization.create("morris_dancer").match(AuthorizationContext.create(user))); test.complete(); })); } @Test public void testNotHasRole(TestContext should) { final Async test = should.async(); loginThen(should, user -> authz.getAuthorizations(user) .onFailure(should::fail) .onSuccess(v -> { should.assertFalse( RoleBasedAuthorization.create("manager").match(AuthorizationContext.create(user))); should.assertFalse( RoleBasedAuthorization.create("manager").match(AuthorizationContext.create(user))); test.complete(); })); } @Test public void testHasPermission(TestContext should) { final Async test = should.async(); loginThen(should, user -> authz.getAuthorizations(user) .onFailure(should::fail) .onSuccess(v -> { should.assertTrue( PermissionBasedAuthorization.create("do_actual_work").match(AuthorizationContext.create(user))); should.assertTrue( PermissionBasedAuthorization.create("do_actual_work").match(AuthorizationContext.create(user))); test.complete(); })); } @Test public void testNotHasPermission(TestContext should) { final Async test = should.async(); loginThen(should, user -> authz.getAuthorizations(user) .onFailure(should::fail) .onSuccess(v -> { should.assertFalse( PermissionBasedAuthorization.create("play_golf").match(AuthorizationContext.create(user))); should.assertFalse( PermissionBasedAuthorization.create("play_golf").match(AuthorizationContext.create(user))); test.complete(); })); } private void loginThen(TestContext should, Consumer<User> runner) { JsonObject authInfo = new JsonObject().put("username", "tim").put("password", "<PASSWORD>"); authn.authenticate(authInfo) .onFailure(should::fail) .onSuccess(user -> { should.assertNotNull(user); runner.accept(user); }); } @Before public void setUp() throws Exception { authn = PropertyFileAuthentication.create(rule.vertx(), this.getClass().getResource("/test-auth.properties").getFile()); authz = PropertyFileAuthorization.create(rule.vertx(), this.getClass().getResource("/test-auth.properties").getFile()); } @Test public void testHasWildcardPermission(TestContext should) { final Async test = should.async(); JsonObject authInfo = new JsonObject().put("username", "paulo").put("password", "<PASSWORD>"); authn.authenticate(authInfo) .onFailure(should::fail) .onSuccess(user -> { should.assertNotNull(user); authz.getAuthorizations(user) .onFailure(should::fail) .onSuccess(v -> { // paulo can do anything... should.assertTrue( WildcardPermissionBasedAuthorization.create("do_actual_work").match(AuthorizationContext.create(user))); test.complete(); }); }); } @Test public void testHasWildcardMatchPermission(TestContext should) { final Async test = should.async(); JsonObject authInfo = new JsonObject().put("username", "editor").put("password", "<PASSWORD>"); authn.authenticate(authInfo) .onFailure(should::fail) .onSuccess(user -> { should.assertNotNull(user); // editor can edit any newsletter item... authz.getAuthorizations(user) .onFailure(should::fail) .onSuccess(u -> { should.assertTrue( WildcardPermissionBasedAuthorization.create("newsletter:edit:13").match(AuthorizationContext.create(user))); test.complete(); }); }); } }
#!/bin/sh TEST_ROOT=$PWD TASKLIB=$TEST_ROOT/diffexSrc/src WORKING_DIR=$TEST_ROOT/job_1 INPUT_FILE_DIRECTORIES=$TEST_ROOT/diffexSrc/data COMMAND_LINE="python $TASKLIB/DiffEx.py $INPUT_FILE_DIRECTORIES/test_dataset.gct $INPUT_FILE_DIRECTORIES/test_dataset.cls 5" # local only variables # DOCKER_CONTAINER=genepattern/docker-aws-python36 # batch only variables # JOB_DEFINITION_NAME="Python36_Generic" JOB_ID=gp_job_python36_$1
const executeIfFunction = <T>(f: T | ((key: string) => T), arg: string) => typeof f === "function" ? f(arg) : f ; const toString = (key: string | number) => typeof key === "number" ? key.toString() : key; export const switchcaseC: <T>(cases: { [id: string]: T }) => ((defaultCase: T) => ((key: string | number) => T)) = (cases) => (defaultCase) => (key) => toString(key) in cases ? cases[key] : defaultCase ; export const switchcase: <T>(cases: { [id: string]: T | ((key: string) => T) }) => ((defaultCase: T | ((key: string) => T)) => ((key: string) => T)) = (cases) => (defaultCase) => (key) => executeIfFunction(switchcaseC(cases)(defaultCase)(key), key) ; export const extract = <T>(value: T | undefined) => { if (value === undefined) { throw new Error("Cannot be undefined"); } else { return value; } };
def is_balanced(s: str) -> bool: left_count = 0 star_count = 0 for char in s: if char == '(': left_count += 1 elif char == ')': if left_count > 0: left_count -= 1 elif star_count > 0: star_count -= 1 else: return False elif char == '*': star_count += 1 right_count = 0 star_count = 0 for char in s[::-1]: if char == ')': right_count += 1 elif char == '*': star_count += 1 else: break return left_count <= star_count + right_count
TERMUX_PKG_HOMEPAGE=https://xiph.org/flac/ TERMUX_PKG_DESCRIPTION="FLAC (Free Lossless Audio Codec) library" TERMUX_PKG_VERSION=1.3.2 TERMUX_PKG_REVISION=2 TERMUX_PKG_SRCURL=http://downloads.xiph.org/releases/flac/flac-1.3.1.tar.xz TERMUX_PKG_SHA256=4773c0099dba767d963fd92143263be338c48702172e8754b9bc5103efe1c56c TERMUX_PKG_DEPENDS="libogg"
<gh_stars>0 package tree.symbols; import tree.DefaultTreeNodeSymbol; public class TSComma extends DefaultTreeNodeSymbol { public static int id = COMMA; public static String text = ","; public TSComma() { super(text, id); } }
import { GRAY, CYAN, YELLOW, RED } from 'ibuprofen/lib/colors' const KEYWORDS = { 'SELECT': GRAY, 'UPDATE': CYAN, 'INSERT': YELLOW, 'DELETE': RED, } const formatQuery = (qry, params) => { let q = qry.replace('Executing (default):', '') q = q.replace('WITH rows as (', '') q = q.replace(') SELECT count(*) FROM rows', '') for (const kw in KEYWORDS) q = q.replace(new RegExp(kw, 'g'), KEYWORDS[kw](kw)) let p = params != undefined ? `[${params.join(', ')}]` : '' return `${q} ${p}` } export default formatQuery
<gh_stars>1-10 #ifndef __IM_GROOT_FILE_BROWSER_H__ #define __IM_GROOT_FILE_BROWSER_H__ #include <filesystem> namespace ImGroot { class FileBrowser { private: std::filesystem::path m_current_dir = std::filesystem::current_path(); uint32_t m_selected_item_id = std::numeric_limits<uint32_t>::max(); private: void unselect_item() noexcept; private: void draw_none_icon(float width, float height) const noexcept; void draw_home_icon(float width, float height, uint32_t color) const noexcept; void draw_desktop_icon(float width, float height, uint32_t color) const noexcept; void draw_recent_icon(float width, float height, uint32_t color) const noexcept; void draw_trash_icon(float width, float height, uint32_t color) const noexcept; void draw_image_file_icon(float width, float height, uint32_t color) const noexcept; void draw_file_icon(float width, float height, uint32_t color) const noexcept; void draw_dir_icon(float width, float height, uint32_t color) const noexcept; enum class ButtonState { NONE = 0, HOVERED, CLICKED }; ButtonState draw_wide_button(bool selected, uint32_t hovered_color, uint32_t active_color) const noexcept; private: void show_item_context_menu() const noexcept; void show_general_context_menu() const noexcept; void show_nav_menu() noexcept; void show_side_menu() noexcept; void show_dir_browser_list() noexcept; public: void render() noexcept; }; } #endif // !__IM_GROOT_FILE_BROWSER_H__
<gh_stars>1-10 package de.hswhameln.typetogether.client.gui; import de.hswhameln.typetogether.client.businesslogic.ClientUser; import de.hswhameln.typetogether.client.runtime.PropertyChangeManager; import de.hswhameln.typetogether.client.runtime.SessionStorage; import de.hswhameln.typetogether.client.runtime.commands.CommandInvoker; import de.hswhameln.typetogether.client.runtime.commands.CreateDocumentCharacterCommand; import de.hswhameln.typetogether.client.runtime.commands.CreateDocumentCharactersCommand; import de.hswhameln.typetogether.client.runtime.commands.DeleteDocumentCharacterCommand; import de.hswhameln.typetogether.client.runtime.commands.DeleteDocumentCharactersCommand; import de.hswhameln.typetogether.networking.LocalDocument; import de.hswhameln.typetogether.networking.api.Document; import de.hswhameln.typetogether.networking.types.DocumentCharacter; import de.hswhameln.typetogether.networking.types.Identifier; import de.hswhameln.typetogether.networking.util.DocumentCharacterFactory; import de.hswhameln.typetogether.networking.util.ExceptionHandler; import de.hswhameln.typetogether.networking.util.LoggerFactory; import javax.print.Doc; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import java.beans.PropertyChangeEvent; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class EditorListener implements DocumentListener { private final Logger logger = LoggerFactory.getLogger(this); private Document sharedDocument; private ClientUser user; private LocalDocument localDocument; private CommandInvoker invoker; private final PropertyChangeManager propertyChangeManager; public EditorListener(SessionStorage sessionStorage) { this.sharedDocument = sessionStorage.getCurrentSharedDocument(); this.invoker = sessionStorage.getCommandInvoker(); this.setUser(sessionStorage.getCurrentUser()); this.propertyChangeManager = new PropertyChangeManager(); sessionStorage.addPropertyChangeListener(this.propertyChangeManager); this.propertyChangeManager.onPropertyChange(ClientUser.LOCAL_DOCUMENT, this::localDocumentChanged); this.propertyChangeManager.onPropertyChange(SessionStorage.CURRENT_USER, this::currentUserChanged); this.propertyChangeManager.onPropertyChange(SessionStorage.CURRENT_SHARED_DOCUMENT, this::currentSharedDocumentChanged); } @Override public void insertUpdate(DocumentEvent e) { if (e instanceof CustomSwingDocument.MyDefaultDocumentEvent) { return; } if (this.user == null) { this.logger.warning("Author is null. Ignoring insertUpdate"); return; } if (this.localDocument == null) { this.logger.warning("LocalDocument is null. Ignoring insertUpdate"); return; } if (this.sharedDocument == null) { this.logger.warning("SharedDocument is null. Ignoring insertUpdate"); return; } String update = getStringFromDocumentEvent(e); this.logger.log(Level.INFO, "insertUpdate called, trying to insert string " + update); List<DocumentCharacter> documentCharacters = new ArrayList<>(e.getLength()); // the char that was the last one to be created and to which the next character from this batch must be appended. DocumentCharacter lastCreatedCharacter = null; for (char c : update.toCharArray()) { //Get Position of Changed Character(s) int index = e.getOffset() + 1; // Between old indices index - 1 and index <=> between new indices index - 1 and index + 1 //Get before and after DocumentCharacter previousCharacter = lastCreatedCharacter != null ? lastCreatedCharacter : this.localDocument.getDocumentCharacterOfIndex(index - 1); DocumentCharacter nextCharacter = this.localDocument.getDocumentCharacterOfIndex(index); DocumentCharacter characterToAdd = this.generateDocumentCharacter(previousCharacter, nextCharacter, c); lastCreatedCharacter = characterToAdd; this.logger.log(Level.INFO, "Generated document character " + characterToAdd + " between " + previousCharacter + " and " + nextCharacter + "."); documentCharacters.add(characterToAdd); } if (documentCharacters.size() == 1) { this.invoker.execute(new CreateDocumentCharacterCommand(documentCharacters.get(0), this.user, this.localDocument, this.sharedDocument)); return; } this.invoker.execute(new CreateDocumentCharactersCommand(documentCharacters, this.user, this.localDocument, this.sharedDocument)); } @Override public void removeUpdate(DocumentEvent e) { if (e instanceof CustomSwingDocument.MyDefaultDocumentEvent) { return; } if (this.user == null) { this.logger.warning("Author is null. Ignoring removeUpdate"); return; } if (this.localDocument == null) { this.logger.warning("LocalDocument is null. Ignoring removeUpdate"); return; } if (this.sharedDocument == null) { this.logger.warning("SharedDocument is null. Ignoring removeUpdate"); return; } this.logger.log(Level.INFO, "removeUpdate called, trying to remove string of length " + e.getLength() + ", starting at index " + e.getOffset() + "."); List<DocumentCharacter> documentCharacters = new ArrayList<>(e.getLength()); for (int i = 0; i < e.getLength(); i++) { //Get Position of Changed Character(s) int index = e.getOffset() + i + 1; // Get DocumentCharacter for position documentCharacters.add(this.localDocument.getDocumentCharacterOfIndex(index)); } if (documentCharacters.size() == 1) { this.invoker.execute(new DeleteDocumentCharacterCommand(documentCharacters.get(0), this.user, this.localDocument, this.sharedDocument)); return; } this.invoker.execute(new DeleteDocumentCharactersCommand(documentCharacters, this.user, this.localDocument, this.sharedDocument)); } @Override public void changedUpdate(DocumentEvent e) { //Plain text components do not fire these events } private String getStringFromDocumentEvent(DocumentEvent e) { String update = ""; try { update = e.getDocument().getText(e.getOffset(), e.getLength()); } catch (BadLocationException e1) { ExceptionHandler.getExceptionHandler().handle(e1, Level.SEVERE, "Error getting Position of change in Editor. Update is ignored.", EditorListener.class); } return update; } /** * charBefore and charAfter may be null */ private DocumentCharacter generateDocumentCharacter(DocumentCharacter charBefore, DocumentCharacter charAfter, char changedChar) { DocumentCharacter characterToAdd; if (charBefore != null && charAfter != null) { characterToAdd = DocumentCharacterFactory.getDocumentCharacter(changedChar, charBefore.getPosition(), charAfter.getPosition(), user.getId()); } else if (charBefore == null && charAfter != null) { throw new UnsupportedOperationException("Inserting a char before the first character should not be possible"); } else if (charBefore != null) { characterToAdd = DocumentCharacterFactory.getDocumentCharacter(changedChar, charBefore.getPosition(), user.getId()); } else { characterToAdd = new DocumentCharacter(changedChar, List.of(new Identifier(1, user.getId()))); } return characterToAdd; } private void localDocumentChanged(PropertyChangeEvent propertyChangeEvent) { setLocalDocument((LocalDocument) propertyChangeEvent.getNewValue()); } private void setLocalDocument(LocalDocument newLocalDocument) { this.localDocument = newLocalDocument; } private void currentSharedDocumentChanged(PropertyChangeEvent propertyChangeEvent) { this.sharedDocument = (Document) propertyChangeEvent.getNewValue(); } private void currentUserChanged(PropertyChangeEvent propertyChangeEvent) { setUser((ClientUser) propertyChangeEvent.getNewValue()); } private void setUser(ClientUser newUser) { if (this.user != null) { this.user.removePropertyChangeListener(this.propertyChangeManager); } this.user = newUser; if (this.user != null) { this.user.addPropertyChangeListener(this.propertyChangeManager); this.setLocalDocument((LocalDocument) this.user.getDocument()); } } }
<filename>gulpfile.js const gulp = require("gulp"); const postcss = require("gulp-postcss"); const stylelint = require("stylelint"); const gulpStylelint = require("gulp-stylelint"); const autoprefixer = require("autoprefixer"); const path = require("path"); const APP_PATH = path.join(__dirname, "app"); const STYLES_PATH = path.join(APP_PATH, "project*/**/*"); const DIST_PATH = path.join(APP_PATH, "dist"); gulp.task("css:lint", () => { return gulp.src(STYLES_PATH) .pipe(gulpStylelint({ reporters: [{ formatter: "verbose", console: true }] })); }); gulp.task("css:lint-fix", () => { return gulp.src(STYLES_PATH) .pipe(gulpStylelint({ failAfterError: false, fix: true })) .pipe(gulp.dest(APP_PATH)); }); gulp.task("autoprefixer", () => { function callback(file) { const parsers = { ".scss": require("postcss-scss"), ".less": require("postcss-less") }; return { plugins: [ autoprefixer({ browsers: [ "last 5 versions" ] }) ], options: { parser: parsers[file.extname] || false } }; } return gulp.src(STYLES_PATH, { base: "app" }) .pipe(postcss(callback)) .pipe(gulp.dest(DIST_PATH)); });
def number_of_paths(m, n): # Create a 2D array dp = [[0 for x in range(n)] for y in range(m)] # Fill out 1st row and 1st column # when moving either right or down for i in range(n): dp[0][i] = 1 for i in range(m): dp[i][0] = 1 # Fill out the remaining elements # using the number of paths of the location above and/or left for i in range(m): for j in range(n): dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[m - 1][n - 1]
const { expect } = require("chai"); const linthtml = require("../../../index"); const none = require("../../../presets").presets.none; function createLinter() { return new linthtml.LegacyLinter(linthtml.rules); } describe("head-valid-content-model", function() { it("Should report an error for every invalid child", async function() { const linter = createLinter(); const html = ` <html> <head> <div>a div</div> <p>a paragraph</p> </head> </html> `; const issues = await linter.lint(html, none, { "head-valid-content-model": true }); expect(issues).to.have.lengthOf(2); }); it("Should not report any error when <head> is not present", async function() { const linter = createLinter(); const html = ` <html> <body></body> </html> `; const issues = await linter.lint(html, none, { "head-valid-content-model": true }); expect(issues).to.have.lengthOf(0); }); it("Should not report any error for valid child element", async function() { const linter = createLinter(); const html = ` <html> <head> <title></title> <link></link> <script></script> <style></style> <template></template> <noscript></noscript> <meta></meta> </head> </html> `; const issues = await linter.lint(html, none, { "head-valid-content-model": true }); expect(issues).to.have.lengthOf(0); }); it("Should not report any error for empty <head> element", async function() { const linter = createLinter(); const html = ` <html> <head> </head> </html> `; const issues = await linter.lint(html, none, { "head-valid-content-model": true }); expect(issues).to.have.lengthOf(0); }); });
<filename>src/aguegu/dotmatrix/DMImage.java<gh_stars>10-100 package aguegu.dotmatrix; import java.awt.image.BufferedImage; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; public class DMImage extends BufferedImage { private static int blockWidth = 13; private static Color backgroundColor = Color.lightGray; private static Color onColor = Color.white; private static Color offColor = Color.gray; private static BasicStroke bs; private Graphics2D g2d; private boolean[] dot; public DMImage() { super(blockWidth * 8, blockWidth * 8, BufferedImage.TYPE_BYTE_GRAY); dot = new boolean[64]; g2d = this.createGraphics(); g2d.setBackground(backgroundColor); g2d.clearRect(0, 0, this.getWidth(), this.getHeight()); bs = new BasicStroke(blockWidth - 1); g2d.setStroke(bs); this.update(); } public void update() { for (int r = 0, y = blockWidth / 2; r < 8; r++, y += blockWidth) { for (int c = 0, x = blockWidth / 2; c < 8; c++, x += blockWidth) { g2d.setColor(dot[r * 8 + c] ? onColor : offColor); g2d.drawLine(x, y, x, y); } } } public void setDot(int index, boolean value) { try { dot[index] = value; } catch (ArrayIndexOutOfBoundsException ex) { } } public static int getBlockWidth() { return blockWidth; } }
maxdivider = 20 def task5(maxdivider): num = 11 test = 1 while test != 0: test = 0 for div in range(1,maxdivider): test += num%div num += 1 return num - 1 print(task5(maxdivider))
package com.watayouxiang.mediaplayer.utils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.widget.ImageView; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; /** * 简单的图片加载器 */ public class ImageLoader { private LoadImgHandler mLoadImgHandler; public ImageLoader(ImageView imageView) { mLoadImgHandler = new LoadImgHandler(imageView); } /** * 异步加载图片 * * @param url 图片地址 */ public void loadAsync(final String url) { new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = getBitmap(url); Message msg = mLoadImgHandler.obtainMessage(); msg.obj = bitmap; mLoadImgHandler.sendMessage(msg); } }).start(); } private Bitmap getBitmap(String url) { Bitmap bitmap = null; HttpURLConnection conn = null; InputStream is = null; try { URL imgUrl = new URL(url); conn = (HttpURLConnection) imgUrl .openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); conn.setDoInput(true); conn.connect(); is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (Exception e) { //e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (Exception e) { } if (conn != null) { conn.disconnect(); } } return bitmap; } private static class LoadImgHandler extends Handler { private WeakReference<ImageView> imageViewWeakReference; LoadImgHandler(ImageView imageView) { imageViewWeakReference = new WeakReference<>(imageView); } @Override public void handleMessage(Message msg) { ImageView imageView = imageViewWeakReference.get(); if (imageView == null) { return; } Bitmap bitmap = (Bitmap) msg.obj; imageView.setImageBitmap(bitmap); super.handleMessage(msg); } } }
#! /bin/bash DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) source $DIR/common.sh ID1=`$EXEC filelink --server=$SERVER -k --api_key=$KEY $DIR/send_test.sh` test_status "Couldn't create filelink" ID1=${ID1##* } ID1=${ID1##*/} ID2=`$EXEC attach --server=$SERVER -k --api_key=$KEY $DIR/attach_test.sh` test_status "Couldn't upload file" ID2=${ID2##* } ID2=`$EXEC filelink --server=$SERVER -k -r --api_key=$KEY $ID2` test_status "Couldn't create filelink" ID2=${ID2##* } ID2=${ID2##*/} $EXEC filelinks --server=$SERVER -k --api_key=$KEY test_status "Couldn't retrieve filelinks" $EXEC filelinks --server=$SERVER -k --api_key=$KEY --output_format=csv test_status "Couldn't retrieve filelinks in csv format" $EXEC delete_filelink --server=$SERVER -k --api_key=$KEY --filelink_id=$ID1 test_status "Couldn't delete filelink" $EXEC delete_filelink --server=$SERVER -k --api_key=$KEY --filelink_id=$ID2 test_status "Couldn't delete filelink" echo "Test PASSED."
import Mirage from 'ember-cli-mirage'; const avatarBase = 'http://slack.global.ssl.fastly.net/3654/img/avatars'; function avatar(i, size) { let x = (`000${i % 25}`).slice(-4); let suffix = size === 192 ? '' : `-${size}`; return `${avatarBase}/ava_${x}${suffix}.png`; } // jscs:disable requireCamelCaseOrUpperCaseIdentifiers export default Mirage.Factory.extend({ id: i => `U${2000 + i}BEGCF`, name: i => `user-${i}`, deleted: false, status: null, color: '9f69e7', real_name: i => `User-${i} Lastname`, tz: 'Europe/London', tz_label: 'London', tz_offset: 0, profile(i) { let first_name = `User-${i}`; return { first_name, last_name: 'Lastname', real_name: `${first_name} Lastname`, real_name_normalized: `${first_name} Lastname`, title: 'Cool Person', email: `<EMAIL>`, image_24: avatar(i, 24), image_32: avatar(i, 32), image_48: avatar(i, 48), image_72: avatar(i, 72), image_192: avatar(i, 192) }; }, is_admin: false, is_owner: false, is_primary_owner: false, is_restricted: false, is_ultra_restricted: false, is_bot: false, has_files: true, has_2fa: false }); // jscs:enable
const crypto = require('crypto') const chalk = require('chalk') const _createComparisonSignature = (body) => { const hmac = crypto.createHmac('sha1', process.env.secret) const self_signature = hmac.update(JSON.stringify(body)).digest('hex') return `sha1=${self_signature}` } const _compareSignatures = (signature, comparison_signature) => { const source = Buffer.from(signature) const comparison = Buffer.from(comparison_signature) return crypto.timingSafeEqual(source, comparison) } const verifyGithubPayload = (req, res, next) => { const { headers, body } = req const signature = headers['x-hub-signature'] const comparison_signature = _createComparisonSignature(body) if (!_compareSignatures(signature, comparison_signature)) { console.log(`${chalk.red("[Github]")} Invalid signature ${chalk.yellow(signature)}`) return res.status(401).send('Mismatched signatures') } const { action, ...payload } = body console.log(`${chalk.green("[Github]")} Valid signature.`) req.event_type = headers['x-github-event'] req.action = action req.payload = payload next() } module.exports = { verifyGithubPayload, }
<filename>src/ts/pages.ts import UsersStore from "./UsersStore"; export function setTemplate() { document.getElementById("app").innerHTML = ` <header class="header"> <div class="header__item"> <div class="header__item--logo"> <span class="logo-top">Match</span> <span class="logo-bottom">Match</span> </div> </div> <nav class="navbar"> <div class="navbar__item active"> <a href="#" class="page-render" id="page-about" data-value="about"> <svg> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-about"></use> </svg> <h4>About Game</h4> </a> </div> <div class="navbar__item"> <a href="#" class="page-render" id="page-rank" data-value="ranking"> <svg> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-star"></use> </svg> <h4>Best Score</h4> </a> </div> <div class="navbar__item"> <a href="#" class="page-render" data-value="settings"> <svg> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-settings"></use> </svg> <h4>Game Settings</h4> </a> </div> </nav> <div class="header__item"> <a href="#" class="btn btn--ghost page-render not-signed-in" data-value="registration" id="register">Register New Player</a> <a href="#" class="btn btn--ghost page-render signed-in" data-value="game" id="start">Start Game</a> <a href="#" class="btn btn--ghost signed-in" id="quit">Quit</a> <div class="profile-avatar signed-in"> <div id="nav-avatar"></div> </div> </div> </header> <main id="main"></main> `; } export async function renderPage( page: "about" | "ranking" | "settings" | "game" | "reg", gameSettings?: { gridSize: number; cardType: string } ): Promise<void> { if (page === "about") { document.getElementById("main").innerHTML = ` <main class="instr"> <h1 class="h1">How to play?</h1> <section class="instr__item"> <div class="instr__content"> <span class="instr__number">1</span> <p class="instr__text">Register new player in game</p> </div> <img src=${require("../img/instr-1.png")} class="instr__img"></img> </section> <section class="instr__item"> <div class="instr__content"> <span class="instr__number">2</span> <p class="instr__text">Configure your game settings</p> </div> <img src=${require("../img/instr-2.png")} class="instr__img"></img> </section> <section class="instr__item"> <div class="instr__content"> <span class="instr__number">3</span> <p class="instr__text">Start your new game!</p> </div> <img src=${require("../img/instr-3.png")} class="instr__img"></img> </section> </main> `; } else if (page === "ranking") { const users = await new UsersStore().getAllUsers(); document.getElementById("main").innerHTML = ` <main class="rank"> <div class="rank__container"> <h1 class="h1">Best Players</h1> <ul class="rank__list" id="rank-list"></ul> </div> </main> `; setTimeout(() => { users .sort((x, y) => y.score - x.score) .forEach((user) => { document.getElementById("rank-list").innerHTML += ` <li class="rank__item"> <div class="rank__item-container"> <div id="rank-avatar" style="background-image: url(${ user.avatar ? user.avatar : require("../img/profile.png") })" alt="User 1"></div> <div class="rank__item-details"> <h3>${user.firstName} ${user.lastName}</h3> <p>${user.email}</p> </div> </div> <h3 class="rank__item-score">Score: <span>${user.score}</span></h3> </li>`; }); }, 100); } else if (page === "settings") { document.getElementById("main").innerHTML = ` <main class="settings"> <div class="settings__container"> <label class="h1" for="card-type">Game Cards</label> <select name="card-type" id="card-type" class="settings__input"> <option value="" selected>select game cards type</option> <option value="animal">Animals</option> <option value="flag">Flags</option> </select> <label class="h1" for="difficulty">Difficulty</label> <select name="difficulty" id="difficulty" class="settings__input"> <option value="" selected>select game type</option> <option value="4">4x4</option> <option value="6">6x6</option> <option value="8">8x8</option> </select> </div> </main> `; } else if (page === "game") { const gameModeSetup = () => { const cardIndexes: number[] = []; if (gameSettings.gridSize === 4) { for (let i = 1; i <= 8; i += 1) { cardIndexes.push(i, i); } } else if (gameSettings.gridSize === 6) { for (let i = 1; i <= 9; i += 1) { cardIndexes.push(i, i, i, i); } } else if (gameSettings.gridSize === 8) { for (let i = 1; i <= 8; i += 1) { cardIndexes.push(i, i, i, i, i, i, i, i); } } return cardIndexes.sort(() => 0.5 - Math.random()); }; document.getElementById("main").innerHTML = ` <main class="game"> <div class="game__container"> <div class="game__timer">00:00</div> <div class="game__cards" id="game-cards"></div> </div> </main> `; document.getElementById("game-cards").setAttribute( "style", ` grid-template-columns: repeat(${gameSettings.gridSize}, 15%); grid-template-rows: repeat(${gameSettings.gridSize}, 15%); ` ); gameModeSetup().forEach((i) => { document.getElementById("game-cards").innerHTML += ` <div class="game__card" data-id="photo${i}"> <div class="game__card--front"> <img src=${require("../img/mask.png")} alt="Mask"> </div> <div class="game__card--back"> <img src=${require(`../img/card-images/${gameSettings.cardType}-${i}.jpg`)} alt="Mask"> </div> </div> `; }); } else if (page === "reg") { document.getElementById("app").insertAdjacentHTML( "beforeend", ` <section class="reg" id="reg-window"> <!-- add "active" class-name to make it visible --> <div class="reg__window"> <h1 class="h1">Register new Player</h1> <div class="reg__form"> <div class="reg__form--main" action="#"> <label for="first-name" class="reg__label"> First Name <input type="text" id="first-name" name="first-name" class="reg__input"> <svg class="visible"> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-tick"></use> </svg> </label> <label for="last-name" class="reg__label"> Last Name <input type="text" id="last-name" name="last-name" class="reg__input"> <svg class="visible"> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-tick"></use> </svg> </label> <label for="email" class="reg__label"> E-mail <input type="email" id="email" name="email" class="reg__input"> <svg class="visible"> <use xlink:href="${require("../fonts/symbol-defs.svg")}#i-tick"></use> </svg> </label> </div> <div class="reg__form--avatar"> <label for="avatar"> <input type="file" id="avatar" class="reg__input" accept="image/png, image/jpg, image/jpeg"> <div id="avatar-image"></div> </label> </div> <div class="reg__buttons"> <a href="#" class="btn btn--dark disabled" id="add-user">Add User</a> <a href="#" class="btn btn--light" id="cancel-reg">Cancel</a> </div> </div> </div> </section> ` ); } }
#!/bin/sh rm thx.core.zip zip -r thx.core.zip hxml src doc/ImportCore.hx test extraParams.hxml haxelib.json LICENSE README.md haxelib submit thx.core.zip
public class MicrophoneSpeakerManager : MonoBehaviour { private List<Microphone> availableMicrophones = new List<Microphone>(); private List<Speaker> availableSpeakers = new List<Speaker>(); private void Start() { RefreshMicrophonesButtonOnClickHandler(); listener.SpeakersUpdatedEvent += SpeakersUpdatedEventHandler; } private void Update() { // Continuously update the system // Your implementation here } private void RefreshMicrophonesButtonOnClickHandler() { // Refresh the list of available microphones availableMicrophones = MicrophoneManager.GetAvailableMicrophones(); } private void SpeakersUpdatedEventHandler(object sender, EventArgs e) { // Handle updates to the list of speakers availableSpeakers = SpeakerManager.GetAvailableSpeakers(); } }
fun main() { var n1:Int=0 var n2:Int=1 var n3:Int println(n1) println(n2) for(i in 0..18){ n3=n1+n2 n1=n2 n2=n3 println(n3) } }
#!/bin/bash # shellcheck source=./common.sh source "$(dirname "${BASH_SOURCE[0]}")/common.sh" if [[ ${BUILD_ENVIRONMENT} == *onnx* ]]; then pip install click mock tabulate networkx==2.0 pip -q install --user "file:///var/lib/jenkins/workspace/third_party/onnx#egg=onnx" fi # Skip tests in environments where they are not built/applicable if [[ "${BUILD_ENVIRONMENT}" == *-android* ]]; then echo 'Skipping tests' exit 0 fi if [[ "${BUILD_ENVIRONMENT}" == *-rocm* ]]; then # temporary to locate some kernel issues on the CI nodes export HSAKMT_DEBUG_LEVEL=4 fi # These additional packages are needed for circleci ROCm builds. if [[ $BUILD_ENVIRONMENT == *rocm* ]]; then # Need networkx 2.0 because bellmand_ford was moved in 2.1 . Scikit-image by # defaults installs the most recent networkx version, so we install this lower # version explicitly before scikit-image pulls it in as a dependency pip install networkx==2.0 # click - onnx pip install --progress-bar off click protobuf tabulate virtualenv mock typing-extensions fi # Find where cpp tests and Caffe2 itself are installed if [[ "$BUILD_ENVIRONMENT" == *cmake* ]]; then # For cmake only build we install everything into /usr/local cpp_test_dir="$INSTALL_PREFIX/cpp_test" ld_library_path="$INSTALL_PREFIX/lib" else # For Python builds we install into python # cd to /usr first so the python import doesn't get confused by any 'caffe2' # directory in cwd python_installation="$(dirname $(dirname $(cd /usr && $PYTHON -c 'import os; import caffe2; print(os.path.realpath(caffe2.__file__))')))" caffe2_pypath="$python_installation/caffe2" cpp_test_dir="$python_installation/torch/test" ld_library_path="$python_installation/torch/lib" fi ################################################################################ # C++ tests # ################################################################################ # Only run cpp tests in the first shard, don't run cpp tests a second time in the second shard if [[ "${SHARD_NUMBER:-1}" == "1" ]]; then echo "Running C++ tests.." for test in $(find "$cpp_test_dir" -executable -type f); do case "$test" in # skip tests we know are hanging or bad */mkl_utils_test|*/aten/integer_divider_test) continue ;; */scalar_tensor_test|*/basic|*/native_test) if [[ "$BUILD_ENVIRONMENT" == *rocm* ]]; then continue else LD_LIBRARY_PATH="$ld_library_path" "$test" fi ;; */*_benchmark) LD_LIBRARY_PATH="$ld_library_path" "$test" --benchmark_color=false ;; *) # Currently, we use a mixture of gtest (caffe2) and Catch2 (ATen). While # planning to migrate to gtest as the common PyTorch c++ test suite, we # currently do NOT use the xml test reporter, because Catch doesn't # support multiple reporters # c.f. https://github.com/catchorg/Catch2/blob/master/docs/release-notes.md#223 # which means that enabling XML output means you lose useful stdout # output for Jenkins. It's more important to have useful console # output than it is to have XML output for Jenkins. # Note: in the future, if we want to use xml test reporter once we switch # to all gtest, one can simply do: LD_LIBRARY_PATH="$ld_library_path" \ "$test" --gtest_output=xml:"$gtest_reports_dir/$(basename $test).xml" ;; esac done fi ################################################################################ # Python tests # ################################################################################ if [[ "$BUILD_ENVIRONMENT" == *cmake* ]]; then exit 0 fi # If pip is installed as root, we must use sudo. # CircleCI docker images could install conda as jenkins user, or use the OS's python package. PIP=$(which pip) PIP_USER=$(stat --format '%U' $PIP) CURRENT_USER=$(id -u -n) if [[ "$PIP_USER" = root && "$CURRENT_USER" != root ]]; then MAYBE_SUDO=sudo fi # Uninstall pre-installed hypothesis and coverage to use an older version as newer # versions remove the timeout parameter from settings which ideep/conv_transpose_test.py uses $MAYBE_SUDO pip -q uninstall -y hypothesis $MAYBE_SUDO pip -q uninstall -y coverage # "pip install hypothesis==3.44.6" from official server is unreliable on # CircleCI, so we host a copy on S3 instead $MAYBE_SUDO pip -q install attrs==18.1.0 -f https://s3.amazonaws.com/ossci-linux/wheels/attrs-18.1.0-py2.py3-none-any.whl $MAYBE_SUDO pip -q install coverage==4.5.1 -f https://s3.amazonaws.com/ossci-linux/wheels/coverage-4.5.1-cp36-cp36m-macosx_10_12_x86_64.whl $MAYBE_SUDO pip -q install hypothesis==3.44.6 -f https://s3.amazonaws.com/ossci-linux/wheels/hypothesis-3.44.6-py3-none-any.whl # Collect additional tests to run (outside caffe2/python) EXTRA_TESTS=() # CUDA builds always include NCCL support if [[ "$BUILD_ENVIRONMENT" == *-cuda* ]] || [[ "$BUILD_ENVIRONMENT" == *-rocm* ]]; then EXTRA_TESTS+=("$caffe2_pypath/contrib/nccl") fi rocm_ignore_test=() if [[ $BUILD_ENVIRONMENT == *-rocm* ]]; then # Currently these tests are failing on ROCM platform: # On ROCm, RCCL (distributed) development isn't complete. # https://github.com/ROCmSoftwarePlatform/rccl rocm_ignore_test+=("--ignore $caffe2_pypath/python/data_parallel_model_test.py") # This test has been flaky in ROCm CI (but note the tests are # cpu-only so should be unrelated to ROCm) rocm_ignore_test+=("--ignore $caffe2_pypath/python/operator_test/blobs_queue_db_test.py") # This test is skipped on Jenkins(compiled without MKL) and otherwise known flaky rocm_ignore_test+=("--ignore $caffe2_pypath/python/ideep/convfusion_op_test.py") # This test is skipped on Jenkins(compiled without MKL) and causing segfault on Circle rocm_ignore_test+=("--ignore $caffe2_pypath/python/ideep/pool_op_test.py") fi echo "Running Python tests.." # locale setting is required by click package for loc in "en_US.utf8" "C.UTF-8"; do if locale -a | grep "$loc" >/dev/null 2>&1; then export LC_ALL="$loc" export LANG="$loc" break; fi done # Some Caffe2 tests fail when run using AVX512 ISA, see https://github.com/pytorch/pytorch/issues/66111 export DNNL_MAX_CPU_ISA=AVX2 # Should still run even in the absence of SHARD_NUMBER if [[ "${SHARD_NUMBER:-1}" == "1" ]]; then pip install --user pytest-sugar # NB: Warnings are disabled because they make it harder to see what # the actual erroring test is "$PYTHON" \ -m pytest \ -x \ -v \ --disable-warnings \ --junit-xml="$pytest_reports_dir/result.xml" \ --ignore "$caffe2_pypath/python/test/executor_test.py" \ --ignore "$caffe2_pypath/python/operator_test/matmul_op_test.py" \ --ignore "$caffe2_pypath/python/operator_test/pack_ops_test.py" \ --ignore "$caffe2_pypath/python/mkl/mkl_sbn_speed_test.py" \ --ignore "$caffe2_pypath/python/trt/test_pt_onnx_trt.py" \ ${rocm_ignore_test[@]} \ "$caffe2_pypath/python" \ "${EXTRA_TESTS[@]}" fi ############## # ONNX tests # ############## if [[ "$BUILD_ENVIRONMENT" == *onnx* ]]; then # Check out torch/vision at 0.9.0-rc1 commit # This hash must match one in .jenkins/pytorch/test.sh pip install -q --user git+https://github.com/pytorch/vision.git@8a2dc6f22ac4389ccba8859aa1e1cb14f1ee53db pip install -q --user ninja flatbuffers==2.0 numpy==1.21.5 onnxruntime==1.11.0 # numba requires numpy <= 1.20, onnxruntime requires numpy >= 1.21. # We don't actually need it for our tests, but it's imported if it's present, so uninstall. pip uninstall -q --yes numba # JIT C++ extensions require ninja, so put it into PATH. export PATH="/var/lib/jenkins/.local/bin:$PATH" "$ROOT_DIR/scripts/onnx/test.sh" fi
<gh_stars>10-100 package io.opensphere.csv.config.v2; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import javax.xml.bind.JAXBException; import org.junit.Assert; import org.junit.Test; import io.opensphere.core.util.Utilities; import io.opensphere.core.util.XMLUtilities; import io.opensphere.csvcommon.config.v1.CSVColumnInfo; import io.opensphere.csvcommon.config.v2.CSVDelimitedColumnFormat; import io.opensphere.csvcommon.config.v2.CSVParseParameters; import io.opensphere.importer.config.ColumnType; import io.opensphere.importer.config.LayerSettings; import io.opensphere.importer.config.SpecialColumn; import io.opensphere.mantle.data.LoadsTo; /** Tests for {@link CSVDataSource}. */ public class CSVDataSourceTest { /** Column for testing. */ private static final String COL1 = "col1"; /** Column for testing. */ private static final String COL2 = "col2"; /** Column for testing. */ private static final String COL3 = "col3"; /** * Test marshalling and unmarshalling. * * @throws JAXBException If there is a JAXB error. */ @Test public void testMarshalling() throws JAXBException { CSVDataSource input = getTestObject(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLUtilities.writeXMLObject(input, outputStream, CSVDataSource.class.getPackage()); CSVDataSource result = XMLUtilities.readXMLObject(new ByteArrayInputStream(outputStream.toByteArray()), CSVDataSource.class, CSVDataSource.class.getPackage()); Assert.assertEquals(input, result); } /** * Test clone. */ @Test public void testClone() { CSVDataSource input = getTestObject(); CSVDataSource clone = input.clone(); Assert.assertTrue(Utilities.notSameInstance(input, clone)); Assert.assertTrue(Utilities.sameInstance(input.getClass(), clone.getClass())); Assert.assertEquals(input, clone); } /** * Tests the generate type key. */ @Test public void testGenerateTypeKey() { CSVDataSource dataSource = getTestObject(); File file = new File("x:\\sample_files\\test.csv"); URI uri = file.toURI(); dataSource.setSourceUri(uri); String expectedTypeKey = "CSV::" + dataSource.getName() + "::" + file.getAbsolutePath(); Assert.assertEquals(expectedTypeKey, dataSource.generateTypeKey()); } /** * Creates a CSVDataSource test object. * * @return the CSVDataSource */ public static CSVDataSource getTestObject() { CSVDataSource dataSource = new CSVDataSource(); dataSource.setParseParameters(getParamsObject()); dataSource.setLayerSettings(getLayerSettingsTestObject()); try { dataSource.setSourceUri(new URI("file:///tmp/test.csv")); } catch (URISyntaxException e) { Assert.fail(e.getMessage()); } dataSource.setVisible(false); return dataSource; } /** * Creates a CSVLayerSettings test object. * * @return the CSVLayerSettings */ public static LayerSettings getLayerSettingsTestObject() { LayerSettings layerSettings = new LayerSettings("Tommy"); layerSettings.setLoadsTo(LoadsTo.STATIC); layerSettings.setColor(Color.YELLOW); layerSettings.setActive(true); return layerSettings; } /** * Creates a CSVParseParameters test object. * * @return the CSVParseParameters */ private static CSVParseParameters getParamsObject() { CSVParseParameters parseParameters = new CSVParseParameters(); SpecialColumn dateColumn = new SpecialColumn(); dateColumn.setColumnIndex(5); dateColumn.setColumnType(ColumnType.DATE); dateColumn.setFormat("format"); parseParameters.getSpecialColumns().add(dateColumn); parseParameters.setColumnFormat(new CSVDelimitedColumnFormat(":", "'", 4)); parseParameters.setColumnNames(Arrays.asList(COL1, COL2, COL3)); parseParameters.setCommentIndicator("!"); parseParameters.setDataStartLine(Integer.valueOf(5)); parseParameters.setHeaderLine(Integer.valueOf(2)); parseParameters.getColumnClasses().add(new CSVColumnInfo("java.lang.Float", 1, 2, true)); return parseParameters; } }
<filename>func-core/src/test/java/cyclops/container/foldable/AbstractConvertableSequenceTest.java package cyclops.container.foldable; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import cyclops.container.immutable.impl.ConvertableSequence; import java.util.Comparator; import org.junit.Test; public abstract class AbstractConvertableSequenceTest { public abstract <T> ConvertableSequence<T> of(T... elements); public abstract <T> ConvertableSequence<T> empty(); @Test public void emptyConvert() { assertFalse(empty().option() .isPresent()); assertFalse(empty().seq() .size() > 0); assertFalse(empty().lazySeq() .size() > 0); assertFalse(empty().vector() .size() > 0); assertFalse(empty().bankersQueue() .size() > 0); assertFalse(empty().hashSet() .size() > 0); assertFalse(empty().treeSet((Comparator) Comparator.naturalOrder()) .size() > 0); assertFalse(empty().hashMap(t -> t, t -> t) .size() > 0); } @Test public void presentConvert() { assertTrue(of(1).option() .isPresent()); assertTrue(of(1).seq() .size() > 0); assertTrue(of(1).lazySeq() .size() > 0); assertTrue(of(1).bankersQueue() .size() > 0); assertTrue(of(1).vector() .size() > 0); assertTrue(of(1).hashSet() .size() > 0); assertTrue(of(1).treeSet(Comparator.naturalOrder()) .size() > 0); assertTrue(of(1).bag() .size() > 0); assertTrue(of(1).hashMap(t -> t, t -> t) .size() > 0); } @Test public void lazyString() { assertThat(of(1, 2).lazyString() .toString(), equalTo(of(1, 2).stream() .join(", "))); } @Test public void lazyStringEmpty() { assertThat(empty().lazyString() .toString(), equalTo(empty().stream() .join(","))); } }
<reponame>savvasth96/fructose /** * Reinforcement Q-learning. */ package fwcd.fructose.ml.rl.qlearn;
#!/bin/sh #--------------------------------------------------------------------------- # Copyright 2006-2009 # Dan Roozemond, d.a.roozemond@tue.nl, (TU Eindhoven, Netherlands) # Peter Horn, horn@math.uni-kassel.de (University Kassel, Germany) # # 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. #--------------------------------------------------------------------------- exec java -Dorg.mortbay.util.FileResource.checkAliases=false -jar target/wupsi.jar "$@"
import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # Create a model model = Sequential() model.add(Dense(4, activation="relu", input_dim=1)) model.add(Dense(2, activation="sigmoid")) model.compile(loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"]) # Train the model x = np.array([0, 1, 2, 3, 4, 5]) y = np.array([0, 1, 0, 1, 0, 1]) model.fit(x, y, epochs=100)
package binary_search; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author minchoba * 백준 16401번: 과자나눠주기 * * @see https://www.acmicpc.net/problem/16401/ * */ public class Boj16401 { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int M = Integer.parseInt(st.nextToken()); int N = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int[] snack = new int[N]; int max = 0; long target = 0; for(int i = 0; i < N; i++) { snack[i] = Integer.parseInt(st.nextToken()); if(snack[i] > max) max = snack[i]; target += snack[i]; } System.out.println(binarySearch(M, N, snack, max, target >= M ? 1: 0)); } private static long binarySearch(int m, int n, int[] arr, int end, long leng) { int start = 0; while(start <= end) { int mid = (start + end) / 2; if(mid == 0) break; int count = 0; for(int i = 0; i < n; i++) { // mid 길이로 조카들에게 분배 가능한지 확인 count += (arr[i] / mid); } if(count >= m) { // 가능한경우 길이를 더 키워서 진행 leng = mid; start = mid + 1; } else { // 불가능한 경우 길이를 줄여봄 end = mid - 1; } } return leng; } }
<filename>cohort/week12/CacheV1.java import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class CacheV1 { // Iterators returned by ConcurrentHashMap are weakly consistent instead of fail-fast (it also // employs lock stripping and does not support client-based locking) private final ConcurrentHashMap<Integer, List<Integer>> results = new ConcurrentHashMap<Integer, List<Integer>>(); // the factors must be the factors of // the corresponding number // This is a big problem if factor(a) is required to execute once-and-only-once (no redundant // computations). public List<Integer> service(int input) { List<Integer> factors = results.get(input); if (factors == null) { factors = factor(input); results.put(input, factors); } return factors; } public List<Integer> factor(int n) { List<Integer> factors = new ArrayList<Integer>(); for (int i = 2; i <= n; i++) { while (n % i == 0) { factors.add(i); n /= i; } } return factors; } }
<filename>app/views/groups/show.json.jbuilder json.extract! @group, :id, :name, :value, :description, :created_at, :updated_at
#!/bin/bash if [[ $target_platform =~ linux.* ]] || [[ $target_platform == win-32 ]] || [[ $target_platform == win-64 ]] || [[ $target_platform == osx-64 ]]; then export DISABLE_AUTOBREW=1 $R CMD INSTALL --build . else mkdir -p $PREFIX/lib/R/library/gtsummary mv * $PREFIX/lib/R/library/gtsummary if [[ $target_platform == osx-64 ]]; then pushd $PREFIX for libdir in lib/R/lib lib/R/modules lib/R/library lib/R/bin/exec sysroot/usr/lib; do pushd $libdir || exit 1 for SHARED_LIB in $(find . -type f -iname "*.dylib" -or -iname "*.so" -or -iname "R"); do echo "fixing SHARED_LIB $SHARED_LIB" install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5.0-MRO/Resources/lib/libR.dylib "$PREFIX"/lib/R/lib/libR.dylib $SHARED_LIB || true install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libR.dylib "$PREFIX"/lib/R/lib/libR.dylib $SHARED_LIB || true install_name_tool -change /usr/local/clang4/lib/libomp.dylib "$PREFIX"/lib/libomp.dylib $SHARED_LIB || true install_name_tool -change /usr/local/gfortran/lib/libgfortran.3.dylib "$PREFIX"/lib/libgfortran.3.dylib $SHARED_LIB || true install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libquadmath.0.dylib "$PREFIX"/lib/libquadmath.0.dylib $SHARED_LIB || true install_name_tool -change /usr/local/gfortran/lib/libquadmath.0.dylib "$PREFIX"/lib/libquadmath.0.dylib $SHARED_LIB || true install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libgfortran.3.dylib "$PREFIX"/lib/libgfortran.3.dylib $SHARED_LIB || true install_name_tool -change /usr/lib/libgcc_s.1.dylib "$PREFIX"/lib/libgcc_s.1.dylib $SHARED_LIB || true install_name_tool -change /usr/lib/libiconv.2.dylib "$PREFIX"/sysroot/usr/lib/libiconv.2.dylib $SHARED_LIB || true install_name_tool -change /usr/lib/libncurses.5.4.dylib "$PREFIX"/sysroot/usr/lib/libncurses.5.4.dylib $SHARED_LIB || true install_name_tool -change /usr/lib/libicucore.A.dylib "$PREFIX"/sysroot/usr/lib/libicucore.A.dylib $SHARED_LIB || true install_name_tool -change /usr/lib/libexpat.1.dylib "$PREFIX"/lib/libexpat.1.dylib $SHARED_LIB || true install_name_tool -change /usr/lib/libcurl.4.dylib "$PREFIX"/lib/libcurl.4.dylib $SHARED_LIB || true install_name_tool -change /usr/lib/libc++.1.dylib "$PREFIX"/lib/libc++.1.dylib $SHARED_LIB || true install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libc++.1.dylib "$PREFIX"/lib/libc++.1.dylib $SHARED_LIB || true done popd done popd fi fi
read_default_username() { local file_path="$1" local read_result=$(read_field_from_file 'default_username' "$file_path") printf "$read_result" } read_default_host_address() { local file_path="$1" local read_result=$(read_field_from_file 'default_host_address' "$file_path") printf "$read_result" } read_default_key_file_name() { local file_path="$1" local read_result=$(read_field_from_file 'default_key_file_name' "$file_path") printf "$read_result" }
<filename>models/hotels.js module.exports = function(sequelize, DataTypes) { var Hotel = sequelize.define("Hotel", { name: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true } }, rating: { type: DataTypes.DECIMAL, allowNull: true, }, city: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true } } }); Hotel.associate = function(models) { //associating hotels with reviews Hotel.hasMany(models.Review, { onDelete: "cascade" }); }; Hotel.associate = function(models) { Hotel.belongsTo(models.User, { foreignKey : { allowNull : false } }); }; // Hotel.associate = function(models) { // Hotel.belongsTo(models.Search, { // foreignKey : { // allowNull : false // } // }); // }; return Hotel; };
<reponame>glowroot/glowroot-instrumentation<filename>instrumentation-test-matrix/src/main/java/org/glowroot/instrumentation/test/matrix/ApacheHttpAsyncClient.java /** * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.glowroot.instrumentation.test.matrix; import static org.glowroot.instrumentation.test.matrix.JavaVersion.JAVA6; import static org.glowroot.instrumentation.test.matrix.JavaVersion.JAVA7; import static org.glowroot.instrumentation.test.matrix.JavaVersion.JAVA8; public class ApacheHttpAsyncClient { private static final String MODULE_PATH = "instrumentation/apache-http-async-client"; public static void main(String[] args) throws Exception { if (args.length == 1 && args[0].equals("short")) { runShort(); } else { runAll(); } } static void runShort() throws Exception { run("4.0"); } static void runAll() throws Exception { run("4.0"); run("4.0.1"); run("4.0.2"); run("4.1"); run("4.1.1"); run("4.1.2"); run("4.1.3"); } private static void run(String version) throws Exception { Util.updateLibVersion(MODULE_PATH, "apachehttpasyncclient.version", version); Util.runTests(MODULE_PATH, JAVA8, JAVA7, JAVA6); } }
#!/bin/sh echo "stopping nomatrix MN ..." docker stop nomatrix echo DONE!
<filename>src/components/methodUI.styles.tsx import styled from "styled-components"; export const MethodWrapper = styled.div` display: flex; flex-direction: column; background: white; padding: var(--space-m); border: 1px solid; border-radius: 0.4rem; `; export const Banner = styled.div` font-size: var(--font-size-s); background: var(--pastel-gradient); padding: var(--space-xs) var(--space-s); border-radius: 8px; margin: 0 0 var(--space-s); `; export const Caption = styled.p` margin-top: 0; code { font-size: var(--font-size-s); } `; export const Desc = styled.p` font-size: var(--font-size-s); line-height: 1.3; margin: 0 0 var(--space-xxs); `; export const Arg = styled.div` margin-bottom: var(--space-l); `; export const Footer = styled.div` display: flex; align-items: center; gap: var(--space-m); `; export const Button = styled.button` color: var(--grey-darkest); font-weight: bold; background: var(--color-primary); padding: var(--space-xs) var(--space-m); border: 1px solid transparent; border-radius: 4px; cursor: pointer; &:hover { background-color: var(--color-primary-light); } &[disabled] { background: var(--grey-light); cursor: default; } `; export const Return = styled.div` display: flex; align-items: center; font-size: var(--font-size-s); column-gap: 0.2rem; ${Desc} { margin: 0; } `; export const ReturnHeader = styled.p` display: flex; align-items: center; gap: var(--space-xs); margin: 0; `; export const ResultWrapper = styled.div` margin-top: var(--space-l); p { font-size: var(--font-size-xs); margin: 0 0 var(--space-s); } `; export const Result = styled.pre` font-size: var(--font-size-s); padding: var(--space-m); border: 1px solid var(--grey-light); border-radius: 4px; margin: 0; white-space: pre-wrap; `;
#!/usr/bin/env bash # # Copyright (c) 2018 The Readercoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. export LC_ALL=C.UTF-8 PATH=$(echo $PATH | tr ':' "\n" | sed '/\/opt\/python/d' | tr "\n" ":" | sed "s|::|:|g") # Add llvm-symbolizer directory to PATH. Needed to get symbolized stack traces from the sanitizers. PATH=$PATH:/usr/lib/llvm-6.0/bin/ export PATH BEGIN_FOLD () { echo "" CURRENT_FOLD_NAME=$1 echo "travis_fold:start:${CURRENT_FOLD_NAME}" } END_FOLD () { RET=$? echo "travis_fold:end:${CURRENT_FOLD_NAME}" if [ $RET != 0 ]; then echo "${CURRENT_FOLD_NAME} failed with status code ${RET}" fi }
<gh_stars>0 import 'jest'; // @ts-ignore import PROJECT from '[PROJECT NAME]'; describe('example test suite', () => {});
import { useStaticQuery, graphql } from "gatsby" import Img from "gatsby-image" import React, { useEffect } from "react" import { ExtraImageProps } from "../../../../../types/shared" const alt = { sensojiGarden: "Senso-Ji Garden", sensojiGarden2: "Senso-Ji Garden", sensojiGarden3: "Senso-Ji Garden", sensojiGarden4: "Senso-Ji Garden", sensojiGarden5: "Senso-Ji Garden", sensojiGarden6: "Senso-Ji Garden", sensojiGarden7: "Senso-Ji Garden", sensojiComplex: "Senso-Ji Complex", sensojiComplex2: "Senso-Ji Complex", sensojiComplex3: "Senso-Ji Complex", sensojiComplex4: "Senso-Ji Complex", sensojiComplex5: "Senso-Ji Complex", sensojiComplex6: "Senso-Ji Complex", sensojiComplex7: "Senso-Ji Complex", sensojiComplex8: "Senso-Ji Complex", sensojiComplex9: "Senso-Ji Complex", sensojiComplex10: "Senso-Ji Complex", sensojiComplex11: "Senso-Ji Complex", sensojiComplex12: "Senso-Ji Complex", sensojiComplex13: "Senso-Ji Complex", sensojiComplex14: "Senso-Ji Complex", sensojiComplex15: "Senso-Ji Complex", sensojiComplex16: "Senso-Ji Complex", sensojiComplex17: "Senso-Ji Complex", sensojiComplex18: "Senso-Ji Complex", sensojiComplex19: "Senso-Ji Complex", cardFr1: "Senso-Ji Temple Pinterest card", cardFr2: "Senso-Ji Temple Pinterest card", cardEn1: "Senso-Ji Temple Pinterest card", cardEn2: "Senso-Ji Temple Pinterest card", } export const SensojiImages: React.FunctionComponent<ExtraImageProps & { image: keyof typeof alt }> = ({ className = "", image, fluidObject = {}, imgStyle = {}, onLoad, }) => { const data = useStaticQuery(graphql` query { sensojiGarden: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-garden.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiGarden2: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-garden2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiGarden3: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-garden3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiGarden4: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-garden4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiGarden5: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-garden5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiGarden6: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-garden6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiGarden7: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-garden7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex2: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex3: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex4: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex5: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex6: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex7: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex8: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex9: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex10: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex10.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex11: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex11.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex12: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex12.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex13: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex13.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex14: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex14.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex15: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex15.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex16: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex16.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex17: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex17.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex18: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex18.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sensojiComplex19: file(relativePath: { eq: "asia/japan/tokyo/sensoji/sensoji-complex19.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } cardFr1: file(relativePath: { eq: "asia/japan/tokyo/sensoji/card-fr1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardFr2: file(relativePath: { eq: "asia/japan/tokyo/sensoji/card-fr2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn1: file(relativePath: { eq: "asia/japan/tokyo/sensoji/card-en1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn2: file(relativePath: { eq: "asia/japan/tokyo/sensoji/card-en2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } } `) useEffect(() => { if (onLoad) onLoad(data[image].childImageSharp.fluid.src) }, [data, image, onLoad]) return ( <Img fluid={{ ...data[image].childImageSharp.fluid, ...fluidObject }} alt={alt[image]} className={className} imgStyle={imgStyle} /> ) }
<gh_stars>1-10 #include <stdio.h> #include <string.h> #include <math.h> #include <time.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "mmt_core.h" #ifdef _WIN32 #include <ws2tcpip.h> #else #include <arpa/inet.h> //inet_ntop #include <netinet/in.h> #endif #ifdef _WIN32 #include <time.h> #include <windows.h> #endif #include "processing.h" #include <sys/ioctl.h> #include <net/if.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <errno.h> #include <pthread.h> #include <sys/types.h> #ifdef linux #include <syscall.h> #endif #include <netinet/ip.h> #include "tcpip/mmt_tcpip.h" #ifdef _WIN32 #ifndef socklen_t typedef int socklen_t; #define socklen_t socklen_t #endif #endif #if (_WIN32_WINNT) void WSAAPI freeaddrinfo(struct addrinfo*); int WSAAPI getaddrinfo(const char*, const char*, const struct addrinfo*, struct addrinfo**); int WSAAPI getnameinfo(const struct sockaddr*, socklen_t, char*, DWORD, char*, DWORD, int); #endif #ifdef _WIN32 const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) { if (af == AF_INET) { struct sockaddr_in in; memset(&in, 0, sizeof (in)); in.sin_family = AF_INET; memcpy(&in.sin_addr, src, sizeof (struct in_addr)); getnameinfo((struct sockaddr *) &in, sizeof (struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST); return dst; } else if (af == AF_INET6) { struct sockaddr_in6 in; memset(&in, 0, sizeof (in)); in.sin6_family = AF_INET6; memcpy(&in.sin6_addr, src, sizeof (struct in_addr6)); getnameinfo((struct sockaddr *) &in, sizeof (struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST); return dst; } return NULL; } #endif /* This function takes start time and end time as an input and returns their difference.*/ struct timeval mmt_time_diff(struct timeval tstart, struct timeval tend) { tstart.tv_sec = tend.tv_sec - tstart.tv_sec; tstart.tv_usec = tend.tv_usec - tstart.tv_usec; if ((int) tstart.tv_usec < 0) { tstart.tv_usec += 1000000; tstart.tv_sec -= 1; } return tstart; } /*This function takes IPv6 address and finds whether this address belongs to a local network. *It returns 1 if the address belongs to a IPv6 local network */ int is_localv6_net(char * addr) { if (strncmp(addr, "fec0", 4) == 0)return 1; if (strncmp(addr, "fc00", 4) == 0)return 1; if (strncmp(addr, "fe80", 4) == 0)return 1; return 0; } /*This function takes IPv4 address and finds whether this address belongs to a local network. *It returns 1 if the address belongs to a IPv4 local network */ int is_local_net(int addr) { if ((ntohl(addr) & 0xFF000000 /* 255.0.0.0 */) == 0x0A000000 /* 10.0.0.0 */) { return 1; } if ((ntohl(addr) & 0xFF000000 /* 255.0.0.0 */) == 0xC0000000 /* 192.0.0.0 */) { return 1; } if ((ntohl(addr) & 0xFF000000 /* 255.0.0.0 */) == 0xAC000000 /* 172.16.31.10 */) { return 1; } if ((ntohl(addr) & 0xFF000000 /* 255.0.0.0 */) == 0xA9000000 /* 192.168.127.12 */) { return 1; } return 0; } /* This function writes messages to a log file, including the msg level, time and code */ void mmt_log(mmt_probe_context_t * mmt_conf, int level, int code, const char * log_msg) { if (level >= mmt_conf->log_level) { struct timeval tv; gettimeofday(&tv, NULL); FILE * log_file = (mmt_conf->log_output != NULL) ? mmt_conf->log_output : stdout; fprintf(log_file, "%i\t%lu\t%i\t[%s]\n", level, tv.tv_sec, code, log_msg); fflush(log_file); } } #ifdef HTTP_RECONSTRUCT_MODULE uint8_t is_http_packet(const ipacket_t * ipacket){ uint16_t http_index = get_protocol_index_by_id(ipacket, PROTO_HTTP); // META->ETH->IP->TCP->HTTP if(http_index < 4){ fprintf(stderr, "[error] %lu: PROTO_HTTP has index smaller than 4\n", ipacket->packet_id); return 0; } return 1; } #endif // End of HTTP_RECONSTRUCT_MODULE /* This function puts the protocol path as a string (for example, 99.178.376, * where,99-Ethernet, 178-IP and 376-UDP), in a variable dest and * returns its length as a offset. * */ int proto_hierarchy_ids_to_str(const proto_hierarchy_t * proto_hierarchy, char * dest) { int offset = 0; if (proto_hierarchy->len < 1) { offset += sprintf(dest, "."); } else { int index = 1; offset += sprintf(dest, "%u", proto_hierarchy->proto_path[index]); index++; for (; index < proto_hierarchy->len && index < 16; index++) { offset += sprintf(&dest[offset], ".%u", proto_hierarchy->proto_path[index]); } } return offset; } /* This function returns the index of a particular proto_id, in a proto_path. * If the proto_id does not exit it returns -1 * */ int get_protocol_index_from_session(const proto_hierarchy_t * proto_hierarchy, uint32_t proto_id) { int index = 0; for (; index < proto_hierarchy->len && index < 16; index++) { if (proto_hierarchy->proto_path[index] == proto_id) return index; } return -1; } static mmt_probe_context_t probe_context = {0}; inline mmt_probe_context_t * get_probe_context_config() { return & probe_context; } void create_session (const ipacket_t * ipacket, void * user_args){ mmt_session_t * session = get_session_from_packet(ipacket); if(session == NULL) return; struct smp_thread *th = (struct smp_thread *) user_args; session_struct_t *temp_session = malloc(sizeof (session_struct_t)); if (temp_session == NULL) { mmt_log(&probe_context, MMT_L_WARNING, MMT_P_MEM_ERROR, "Memory error while creating new flow reporting context"); //fprintf(stderr, "Memory allocation failed when creating a new file reporting struct! This flow will be ignored! Sorry!"); return; } memset(temp_session, '\0', sizeof (session_struct_t)); temp_session->session_id = get_session_id(session); temp_session->thread_number = th->thread_index; temp_session->format_id = MMT_STATISTICS_FLOW_REPORT_FORMAT; temp_session->app_format_id = MMT_DEFAULT_APP_REPORT_FORMAT; if (temp_session->isFlowExtracted){ free(temp_session); return; } // Flow extraction int ipindex = get_protocol_index_by_id(ipacket, PROTO_IP); const proto_hierarchy_t * proto_hierarchy = get_session_protocol_hierarchy(ipacket->session); temp_session->application_class = get_application_class_by_protocol_id(proto_hierarchy->proto_path[(proto_hierarchy->len <= 16)?(proto_hierarchy->len - 1):(16 - 1)]); temp_session->proto_path = proto_hierarchy->proto_path[(proto_hierarchy->len <= 16)?(proto_hierarchy->len - 1):(16 - 1)]; unsigned char *src = (unsigned char *) get_attribute_extracted_data(ipacket, PROTO_ETHERNET, ETH_SRC); unsigned char *dst = (unsigned char *) get_attribute_extracted_data(ipacket, PROTO_ETHERNET, ETH_DST); if (src) { memcpy(temp_session->src_mac, src, 6); temp_session->src_mac [6] = '\0'; } if (dst) { memcpy(temp_session->dst_mac, dst, 6); temp_session->dst_mac [6] = '\0'; } if (ipindex != -1) { uint32_t * ip_src = (uint32_t *) get_attribute_extracted_data(ipacket, PROTO_IP, IP_SRC); uint32_t * ip_dst = (uint32_t *) get_attribute_extracted_data(ipacket, PROTO_IP, IP_DST); if (ip_src) { //printf("HAS IP ADDRESS \n"); temp_session->ipclient.ipv4 = (*ip_src); } if (ip_dst) { temp_session->ipserver.ipv4 = (*ip_dst); } uint8_t * proto_id = (uint8_t *) get_attribute_extracted_data(ipacket, PROTO_IP, IP_PROTO_ID); if (proto_id != NULL) { temp_session->proto = *proto_id; } else { temp_session->proto = 0; } temp_session->ipversion = 4; uint16_t * cport = (uint16_t *) get_attribute_extracted_data(ipacket, PROTO_IP, IP_CLIENT_PORT); uint16_t * dport = (uint16_t *) get_attribute_extracted_data(ipacket, PROTO_IP, IP_SERVER_PORT); if (cport) { temp_session->clientport = *cport; } if (dport) { temp_session->serverport = *dport; } } else { void * ipv6_src = (void *) get_attribute_extracted_data(ipacket, PROTO_IPV6, IP6_SRC); void * ipv6_dst = (void *) get_attribute_extracted_data(ipacket, PROTO_IPV6, IP6_DST); if (ipv6_src) { memcpy(&temp_session->ipclient.ipv6, ipv6_src, 16); } if (ipv6_dst) { memcpy(&temp_session->ipserver.ipv6, ipv6_dst, 16); } uint8_t * proto_id = (uint8_t *) get_attribute_extracted_data(ipacket, PROTO_IPV6, IP6_NEXT_PROTO); if (proto_id != NULL) { temp_session->proto = *proto_id; } else { temp_session->proto = 0; } temp_session->ipversion = 6; uint16_t * cport = (uint16_t *) get_attribute_extracted_data(ipacket, PROTO_IPV6, IP6_CLIENT_PORT); uint16_t * dport = (uint16_t *) get_attribute_extracted_data(ipacket, PROTO_IPV6, IP6_SERVER_PORT); if (cport) { temp_session->clientport = *cport; } if (dport) { temp_session->serverport = *dport; } } temp_session->isFlowExtracted = 1; #ifdef HTTP_RECONSTRUCT_MODULE if(probe_context.HTTP_RECONSTRUCT_MODULE_enable == 1){ if(is_http_packet(ipacket) == 1){ // printf("[debug] %lu: flow_nb_handle\n", ipacket->packet_id); // printf("[debug] %lu: new_session_handle - 2\n", ipacket->packet_id); http_content_processor_t * http_content_processor = init_http_content_processor(); if (http_content_processor == NULL) { fprintf(stderr, "[error] %lu: Cannot create http_content_processor\n", ipacket->packet_id); free(temp_session); return; } // printf("[debug] %lu: new_session_handle - 3\n", ipacket->packet_id); temp_session->http_content_processor = http_content_processor; // printf("[debug] %lu: new_session_handle - 4\n", ipacket->packet_id); http_session_data_t * http_session_data = get_http_session_data_by_id(get_session_id(session), th->list_http_session_data); if (http_session_data == NULL) { http_session_data = new_http_session_data(); if (http_session_data) { http_session_data->session_id = get_session_id(session); http_session_data->http_session_status = HSDS_START; add_http_session_data(http_session_data,th); } else { fprintf(stderr, "[error] Cannot create http session data for session %lu - packet: %lu\n", get_session_id(session), ipacket->packet_id); } } } } #endif // End of HTTP_RECONSTRUCT_MODULE // printf ("set session\n"); set_user_session_context(session, temp_session); } /* This function assigns the session ID to a new flow (session), maintains session informations in session_struct_t and * updates mmt_session_t context with new session informations (session_struct_t). * */ void flow_nb_handle(const ipacket_t * ipacket, attribute_t * attribute, void * user_args) { create_session (ipacket, (void *)user_args); } /* This function is called by mmt-dpi for each incoming packet. * It extracts packet information from a #ipacket for creating messages/reports. * */ int packet_handler(const ipacket_t * ipacket, void * args) { mmt_probe_context_t * probe_context = get_probe_context_config(); struct smp_thread *th = (struct smp_thread *) args; if(probe_context->enable_session_report == 1){ session_struct_t *temp_session = (session_struct_t *) get_user_session_context_from_packet(ipacket); if (ipacket->session != NULL && temp_session == NULL){ create_session (ipacket, (void *)args); } if (th->pcap_current_packet_time == 0){ th->pcap_last_stat_report_time = ipacket->p_hdr->ts.tv_sec; } th->pcap_current_packet_time = ipacket->p_hdr->ts.tv_sec; if (temp_session != NULL) { // only for packet based on TCP if (temp_session->dtt_seen == 0){ //this will exclude all the protocols except TCP if(TIMEVAL_2_USEC(get_session_rtt(ipacket->session)) != 0){ struct timeval t1; t1.tv_sec = 0; t1.tv_usec = 0; //The download direction is opposite to set_up_direction, the download direction is from server to client if (get_session_last_packet_direction(ipacket->session) != get_session_setup_direction(ipacket->session)){ t1 = get_session_last_data_packet_time_by_direction(ipacket->session,get_session_last_packet_direction(ipacket->session)); } if (TIMEVAL_2_USEC(mmt_time_diff(get_session_init_time(ipacket->session),ipacket->p_hdr->ts)) > TIMEVAL_2_USEC(get_session_rtt(ipacket->session)) && t1.tv_sec > 0){ temp_session->dtt_seen = 1; temp_session->dtt_start_time = ipacket->p_hdr->ts; } } } } } if (probe_context->enable_security_report == 1){ get_security_report(ipacket,args); } if (probe_context->enable_security_report_multisession == 1){ get_security_multisession_report(ipacket,args); } return 0; } /* This function registers the packet handler for each threads */ void proto_stats_init(void * arg) { struct smp_thread *th = (struct smp_thread *) arg; register_packet_handler(th->mmt_handler, 6, packet_handler, arg); } void proto_stats_cleanup(void * handler) { (void) unregister_packet_handler((mmt_handler_t *) handler, 1); } /* This function unregisters the attributes for a flow (session) * */ void flowstruct_uninit(void * args) { struct smp_thread *th = (struct smp_thread *) args; mmt_probe_context_t * probe_context = get_probe_context_config(); int i = 1; if (is_registered_attribute(th->mmt_handler, PROTO_TCP, TCP_SRC_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_TCP, TCP_SRC_PORT); if (is_registered_attribute(th->mmt_handler, PROTO_TCP, TCP_DEST_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_TCP, TCP_DEST_PORT); if (is_registered_attribute(th->mmt_handler, PROTO_TCP, TCP_RTT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_TCP, TCP_RTT); if (is_registered_attribute(th->mmt_handler, PROTO_TCP, UDP_SRC_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_UDP, UDP_SRC_PORT); if (is_registered_attribute(th->mmt_handler, PROTO_TCP, UDP_DEST_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_UDP, UDP_DEST_PORT); if (is_registered_attribute(th->mmt_handler, PROTO_ETHERNET, ETH_DST) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_ETHERNET, ETH_DST); if (is_registered_attribute(th->mmt_handler, PROTO_TCP, TCP_DEST_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_ETHERNET, ETH_SRC); if (is_registered_attribute(th->mmt_handler, PROTO_IP, IP_SRC) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_SRC); if (is_registered_attribute(th->mmt_handler, PROTO_IP, IP_DST) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_DST); if (is_registered_attribute(th->mmt_handler, PROTO_IP, IP_PROTO_ID) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_PROTO_ID); if (is_registered_attribute(th->mmt_handler, PROTO_IP, IP_SERVER_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_SERVER_PORT); if (is_registered_attribute(th->mmt_handler, PROTO_IP, IP_CLIENT_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_CLIENT_PORT); if (is_registered_attribute(th->mmt_handler, PROTO_IPV6, IP6_NEXT_PROTO) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_NEXT_PROTO); if (is_registered_attribute(th->mmt_handler, PROTO_IPV6, IP6_SRC) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_SRC); if (is_registered_attribute(th->mmt_handler, PROTO_IPV6, IP6_DST) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_DST); if (is_registered_attribute(th->mmt_handler, PROTO_IPV6, IP6_SERVER_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_SERVER_PORT); if (is_registered_attribute(th->mmt_handler, PROTO_IPV6, IP6_CLIENT_PORT) == 1) i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_CLIENT_PORT); /* if (probe_context->enable_IP_fragmentation_report == 1){ i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_FRAG_PACKET_COUNT); i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_FRAG_DATA_VOLUME); i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_DF_PACKET_COUNT); i &= unregister_extraction_attribute(th->mmt_handler, PROTO_IP, IP_DF_DATA_VOLUME); } */ if (is_registered_attribute_handler(th->mmt_handler, PROTO_IP, PROTO_SESSION, flow_nb_handle) == 1) i &= unregister_attribute_handler(th->mmt_handler, PROTO_IP, PROTO_SESSION, flow_nb_handle); if (is_registered_attribute_handler(th->mmt_handler, PROTO_IPV6, PROTO_SESSION, flow_nb_handle) == 1) i &= unregister_attribute_handler(th->mmt_handler, PROTO_IPV6, PROTO_SESSION, flow_nb_handle); if (is_registered_attribute_handler(th->mmt_handler, PROTO_IP, IP_RTT, ip_rtt_handler) == 1) i &= unregister_attribute_handler(th->mmt_handler, PROTO_IP, IP_RTT, ip_rtt_handler); if (is_registered_attribute_handler(th->mmt_handler, PROTO_TCP,TCP_CONN_CLOSED, tcp_closed_handler) == 1) i &= unregister_attribute_handler(th->mmt_handler, PROTO_TCP,TCP_CONN_CLOSED, tcp_closed_handler); if(!i) { //TODO: we need a sound error handling mechanism! Anyway, we should never get here :) fprintf(stderr, "Error while initializing MMT handlers and extractions!\n"); } } /* This function registers the required attributes for a flow (session) * */ void flowstruct_init(void * args) { struct smp_thread *th = (struct smp_thread *) args; mmt_probe_context_t * probe_context = get_probe_context_config(); int i = 1; i &= register_extraction_attribute(th->mmt_handler, PROTO_TCP, TCP_SRC_PORT); i &= register_extraction_attribute(th->mmt_handler, PROTO_TCP, TCP_DEST_PORT); i &= register_extraction_attribute(th->mmt_handler, PROTO_TCP, TCP_RTT); i &= register_extraction_attribute(th->mmt_handler, PROTO_UDP, UDP_SRC_PORT); i &= register_extraction_attribute(th->mmt_handler, PROTO_UDP, UDP_DEST_PORT); i &= register_extraction_attribute(th->mmt_handler, PROTO_ETHERNET, ETH_DST); i &= register_extraction_attribute(th->mmt_handler, PROTO_ETHERNET, ETH_SRC); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_SRC); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_DST); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_PROTO_ID); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_SERVER_PORT); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_CLIENT_PORT); i &= register_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_NEXT_PROTO); i &= register_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_SRC); i &= register_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_DST); i &= register_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_SERVER_PORT); i &= register_extraction_attribute(th->mmt_handler, PROTO_IPV6, IP6_CLIENT_PORT); if (probe_context->enable_IP_fragmentation_report == 1){ i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_FRAG_PACKET_COUNT); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_FRAG_DATA_VOLUME); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_DF_PACKET_COUNT); i &= register_extraction_attribute(th->mmt_handler, PROTO_IP, IP_DF_DATA_VOLUME); } i &= register_attribute_handler(th->mmt_handler, PROTO_IP, PROTO_SESSION, flow_nb_handle, NULL, (void *)args); i &= register_attribute_handler(th->mmt_handler, PROTO_IPV6, PROTO_SESSION, flow_nb_handle, NULL, (void *)args); i &= register_attribute_handler(th->mmt_handler, PROTO_IP, IP_RTT, ip_rtt_handler, NULL, (void *)args); i &=register_attribute_handler(th->mmt_handler, PROTO_TCP,TCP_CONN_CLOSED, tcp_closed_handler, NULL, (void *)args); /*if(probe_context->ftp_enable == 1){ register_ftp_attributes(th->mmt_handler); }*/ if(!i) { //TODO: we need a sound error handling mechanism! Anyway, we should never get here :) fprintf(stderr, "Error while initializing MMT handlers and extractions!\n"); } } void flowstruct_cleanup(void * handler) { } int time_diff(struct timeval t1, struct timeval t2) { return (((t2.tv_sec - t1.tv_sec) * 1000000) + (t2.tv_usec - t1.tv_usec)) / 1000; } /* It provides os_id and device_id from a user_agent if it exists or returns 0 * */ mmt_dev_properties_t get_dev_properties_from_user_agent(char * user_agent, uint32_t len) { mmt_dev_properties_t retval = {0}; if ((len > 8) && (mmt_strncasecmp(user_agent, "Mozilla/", 8) == 0)) { if ((len > 20) && (mmt_strncasecmp(&user_agent[12], "(iPhone;", 8) == 0)) { retval.os_id = OS_IOS; retval.dev_id = DEV_IPHONE; } else if ((len > 18) && (mmt_strncasecmp(&user_agent[12], "(iPod;", 6) == 0)) { retval.os_id = OS_IOS; retval.dev_id = DEV_IPOD; } else if ((len > 18) && (mmt_strncasecmp(&user_agent[12], "(iPad;", 6) == 0)) { retval.os_id = OS_IOS; retval.dev_id = DEV_IPAD; } else if ((len > 30) && (mmt_strncasecmp(&user_agent[12], "(Linux; U; Android", 18) == 0)) { retval.os_id = OS_AND; retval.dev_id = DEV_MOB; } else if ((len > 20) && (mmt_strncasecmp(&user_agent[12], "(Android", 8) == 0)) { retval.os_id = OS_AND; retval.dev_id = DEV_MOB; } else if ((len > 24) && (mmt_strncasecmp(&user_agent[12], "(BlackBerry;", 12) == 0)) { retval.os_id = OS_BLB; retval.dev_id = DEV_BLB; } else if ((len > 17) && (mmt_strncasecmp(&user_agent[12], "(X11;", 5) == 0)) { retval.os_id = OS_NUX; retval.dev_id = DEV_PC; } else if ((len > 23) && (mmt_strncasecmp(&user_agent[12], "(Macintosh;", 11) == 0)) { retval.os_id = OS_MAC; retval.dev_id = DEV_MAC; } else if ((len > 29) && (mmt_strncasecmp(&user_agent[12], "(Windows; U; MSIE", 17) == 0)) { retval.os_id = OS_WIN; retval.dev_id = DEV_PC; } else if ((len > 23) && (mmt_strncasecmp(&user_agent[12], "(Windows NT", 11) == 0)) { retval.os_id = OS_WIN; retval.dev_id = DEV_PC; } else if ((len > 35) && (mmt_strncasecmp(&user_agent[12], "(Windows; U; Windows NT", 23) == 0)) { retval.os_id = OS_WIN; retval.dev_id = DEV_PC; } else if ((len > 36) && (mmt_strncasecmp(&user_agent[12], "(compatible; Windows; U;", 24) == 0)) { retval.os_id = OS_WIN; retval.dev_id = DEV_PC; } else if ((len > 46) && (mmt_strncasecmp(&user_agent[12], "(compatible; MSIE 10.0; Macintosh;", 34) == 0)) { retval.os_id = OS_MAC; retval.dev_id = DEV_MAC; } else if ((len > 48) && (mmt_strncasecmp(&user_agent[12], "(compatible; MSIE 9.0; Windows Phone", 36) == 0)) { retval.os_id = OS_WPN; retval.dev_id = DEV_MOB; } else if ((len > 56) && (mmt_strncasecmp(&user_agent[12], "(compatible; MSIE 10.0; Windows NT 6.2; ARM;", 44) == 0)) { retval.os_id = OS_WPN; retval.dev_id = DEV_MOB; } else if ((len > 29) && (mmt_strncasecmp(&user_agent[12], "(compatible; MSIE", 17) == 0)) { retval.os_id = OS_WIN; retval.dev_id = DEV_PC; } } else if ((len > 6) && (mmt_strncasecmp(user_agent, "Opera/", 6) == 0)) { if ((len > 19) && (mmt_strncasecmp(&user_agent[11], "(Windows", 8) == 0)) { retval.os_id = OS_WIN; retval.dev_id = DEV_PC; } else if ((len > 22) && (mmt_strncasecmp(&user_agent[11], "(Macintosh;", 11) == 0)) { retval.os_id = OS_MAC; retval.dev_id = DEV_MAC; } else if ((len > 16) && (mmt_strncasecmp(&user_agent[11], "(X11;", 5) == 0)) { retval.os_id = OS_NUX; retval.dev_id = DEV_PC; } } return retval; } /* This function is called by mmt-dpi for each session time-out (expiry). * It provides the expired session information and frees the memory allocated. * */ void classification_expiry_session(const mmt_session_t * expired_session, void * args) { // debug("classification_expiry_session : %lu",get_session_id(expired_session)); session_struct_t * temp_session = get_user_session_context(expired_session); struct smp_thread *th = (struct smp_thread *) args; if (temp_session == NULL) { return; } #ifdef HTTP_RECONSTRUCT_MODULE // printf("[debug] cleaning HTTP_RECONSTRUCT_MODULE ... %lu \n",get_session_id(expired_session)); if (temp_session->http_content_processor != NULL) { close_http_content_processor(temp_session->http_content_processor); } clean_http_session_data(get_session_id(expired_session),th); #endif mmt_probe_context_t * probe_context = get_probe_context_config(); if (is_microflow(expired_session)) { microsessions_stats_t * mf_stats = &th->iprobe.mf_stats[get_session_protocol_hierarchy(expired_session)->proto_path[(get_session_protocol_hierarchy(expired_session)->len <= 16)?(get_session_protocol_hierarchy(expired_session)->len - 1):(16 - 1)]]; update_microflows_stats(mf_stats, expired_session); if (is_microflow_stats_reportable(mf_stats)) { report_microflows_stats(mf_stats, args); } }else{ if(temp_session->app_format_id == MMT_WEB_REPORT_FORMAT){ if (temp_session->app_data == NULL) { if (temp_session->session_attr != NULL) { //Free the application specific data if (temp_session->session_attr) free(temp_session->session_attr); temp_session->session_attr = NULL; } if(temp_session) free(temp_session); temp_session = NULL; return; } if (((web_session_attr_t *) temp_session->app_data)->state_http_request_response != 0)((web_session_attr_t *) temp_session->app_data)->state_http_request_response = 0; if (temp_session->session_attr == NULL) { temp_session->session_attr = (session_stat_t *) malloc(sizeof (session_stat_t)); memset(temp_session->session_attr, 0, sizeof (session_stat_t)); } temp_session->report_counter = th->report_counter; print_ip_session_report (expired_session, th); }else{ temp_session->report_counter = th->report_counter; print_ip_session_report (expired_session, th); } } if (temp_session->app_data != NULL) { //Free the application specific data if (temp_session->app_format_id == MMT_FTP_REPORT_FORMAT){ if (((ftp_session_attr_t*) temp_session->app_data)->filename != NULL)free (((ftp_session_attr_t*) temp_session->app_data)->filename); if (((ftp_session_attr_t*) temp_session->app_data)->response_value != NULL)free(((ftp_session_attr_t*) temp_session->app_data)->response_value); if (((ftp_session_attr_t*) temp_session->app_data)->session_username != NULL)free(((ftp_session_attr_t*) temp_session->app_data)->session_username); if (((ftp_session_attr_t*) temp_session->app_data)->session_password != NULL)free(((ftp_session_attr_t*) temp_session->app_data)->session_password); ((ftp_session_attr_t*) temp_session->app_data)->filename = NULL; ((ftp_session_attr_t*) temp_session->app_data)->response_value = NULL; ((ftp_session_attr_t*) temp_session->app_data)->session_username = NULL; ((ftp_session_attr_t*) temp_session->app_data)->session_password = <PASSWORD>; } if(temp_session->app_data) free(temp_session->app_data); temp_session->app_data = NULL; } if (temp_session->session_attr != NULL) { //Free the application specific data if (temp_session->session_attr) free(temp_session->session_attr); temp_session->session_attr = NULL; } if(temp_session) free(temp_session); temp_session = NULL; }
<reponame>TecXra/NodeJSTextProject const repository = require('../repository'); const { REMOVE_TAG_ERROR_MESSAGE } = require('../constants'); async function deleteTagDetails(req, res) { let deleteTag; try { deleteTag = await repository.deleteTag({ ...req.body }); } catch (deleteTagError) { deleteTag = deleteTagError; } if (!deleteTag.name) { req.session.messages = { errors: { databaseError: REMOVE_TAG_ERROR_MESSAGE } }; } return res.redirect(`/tag-management`); } module.exports = deleteTagDetails;
INPUT: paragraph SET counter to zero FOR each word in paragraph: IF word is in dictionary of positive words increment counter ELSE IF word is in dictionary of negative words decrement counter IF counter is greater than zero OUTPUT "positive" ELSE IF counter is less than zero OUTPUT "negative" ELSE OUTPUT "neutral"
import component from './ProjectContributions' export default component
#!/usr/bin/env bash set -e -o pipefail set -x source "$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"/../.ci/deps.sh SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" export CHECKOUT_DIR=$(dirname $SCRIPTPATH)/third-party cd $SCRIPTPATH function checkout_dep() ( cd $CHECKOUT_DIR if [ ! -d $1 ]; then git clone $2 $CHECKOUT_DIR/$1 fi cd $1 git fetch origin git checkout $3 ) function build_composer2nix() ( cd $CHECKOUT_DIR/$1 composer install --dev cp composer.lock $SCRIPTPATH/deps/$1-composer.lock composer2nix --output=$1-packages.nix \ --composer-env=/dev/null \ --composition=/dev/null \ --prefer-dist \ --dev mv $1-packages.nix $SCRIPTPATH/deps/ ) function build_dep() { nix-prefetch-git --url $2 --rev $3 | tee $SCRIPTPATH/deps/$1.json checkout_dep $1 $2 $3 build_composer2nix $1 $2 $3 } build_dep ${MONOLOG_SHORTNAME} ${MONOLOG_REPO} ${MONOLOG_VERSION} build_dep $PSX_CACHE_SHORTNAME $PSX_CACHE_REPO $PSX_CACHE_VERSION build_dep $GUZZLE_PSR7_SHORTNAME $GUZZLE_PSR7_REPO $GUZZLE_PSR7_VERSION build_dep $LEAGUE_CONTAINER_SHORTNAME $LEAGUE_CONTAINER_REPO $LEAGUE_CONTAINER_VERSION build_dep $LINK_UTIL_SHORTNAME $LINK_UTIL_REPO $LINK_UTIL_VERSION build_dep $DISPATCH_SHORTNAME $DISPATCH_REPO $DISPATCH_VERSION build_dep $HTTP_FACTORY_GUZZLE_SHORTNAME $HTTP_FACTORY_GUZZLE_REPO $HTTP_FACTORY_GUZZLE_VERSION build_dep $HTTP_GUZZLE_PSR18_ADAPTER_SHORTNAME $HTTP_GUZZLE_PSR18_ADAPTER_REPO $HTTP_GUZZLE_PSR18_ADAPTER_VERSION build_dep $TUKIO_SHORTNAME $TUKIO_REPO $TUKIO_VERSION build_dep ${LAMINAS_CACHE_SHORTNAME} ${LAMINAS_CACHE_REPO} ${LAMINAS_CACHE_VERSION}
is_empty_list([]). is_empty_list([_|_]):- fail.
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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. */ #include "mem/arena.h" #include "mem/pool_manager.h" #include "mem/mem.h" #include "mem/mem_config.h" #include "mem/mmap_mem_pool-inl.h" #include "gtest/gtest.h" #include "utils/logger.h" namespace panda { class ArenaTest : public testing::Test { public: ArenaTest() { panda::mem::MemConfig::Initialize(0, 16_MB, 0, 0); PoolManager::Initialize(); } ~ArenaTest() { PoolManager::Finalize(); panda::mem::MemConfig::Finalize(); } protected: static constexpr size_t ARENA_SIZE = 1_MB; template <class ArenaT> ArenaT *CreateArena(size_t size) const { return PoolManager::GetMmapMemPool()->AllocArena<ArenaT>(size, SpaceType::SPACE_TYPE_INTERNAL, AllocatorType::ARENA_ALLOCATOR); } template <class ArenaT> void GetOccupiedAndFreeSizeTestImplementation(size_t arena_size, size_t alloc_size) const { ASSERT_TRUE(arena_size != 0); ASSERT_TRUE(alloc_size != 0); ArenaT *arena = CreateArena<ArenaT>(arena_size); size_t old_free_size = arena->GetFreeSize(); ASSERT_TRUE(arena->Alloc(alloc_size) != nullptr); ASSERT_TRUE(arena->GetOccupiedSize() == alloc_size); ASSERT_TRUE(old_free_size - alloc_size == arena->GetFreeSize()); } template <class ArenaT> void ResizeAndResetTestImplementation(size_t arena_size, size_t alloc_size) const { ASSERT_TRUE(arena_size != 0); ASSERT_TRUE(alloc_size != 0); ArenaT *arena = CreateArena<ArenaT>(arena_size); ASSERT_TRUE(alloc_size * 2U <= arena->GetFreeSize()); void *first_allocation = arena->Alloc(alloc_size); void *second_allocation = arena->Alloc(alloc_size); ASSERT_TRUE(first_allocation != nullptr); ASSERT_TRUE(first_allocation != nullptr); ASSERT_TRUE(arena->GetOccupiedSize() == 2U * alloc_size); arena->Resize(alloc_size); ASSERT_TRUE(arena->GetOccupiedSize() == alloc_size); void *third_allocation = arena->Alloc(alloc_size); // we expect that we get the same address ASSERT_TRUE(ToUintPtr(second_allocation) == ToUintPtr(third_allocation)); ASSERT_TRUE(arena->GetOccupiedSize() == 2U * alloc_size); arena->Reset(); ASSERT_TRUE(arena->GetOccupiedSize() == 0); } }; TEST_F(ArenaTest, GetOccupiedAndFreeSizeTest) { static constexpr size_t ALLOC_SIZE = AlignUp(ARENA_SIZE / 2, GetAlignmentInBytes(ARENA_DEFAULT_ALIGNMENT)); static constexpr Alignment ARENA_ALIGNMENT = LOG_ALIGN_4; static constexpr size_t ALIGNED_ALLOC_SIZE = AlignUp(ALLOC_SIZE, GetAlignmentInBytes(ARENA_ALIGNMENT)); GetOccupiedAndFreeSizeTestImplementation<Arena>(ARENA_SIZE, ALLOC_SIZE); GetOccupiedAndFreeSizeTestImplementation<AlignedArena<ARENA_ALIGNMENT>>(ARENA_SIZE, ALIGNED_ALLOC_SIZE); GetOccupiedAndFreeSizeTestImplementation<DoubleLinkedAlignedArena<ARENA_ALIGNMENT>>(ARENA_SIZE, ALIGNED_ALLOC_SIZE); } TEST_F(ArenaTest, ResizeAndResetTest) { static constexpr size_t ALLOC_SIZE = AlignUp(ARENA_SIZE / 3, GetAlignmentInBytes(ARENA_DEFAULT_ALIGNMENT)); static constexpr Alignment ARENA_ALIGNMENT = LOG_ALIGN_4; static constexpr size_t ALIGNED_ALLOC_SIZE = AlignUp(ALLOC_SIZE, GetAlignmentInBytes(ARENA_ALIGNMENT)); ResizeAndResetTestImplementation<Arena>(ARENA_SIZE, ALLOC_SIZE); ResizeAndResetTestImplementation<AlignedArena<ARENA_ALIGNMENT>>(ARENA_SIZE, ALIGNED_ALLOC_SIZE); ResizeAndResetTestImplementation<DoubleLinkedAlignedArena<ARENA_ALIGNMENT>>(ARENA_SIZE, ALIGNED_ALLOC_SIZE); } } // namespace panda
<gh_stars>1-10 package benchmarks.caldat.flmoon.Neq; public class newV { public static int jd = 0; public static double frac = 0.0; public static int mm,id,iyyy; public static void flmoon( int n, int nph) { final double RAD=3.141592653589793238/180.0; int i; double am,as,c,t,t2,xtra; c=n+nph/4.0; t=c/1236.85; t2=t*t; as=359.2242+29.105356*c; am=306.0253+385.816918*c+0.010730*t2; jd=2415020+28*n+7*nph; xtra=0.75933+1.53058868*c+((1.178e-4)-(1.55e-7)*t)*t2; if (nph == 0 )//change xtra += (0.1734-3.93e-4*t)*Math.sin(RAD*as)-0.4068*Math.sin(RAD*am); else if (nph == 1 || nph == 3) xtra += (0.1721-4.0e-4*t)*Math.sin(RAD*as)-0.6280*Math.sin(RAD*am); else xtra = 0.0; i=(int) (xtra >= 0.0 ? Math.floor(xtra) : Math.ceil(xtra-1.0)); jd += i; frac=xtra-i; } }
void copy_array(int arr1[], int arr2[], int size) { for (int i=0; i<size; i++) arr2[i] = arr1[i]; }
<gh_stars>1-10 import { nextWeekRoomOpCreator } from '../../api/services/zoom'; test('if forgot set arg', () => { const roomOp = nextWeekRoomOpCreator(); expect(roomOp['topic']).toBe('by my-first-zoom-app'); expect(roomOp['timezone']).toBe('Asia/Tokyo'); });
package joist.domain.util; import java.util.Date; import com.domainlanguage.time.TimePoint; import com.domainlanguage.time.TimeSource; /** A {@link TimeSource} for the current time. */ public class WallClock implements TimeSource { public TimePoint now() { return TimePoint.from(new Date()); } }
package pedroSantosNeto.fazenda; import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.SQLException; import java.util.Date; import org.junit.Test; public class TesteAnimal { @Test public void testarInsercaoAnimal() throws ClassNotFoundException, SQLException { Date data = new Date(); Animal a = new Bovino(1, "Bravo", data, 0, 5000, 10000, true, false, false); DAOAnimal daoA = new DAOAnimal(); daoA.removerTodos(); daoA.inserir(a); Animal outro = daoA.pesquisarPor(1); assertEquals("Bravo", outro.getNome()); } }
//规范:Function文件中只存放全局函数 function formIsValid(formId: string): boolean { let demo = $('#' + formId) as any; if (!demo.valid()) { return false; } else { return true; } } function formReset(formId: string) { (document.getElementById(formId) as any).reset(); } function convert_keyup(obj) { let n = obj.value.replace(/,/g, "") as string; let str = n.split('.'); if (str.length > 2) return; let z = str[0].split('').reverse().join(''); let z1 = ""; for (let i = 0; i < z.length; i++) { z1 = z1 + z[i]; if ((i + 1) % 3 == 0 && i < z.length - 1) z1 = z1 + ","; } z1 = z1.split('').reverse().join(''); let result = z1; if (str.length == 2) { let f = str[1]; result = result + "." + f; } obj.value = result; } function convert(value: string): string { let n = value.replace(/,/g, "") as string; let str = n.split('.'); if (str.length > 2) return; let z = str[0].split('').reverse().join(''); let z1 = ""; for (let i = 0; i < z.length; i++) { z1 = z1 + z[i]; if ((i + 1) % 3 == 0 && i < z.length - 1) z1 = z1 + ","; } z1 = z1.split('').reverse().join(''); let result = z1; if (str.length == 2) { let f = str[1]; result = result + "." + f; } return result; } function convert_keydown(obj) { setTimeout(() => { convert_keyup(obj) }, 10); } function convertTxType(type: AntShares.Core.TransactionType): string { let typeStr: string; switch (type) { case AntShares.Core.TransactionType.MinerTransaction: typeStr = AntShares.UI.Resources.global.minerTx; break; case AntShares.Core.TransactionType.IssueTransaction: typeStr = AntShares.UI.Resources.global.issueTx; break; case AntShares.Core.TransactionType.ClaimTransaction: typeStr = AntShares.UI.Resources.global.claimTx; break; case AntShares.Core.TransactionType.EnrollmentTransaction: typeStr = AntShares.UI.Resources.global.enrollmentTx; break; case AntShares.Core.TransactionType.RegisterTransaction: typeStr = AntShares.UI.Resources.global.registerTx; break; case AntShares.Core.TransactionType.ContractTransaction: typeStr = AntShares.UI.Resources.global.contractTx; break; case AntShares.Core.TransactionType.AgencyTransaction: typeStr = AntShares.UI.Resources.global.agencyTx; break; case AntShares.Core.TransactionType.PublishTransaction: typeStr = AntShares.UI.Resources.global.publishTx; break; } return typeStr; } let isMobileWeb = { Android: function () { return navigator.userAgent.match(/Android/i); }, iOS: function () { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function () { return navigator.userAgent.match(/Opera Mini/i); }, IE: function () { return navigator.userAgent.match(/IEMobile/i); }, Mozilla: function () { return navigator.userAgent.match(/Mozilla/i); }, Safari: function () { return navigator.userAgent.match(/Safari/i); }, Edge: function () { return navigator.userAgent.match(/Edge/i); }, PC: function (): boolean { if (isMobileWeb.Opera() || isMobileWeb.IE() || isMobileWeb.Mozilla() || isMobileWeb.Safari() || isMobileWeb.Edge()) { return true; } else { return false; } }, Web: function (): boolean { if (isMobileWeb.Android() || isMobileWeb.iOS()) { return true; } else { return false; } } } function setTitle(index: number) { $(".header-title").hide(); $(".header-title").eq(index).show(); } let isMobileApp = { Android: function (): boolean { try { if (device.platform == "Android") { return true; } else { return false; } } catch (ReferenceError){ return false; } }, iOS: function (): boolean { try { if (device.platform == "iOS") { return true; } else { return false; } } catch (ReferenceError) { return false; } }, App: function (): boolean { try { return device.platform != ""; } catch (e) { return false; } } } function is_weixin()//only for Android and IOS { let ua: any = navigator.userAgent.toLowerCase(); return ua.match(/MicroMessenger/i) == "micromessenger"; } function is_weibo()//only for Android and IOS { let ua: any = navigator.userAgent.toLowerCase(); return ua.match(/weibo/i) == "weibo"; } function is_qq()//only for Android and IOS { let ua: any = navigator.userAgent.toLowerCase(); return ua.match(/qq/i) == "qq"; } function cordovaFileError(errorCode: number): string { let errorMessage: string = ""; switch (errorCode) { case 1: errorMessage = "NOT_FOUND_ERR"; break; case 2: errorMessage = "SECURITY_ERR"; break; case 3: errorMessage = "ABORT_ERR"; break; case 4: errorMessage = "NOT_READABLE_ERR"; break; case 5: errorMessage = "ENCODING_ERR"; break; case 6: errorMessage = "NO_MODIFICATION_ALLOWED_ERR"; break; case 7: errorMessage = "INVALID_STATE_ERR"; break; case 8: errorMessage = "SYNTAX_ERR"; break; case 9: errorMessage = "INVALID_MODIFICATION_ERR"; break; case 10: errorMessage = "QUOTA_EXCEEDED_ERR"; break; case 11: errorMessage = "TYPE_MISMATCH_ERR"; break; case 12: errorMessage = "PATH_EXISTS_ERR"; break; default: errorMessage = "UNKOWN_ERR"; break; } return errorMessage; } function wait() { $(".hello").focus(); var hello = $(".hello").clone(); hello.addClass("new-hello"); hello.show(); $("body").append(hello); $("body nav").addClass("blur"); $("#page").addClass("blur"); } function wait_cancel() { $(".new-hello").remove(); $("body nav").removeClass("blur"); $("#page").removeClass("blur"); } let noResume = false; function scan() { noResume = true; (<any>cordova).plugins.barcodeScanner.scan(result => { let address: string = result.text; AntShares.UI.TabBase.showTab("#Tab_Account_Index", address); }, error => { alert("Scanning failed: " + error); }, { showFlipCameraButton: true, // iOS and Android showTorchButton: true, // iOS and Android torchOn: false, // Android, launch with the torch switched on (if available) prompt: "Place a barcode inside the scan area", // Android resultDisplayDuration: 500, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500 formats: "QR_CODE", // default: all but PDF_417 and RSS_EXPANDED }); } function delay(t) { return new Promise(function (resolve) { setTimeout(resolve, t) }); } function debugLog(p: any) { console.log(p); $("#debugLog").prepend(p + "|" + new Date().toLocaleString()+ "</br>"); } function scientificToNumber(num): string { var str = num.toString(); var reg = /^(\d+)(\.\d+)?(E)([\-]?\d+)$/; let arr, len; let part = ''; let zero = ''; let result = ''; /*6e7或6e+7 都会自动转换数值*/ if (!reg.test(str)) { return num; } else { /*6e-7 需要手动转换*/ arr = reg.exec(str); len = Math.abs(arr[4]) - 1; for (var i = 0; i < len; i++) { zero += '0'; } if (arr[2] != undefined) { part = arr[2].replace(/./, ''); } result = arr[1] + part; } return '0.' + zero + result; } function ansToNeo(name): string { let assetName: string; switch (name) { case "小蚁股": assetName = "Neo"; break; case "AntShare": assetName = "Neo"; break; case "小蚁币": assetName = "NeoGas"; break; case "AntCoin": assetName = "NeoGas"; break; default: assetName = name; break; } return assetName; }
import { format } from '@root/lib/util/durationFormat'; import { Argument, ArgumentContext, ArgumentResult } from '@sapphire/framework'; import { Duration } from '@sapphire/time-utilities'; export default class extends Argument<number> { public run(parameter: string, context: ArgumentContext): ArgumentResult<number> { const { offset } = new Duration(parameter); if (typeof context.minimum === 'number' && offset < context.minimum) { return this.error({ parameter, identifier: 'ArgumentDurationMinimumDuration', message: `The duration must be at least ${format(context.minimum)}.` }); } if (typeof context.maximum === 'number' && offset > context.maximum) { return this.error({ identifier: 'ArgumentDurationMaximumDuration', message: `The duration can be at most ${format(context.maximum)}.`, parameter }); } return this.ok(offset); } }
#!/bin/bash # Install The Silver Searcher (ag) hash ag >/dev/null || ( # Ensure dependencies sudo apt-get install -y git-core automake pkg-config libpcre3-dev zlib1g-dev liblzma-dev # Get the source sudo mkdir -p /usr/local/src/silversearcher sudo chmod 777 /usr/local/src/silversearcher git clone --depth 1 \ https://github.com/ggreer/the_silver_searcher.git \ /usr/local/src/silversearcher cd /usr/local/src/silversearcher/ ./build.sh && sudo make install cd / sudo rm -rf /usr/local/src/silversearcher ) # Install Keepass and xclip sudo apt-get install -y keepassx keepass2 xclip # Install icdiff hash icdiff >/dev/null || ( curl -s https://raw.githubusercontent.com/jeffkaufman/icdiff/release-1.7.3/icdiff | \ sudo tee /usr/local/bin/icdiff > /dev/null && sudo chmod ugo+rx /usr/local/bin/icdiff ) # Install docker hash docker >/dev/null || ( # Steps from https://docs.docker.com/engine/installation/linux/ubuntu/ # Make sure we can use aufs sudo apt-get install -y --no-install-recommends \ linux-image-extra-$(uname -r) \ linux-image-extra-virtual # Setup the repository sudo apt-get install -y --no-install-recommends \ apt-transport-https \ ca-certificates \ curl \ software-properties-common FINGERPRINT='5811 8E89 F3A9 1289 7C07 0ADB F762 2157 2C52 609D' # Install the Docker GPG key lookup-key () { apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D; } validate-key () { lookup-key | grep -F "$FINGERPRINT" >/dev/null; } validate-key || { curl -fsSL https://apt.dockerproject.org/gpg | sudo apt-key add - } # Verify Docker's GPG key validate-key || { echo "Unable to validate GPG key" >&2 lookup-key exit 1 } # Install Docker Repo grep -F dockerproject /etc/apt/sources.list || { sudo add-apt-repository \ "deb https://apt.dockerproject.org/repo/ \ ubuntu-$(lsb_release -cs) \ main" } sudo apt-get update sudo apt-get -y install docker-engine sudo groupadd docker || true sudo usermod -aG docker $USER echo "You'll need to logout and back in to use Docker without sudo" )
import subprocess def execute_tasks(commands): for i, command in enumerate(commands, start=1): process = subprocess.Popen(command, shell=True) process.communicate() if process.returncode == 0: print(f"Task {i}: Success") else: print(f"Task {i}: Failed") # Example usage commands = ["ts-node -D -F task1.ts", "ts-node -D -F task2.ts", "ts-node -D -F task3.ts"] execute_tasks(commands)
<gh_stars>1-10 #include "Logger.hpp" using namespace DomoticaInternals; Logger::Logger() : _loggingEnabled(true) , _printer(&Serial) { } void Logger::setLogging(bool enable) { _loggingEnabled = enable; } void Logger::setPrinter(Print* printer) { _printer = printer; } size_t Logger::write(uint8_t character) { if (_loggingEnabled) _printer->write(character); } size_t Logger::write(const uint8_t* buffer, size_t size) { if (_loggingEnabled) _printer->write(buffer, size); }
<reponame>Shasthojoy/cartodb<gh_stars>1-10 var Backbone = require('backbone'); var FactoryModals = require('../../../factories/modals'); var EditorHelpers = require('builder/components/form-components/editors/editor-helpers-extend'); function dispatchDocumentEvent (type, opts) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, false, true); if (opts.which) { e.which = opts.which; } document.dispatchEvent(e, opts); } describe('components/form-components/editors/base', function () { var view; beforeEach(function () { view = new Backbone.Form.editors.Base(); view.options = { validators: ['required'] }; document.body.appendChild(view.el); }); afterEach(function () { var parent = view.el.parentNode; parent && parent.removeChild(view.el); view.remove(); }); it('should take default validation', function () { EditorHelpers.setOptions(view, { schema: { min: 0, max: 10, step: 1, showSlider: true } }); expect(view.options.validators.length).toBe(1); expect(view.options.validators[0]).toBe('required'); }); it('should take opts validation plus the default one', function () { EditorHelpers.setOptions(view, { schema: { validators: [{ type: 'regexp', regexp: /^[0-9]*\.?[0-9]*$/, message: 'Must be valid' }] } }); expect(view.options.validators.length).toBe(2); expect(view.options.validators[0].type).toBe('regexp'); expect(view.options.validators[1]).toBe('required'); }); describe('document click and escape binding', function () { beforeEach(function () { this.modals = FactoryModals.createModalService(); }); it('without modals set', function () { var cb = jasmine.createSpy('cb'); view.applyClickOutsideBind(cb); dispatchDocumentEvent('click', { target: 'body' }); expect(cb).toHaveBeenCalled(); }); it('with some modal open', function () { var clickCB = jasmine.createSpy('clickCB'); var escCB = jasmine.createSpy('escCB'); EditorHelpers.setOptions(view, { modals: this.modals }); view.applyClickOutsideBind(clickCB); view.applyESCBind(escCB); this.modals.set('open', true); dispatchDocumentEvent('click', { target: 'body' }); expect(clickCB).not.toHaveBeenCalled(); dispatchDocumentEvent('keydown', { which: 27 }); expect(escCB).not.toHaveBeenCalled(); }); it('without any modal open', function () { var clickCB = jasmine.createSpy('clickCB'); var escCB = jasmine.createSpy('escCB'); EditorHelpers.setOptions(view, { modals: this.modals }); view.applyClickOutsideBind(clickCB); view.applyESCBind(escCB); this.modals.set('open', false); dispatchDocumentEvent('click', { target: 'body' }); expect(clickCB).toHaveBeenCalled(); dispatchDocumentEvent('keydown', { which: 27 }); expect(escCB).toHaveBeenCalled(); }); }); });
/* * Recursively convert object key value pairs into url encoded string * ------------------------------------------------------------------ * * @param o [object] ( only param that needs to be passed by user ) * @param _key [string] ( for iteration ) * @param _list [array] store key value pairs ( for iteration ) * * @return [string] */ export const urlEncode = ( o, _key, _list = [] ) => { if( typeof( o ) == 'object' ) { for( let idx in o ) urlEncode( o[idx], _key ? _key + '[' + idx + ']' : idx, _list ); } else { _list.push( _key + '=' + encodeURIComponent( o ) ); } return _list.join( '&' ); };
class ConfigurationManager: def __init__(self, config_args): self._config_args = config_args @property def experiment_args(self): return self._config_args["Experiment"] @property def train_dataset_args(self): return self._config_args["Dataset - metatrain"] @property def valid_dataset_args(self): return self._config_args["Dataset - metatest"]
require 'vmstat' module Bot module DiscordCommands module Embeds extend Discordrb::EventContainer extend Discordrb::Commands::CommandContainer info_desc = 'Information about Sapphire' command(:info, description: info_desc, help_available: true) do |event| sys = Vmstat.snapshot res_mem = (sys.task.resident_size.to_f / 1000).to_s free_mem = (sys.memory.free_bytes / 1_073_000_000).to_s + '.' + (sys.memory.free_bytes % 1_073_000_000).to_s cpus = sys.cpus.map do |x| (x.system + x.user).to_f / (x.user + x.system + x.idle).to_f end all_cpus = cpus.map.with_index { |x, y| "**#{y + 1}.** #{x.to_s[0..3]}%" } event.channel.send_embed do |e| e.author = { name: event.bot.profile.name, url: 'http://github.com/cyan101/sapphire', icon_url: event.bot.profile.avatar_url } e.color = '3498db' e.thumbnail = { url: event.bot.profile.avatar_url } # e.title = 'System report' # e.description = 'Sapphire system information report' # e.url = 'http://github.com/cyan101' # e.timestamp = Time.now.utc # e.image = { url: 'https://puu.sh/stDbZ.png' } # e.footer = { text: '- Created by Cyan', icon_url: event.bot.profile.avatar_url } e.add_field name: 'CPU Cores Usage:', value: all_cpus.join("\n"), inline: true e.add_field name: 'Servers/Users:', value: "**Servers:** #{event.bot.servers.count}\n**Users:** #{event.bot.users.count}", inline: true e.add_field name: 'Server\'s inactive Memory: ', value: "`#{free_mem[0..3]}GB`", inline: true e.add_field name: "#{event.bot.profile.name} is using:", value: "`#{res_mem[0..4]}MB`", inline: true e.add_field name: 'Version info:', value: "**Ruby:** `#{RUBY_VERSION}`\n**Discordrb:** `#{Discordrb::VERSION}`\n**Sapphire:** `#{CONFIG.bot_vers}`", inline: true e.add_field name: 'Invite Link', value: "[Click here to Invite #{event.bot.profile.name} to your server!](#{event.bot.invite_url})", inline: true end end end end end
#!/bin/bash # This script parses in the command line parameters from runCust, # maps them to the correct command line parameters for DispNet training script and launches that task # The last line of runCust should be: bash $CONFIG_FILE --data-dir $DATA_DIR --log-dir $LOG_DIR # Parse the command line parameters # that runCust will give out DATA_DIR=NONE LOG_DIR=NONE CONFIG_DIR=NONE MODEL_DIR=NONE # Parsing command line arguments: while [[ $# > 0 ]] do key="$1" case $key in -h|--help) echo "Usage: run_dispnet_training_philly.sh [run_options]" echo "Options:" echo " -d|--data-dir <path> - directory path to input data (default NONE)" echo " -l|--log-dir <path> - directory path to save the log files (default NONE)" echo " -p|--config-file-dir <path> - directory path to config file directory (default NONE)" echo " -m|--model-dir <path> - directory path to output model file (default NONE)" exit 1 ;; -d|--data-dir) DATA_DIR="$2" shift # pass argument ;; -p|--config-file-dir) CONFIG_DIR="$2" shift # pass argument ;; -m|--model-dir) MODEL_DIR="$2" shift # pass argument ;; -l|--log-dir) LOG_DIR="$2" ;; *) echo Unkown option $key ;; esac shift # past argument or value done # Prints out the arguments that were passed into the script echo "DATA_DIR=$DATA_DIR" echo "LOG_DIR=$LOG_DIR" echo "CONFIG_DIR=$CONFIG_DIR" echo "MODEL_DIR=$MODEL_DIR" # Run training on philly # Add the root folder of the code to the PYTHONPATH export PYTHONPATH=$PYTHONPATH:$CONFIG_DIR # Run the actual job python $CONFIG_DIR/examples/AnytimeNetwork/densenet-ann.py \ --data_dir=$DATA_DIR \ --log_dir=$LOG_DIR \ --model_dir=$MODEL_DIR \ --ds_name=cifar100 \ -f=2 \ --opt_at=38 \ -n=52 \ -g=32 \ -s=6 \ --dense_select_method=2 \ --batch_size=32 \ --samloss=0
import styled from "@emotion/styled"; const StatsSubline = styled("h4")` font-size: ${({ theme }) => theme.font.xs}; color: ${({ theme }) => theme.col.black}; font-weight: 400; margin: 0 0 12px; `; export default StatsSubline;
#!/bin/bash # if we are linked, use that info # docker-compose uses depends_on, but while building the following will fail since it # assumes a hard-dependency on 'mongodb' # if [ "$MONGO_STARTED" != "" ]; then # Sample: MONGO_PORT=tcp://172.17.0.20:27017 mongo db/admin < /tmp/db-setup.js # fi
docker build -t quickmess-api:v1 . docker run -p 5123:5123 --name quickmess-backend --net wtl-network --ip 172.19.0.11 quickmess-api:v1
<reponame>kr05/tiny-stepper export { TinyStepper } from './src/TinyStepper.js';
<gh_stars>10-100 export function bound (value, interval) { return Math.max(interval[0], Math.min(interval[1], value)) } export function shuffle (array) { var counter = array.length // While there are elements in the array while (counter > 0) { // Pick a random index var index = Math.floor(Math.random() * counter) // Decrease counter by 1 counter-- // And swap the last element with it var temp = array[counter] array[counter] = array[index] array[index] = temp } return array } export function randomIntFromInterval (min, max) { return Math.floor(Math.random() * (max - min + 1) + min) }
/* * Copyright (c) 2017 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * * 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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 data package tests import data.Predef._ import data.RoseTree._ import data.RoseTreeZipper.Zipper class RoseTreeSpec extends DataSuite { /** simple test, move around example tree. */ test("simple rose tree traversal") { /* 0 -> [1,4,5] 1 -> [2,3] 4 -> [] 5 -> [6,7] */ val exampleTree = Node(0, Stream( Node(1,Stream(Node(2,Stream.empty),Node(3,Stream.empty))), Node(4,Stream.empty), Node(5,Stream(Node(6,Stream.empty),Node(7,Stream.empty))))) val z0 = Zipper(exampleTree,Stream.empty,Stream.empty,Stream.empty) z0.getLabel should be (0) val z1 = z0.firstChild.getOrElse(z0) z1.getLabel should be (1) val z2 = z1.moveRight.getOrElse(z0) z2.getLabel should be(4) val z3 = z2.moveLeft.getOrElse(z0) z3.getLabel should be (1) val root = z3.root root should be (z0) root.toTree should be (exampleTree) } }
import { IlpPrepare, serializeIlpPrepare } from 'ilp-packet' import { deserializeIldcpResponse } from 'ilp-protocol-ildcp' import { createILPContext } from '../../utils' import { ILPContext } from '../../rafiki' import { IncomingAccountFactory, IncomingPeerFactory, OutgoingPeerFactory, IlpPrepareFactory, RafikiServicesFactory } from '../../factories' import { createIldcpMiddleware } from '../../middleware/ildcp' import { ZeroCopyIlpPrepare } from '../../middleware/ilp-packet' describe('ILDCP Middleware', function () { const alice = IncomingPeerFactory.build({ id: 'alice' }) const self = OutgoingPeerFactory.build({ id: 'self' }) const services = RafikiServicesFactory.build({}) const middleware = createIldcpMiddleware('test.rafiki') function makeContext(prepare: IlpPrepare): ILPContext { return createILPContext({ services, accounts: { get incoming() { return alice }, get outgoing() { return self } }, request: { prepare: new ZeroCopyIlpPrepare(prepare), rawPrepare: serializeIlpPrepare(prepare) } }) } beforeAll(async () => { await services.accounting.create(self) await services.accounting.create(alice) }) test('returns an ildcp response on success', async () => { const ctx = makeContext( IlpPrepareFactory.build({ destination: 'peer.config' }) ) const next = jest.fn() await expect(middleware(ctx, next)).resolves.toBeUndefined() const reply = deserializeIldcpResponse( ctx.response.rawReply || Buffer.alloc(0) ) expect(reply.clientAddress).toEqual('test.alice') expect(reply.assetScale).toEqual(alice.asset.scale) expect(reply.assetCode).toEqual(alice.asset.code) expect(next).toHaveBeenCalledTimes(0) }) test('calls "next" if destination is not peer.config', async () => { const ctx = makeContext( IlpPrepareFactory.build({ destination: 'test.foo' }) ) const next = jest.fn() await expect(middleware(ctx, next)).resolves.toBeUndefined() expect(next).toHaveBeenCalledTimes(1) }) test('returns an ildcp response if incoming account is not a peer', async () => { const bob = await services.accounting.create( IncomingAccountFactory.build({ id: 'bob' }) ) const ctx = makeContext( IlpPrepareFactory.build({ destination: 'peer.config' }) ) ctx.accounts = { get incoming() { return bob }, get outgoing() { return self } } const next = jest.fn() await expect(middleware(ctx, next)).rejects.toThrowError( 'not a peer account' ) expect(next).toHaveBeenCalledTimes(0) }) })
import unittest b32 = 0xFFFFFFFF def bitInsertionFor(N, M, i, j): clearmask = 0 for b in range(i, j): clearmask |= 1 << b clearmask = ~clearmask r = N & clearmask return r | (M << i) def bitInsertionBit(N, M, i, j): clearmask = (~1 & b32) << j clearmask |= (1 << i) - 1 R = N & clearmask R |= (M << i) return R class Playground(unittest.TestCase): def setUp(self): self.A = [ dict(N=0b10000000000, M=0b10011, i=2, j=6, E=0b10001001100), dict(N=0b10000000000, M=0b10011, i=1, j=5, E=0b10000100110), dict(N=0b11111111111, M=0b10011, i=1, j=5, E=0b11111100111), dict(N=0b11111111111, M=0b10011, i=1, j=5, E=0b11111100111), ] def runAllTests(self, method): for test in self.A: N = test['N'] M = test['M'] i = test['i'] j = test['j'] E = test['E'] self.assertEqual(bin(method(N, M, i, j)), bin(E)) def test_example_for(self): self.runAllTests(bitInsertionFor) def test_example_bit(self): self.runAllTests(bitInsertionBit) if __name__ == '__main__': unittest.main()
package owlmoney.logic.parser.card; import java.util.Iterator; import owlmoney.logic.command.Command; import owlmoney.logic.command.card.EditCardCommand; import owlmoney.logic.parser.exception.ParserException; /** * Parses input by user for editing card. */ public class ParseEditCard extends ParseCard { /** * Creates an instance of ParseEditCard. * * @param data Raw user input date. * @throws ParserException If the first parameter is invalid. */ public ParseEditCard(String data) throws ParserException { super(data); checkFirstParameter(); } /** * Checks each user input for each parameter. * * @throws ParserException If there are any invalid or missing inputs. */ public void checkParameter() throws ParserException { Iterator<String> cardIterator = cardParameters.keySet().iterator(); int changeCounter = 0; while (cardIterator.hasNext()) { String key = cardIterator.next(); String value = cardParameters.get(key); if (NAME_PARAMETER.equals(key) && (value == null || value.isBlank())) { logger.warning(key + " cannot be empty when editing card"); throw new ParserException(key + " cannot be empty when editing card"); } else if (NAME_PARAMETER.equals(key)) { checkName(value); } if (LIMIT_PARAMETER.equals(key) && !(value == null || value.isBlank())) { checkLimit(value); changeCounter++; } if (REBATE_PARAMETER.equals(key) && !(value == null || value.isBlank())) { checkCashBack(value); changeCounter++; } if (NEW_NAME_PARAMETER.equals(key) && !(value == null || value.isBlank())) { checkName(value); changeCounter++; } } if (changeCounter == 0) { logger.warning("Edit should have at least 1 differing parameter to change."); throw new ParserException("Edit should have at least 1 differing parameter to change."); } } /** * Returns the command to execute the editing of a card. * * @return Returns EditCardCommand to be executed. */ public Command getCommand() { EditCardCommand newEditCardCommand = new EditCardCommand(cardParameters.get(NAME_PARAMETER), cardParameters.get(LIMIT_PARAMETER), cardParameters.get(REBATE_PARAMETER), cardParameters.get( NEW_NAME_PARAMETER)); logger.info("Successful creation of EditCardCommand object"); return newEditCardCommand; } }
<filename>src/vscripts/abilities/heroes/kakashi/kakashi_sharingan.ts import { BaseAbility, BaseModifier, registerAbility, registerModifier } from "../../../lib/dota_ts_adapter" interface kv { ability_id: EntityIndex; } @registerAbility() export class kakashi_sharingan extends BaseAbility { Precache(context: CScriptPrecacheContext): void{ //PrecacheResource("particle", "particles/units/heroes/kakashi/chidori.vpcf", context); PrecacheResource("soundfile", "soundevents/heroes/kakashi/game_sounds_kakashi.vsndevts", context); PrecacheResource("soundfile", "soundevents/heroes/kakashi/game_sounds_vo_kakashi.vsndevts", context); } /****************************************/ Spawn(): void { if (this.GetCaster().IsRealHero()) { ListenToGameEvent("dota_player_used_ability", (event) => this.OnAbilityUsed(event), undefined); } } /****************************************/ CastFilterResultTarget(target: CDOTA_BaseNPC): UnitFilterResult { let caster = this.GetCaster(); let result = UnitFilter( target, UnitTargetTeam.ENEMY, UnitTargetType.HERO, UnitTargetFlags.NOT_CREEP_HERO + UnitTargetFlags.NOT_ILLUSIONS, caster.GetTeamNumber() ) if (result != UnitFilterResult.SUCCESS) return result; const tracker = CustomNetTables.GetTableValue("kakashi_sharingan_tracker", target.GetPlayerOwnerID().toString()); return tracker && UnitFilterResult.SUCCESS || UnitFilterResult.FAIL_CUSTOM; } /****************************************/ GetCustomCastErrorTarget(target: CDOTA_BaseNPC): string { return "#dota_hud_error_cant_steal_spell" } /****************************************/ OnSpellStart(): void { let caster = this.GetCaster(); let target = this.GetCursorTarget() as CDOTA_BaseNPC; let duration = this.GetSpecialValueFor("spell_duration") + caster.FindTalentValue("special_bonus_kakashi_5"); if (target?.TriggerSpellAbsorb(this)) return; const tracker = CustomNetTables.GetTableValue("kakashi_sharingan_tracker", target.GetPlayerOwnerID().toString()); let ability_name = tracker && tracker.last_ability || "invalid" let original_ability = target.FindAbilityByName(ability_name); if (!original_ability) return; let ability_id = this.StealAbility(original_ability, ability_name as string); caster.AddNewModifier(caster, this, "modifier_kakashi_sharingan", {duration: duration, ability_id: ability_id}) EmitSoundOn("Hero_Kakashi.Sharingan.Cast", caster); } /****************************************/ StealAbility(ability: CDOTABaseAbility, ability_name: string): EntityIndex { let caster = this.GetCaster(); if (caster.HasModifier("modifier_kakashi_sharingan")) { caster.RemoveModifierByName("modifier_kakashi_sharingan"); } let stolen_ability = caster.AddAbility(ability_name); stolen_ability.SetHidden(true); stolen_ability.SetLevel(this.GetLevel()); stolen_ability.SetStolen(true); caster.SwapAbilities("kakashi_empty", ability_name, false, true) return stolen_ability.entindex(); } /****************************************/ OnAbilityUsed(event: DotaPlayerUsedAbilityEvent): void { if (!event.caster_entindex || !event.abilityname || !event.PlayerID) return; let caster = EntIndexToHScript(event.caster_entindex) as CDOTA_BaseNPC; let ability = caster.FindAbilityByName(event.abilityname); if (!ability || !ability.IsStealable() || ability.GetAbilityType() == AbilityTypes.ULTIMATE) return; CustomNetTables.SetTableValue("kakashi_sharingan_tracker", tostring(event.PlayerID), {last_ability: event.abilityname}); } } @registerModifier() export class modifier_kakashi_sharingan extends BaseModifier { ability_id?: EntityIndex; /****************************************/ OnCreated(params: kv): void { if (!IsServer()) return; this.ability_id = params.ability_id; } /****************************************/ OnDestroy(): void { if (!IsServer()) return; let parent = this.GetParent(); let ability = EntIndexToHScript(this.ability_id!) as CDOTABaseAbility parent.SwapAbilities(ability.GetAbilityName(), "kakashi_empty", false, true) parent.RemoveAbilityByHandle(ability); } }
package io.github.apace100.origins.mixin.fabric; import io.github.apace100.origins.access.EntityShapeContextAccess; import net.minecraft.block.EntityShapeContext; import net.minecraft.entity.Entity; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(EntityShapeContext.class) public class EntityShapeContextMixin implements EntityShapeContextAccess { private Entity entity; @Inject(at = @At("TAIL"), method = "Lnet/minecraft/block/EntityShapeContext;<init>(Lnet/minecraft/entity/Entity;)V") private void setEntityField(Entity entity, CallbackInfo info) { this.entity = entity; } @Override public Entity getEntity() { return entity; } }
<style> body { background-color: #f2f2f2; } .container { width: 500px; margin: 0 auto; } .login-form { background-color: #fff; padding: 30px; border-radius: 5px; box-shadow: 0 5px 5px #000; } .login-form-input { width: 100%; padding: 15px; border: 1px solid #f2f2f2; margin-bottom: 10px; } .login-form-btn { width: 100%; padding: 15px; border: none; background-color: #44bd32; color: #fff; } </style> <div class="container"> <div class="login-form"> <form> <input class="login-form-input" type="text" placeholder="Username"> <input class="login-form-input" type="password" placeholder="Password"> <input class="login-form-btn" type="submit" value="Submit"> </form> </div> </div>
def alternatingCase(s): result = "" for i in range(len(s)): if i % 2 == 0: result = result + s[i].upper() else: result = result + s[i].lower() return result s = "Hello World" print(alternatingCase(s))
exit 1 # This script isn't currently runnable it just documents the process # Remember to update version number cd .. snapcraft clean && SNAPCRAFT_BUILD_ENVIRONMENT_MEMORY=4G snapcraft # Install and test snap snapcraft login snapcraft upload --release=stable mysnap_latest_amd64.snap
"use strict"; /** * Copyright (c) 2012-2015, <NAME> (MIT License) * Copyright (c) 2016, <NAME> (MIT License). * Copyright (c) 2018, Microsoft Corporation (MIT License). */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Terminal = exports.DEFAULT_ROWS = exports.DEFAULT_COLS = void 0; var events_1 = require("events"); var eventEmitter2_1 = require("./eventEmitter2"); exports.DEFAULT_COLS = 80; exports.DEFAULT_ROWS = 24; /** * Default messages to indicate PAUSE/RESUME for automatic flow control. * To avoid conflicts with rebound XON/XOFF control codes (such as on-my-zsh), * the sequences can be customized in `IPtyForkOptions`. */ var FLOW_CONTROL_PAUSE = '\x13'; // defaults to XOFF var FLOW_CONTROL_RESUME = '\x11'; // defaults to XON var Terminal = /** @class */ (function () { function Terminal(opt) { this._onData = new eventEmitter2_1.EventEmitter2(); this._onExit = new eventEmitter2_1.EventEmitter2(); // for 'close' this._internalee = new events_1.EventEmitter(); if (!opt) { return; } // Do basic type checks here in case node-pty is being used within JavaScript. If the wrong // types go through to the C++ side it can lead to hard to diagnose exceptions. this._checkType('name', opt.name ? opt.name : undefined, 'string'); this._checkType('cols', opt.cols ? opt.cols : undefined, 'number'); this._checkType('rows', opt.rows ? opt.rows : undefined, 'number'); this._checkType('cwd', opt.cwd ? opt.cwd : undefined, 'string'); this._checkType('env', opt.env ? opt.env : undefined, 'object'); this._checkType('uid', opt.uid ? opt.uid : undefined, 'number'); this._checkType('gid', opt.gid ? opt.gid : undefined, 'number'); this._checkType('encoding', opt.encoding ? opt.encoding : undefined, 'string'); // setup flow control handling this.handleFlowControl = !!(opt.handleFlowControl); this._flowControlPause = opt.flowControlPause || FLOW_CONTROL_PAUSE; this._flowControlResume = opt.flowControlResume || FLOW_CONTROL_RESUME; } Object.defineProperty(Terminal.prototype, "onData", { get: function () { return this._onData.event; }, enumerable: false, configurable: true }); Object.defineProperty(Terminal.prototype, "onExit", { get: function () { return this._onExit.event; }, enumerable: false, configurable: true }); Object.defineProperty(Terminal.prototype, "pid", { get: function () { return this._pid; }, enumerable: false, configurable: true }); Object.defineProperty(Terminal.prototype, "cols", { get: function () { return this._cols; }, enumerable: false, configurable: true }); Object.defineProperty(Terminal.prototype, "rows", { get: function () { return this._rows; }, enumerable: false, configurable: true }); Terminal.prototype.write = function (data) { if (this.handleFlowControl) { // PAUSE/RESUME messages are not forwarded to the pty if (data === this._flowControlPause) { this.pause(); return; } if (data === this._flowControlResume) { this.resume(); return; } } // everything else goes to the real pty this._write(data); }; Terminal.prototype._forwardEvents = function () { var _this = this; this.on('data', function (e) { return _this._onData.fire(e); }); this.on('exit', function (exitCode, signal) { return _this._onExit.fire({ exitCode: exitCode, signal: signal }); }); }; Terminal.prototype._checkType = function (name, value, type, allowArray) { if (allowArray === void 0) { allowArray = false; } if (value === undefined) { return; } if (allowArray) { if (Array.isArray(value)) { value.forEach(function (v, i) { if (typeof v !== type) { throw new Error(name + "[" + i + "] must be a " + type + " (not a " + typeof v[i] + ")"); } }); return; } } if (typeof value !== type) { throw new Error(name + " must be a " + type + " (not a " + typeof value + ")"); } }; /** See net.Socket.end */ Terminal.prototype.end = function (data) { this._socket.end(data); }; /** See stream.Readable.pipe */ Terminal.prototype.pipe = function (dest, options) { return this._socket.pipe(dest, options); }; /** See net.Socket.pause */ Terminal.prototype.pause = function () { return this._socket.pause(); }; /** See net.Socket.resume */ Terminal.prototype.resume = function () { return this._socket.resume(); }; /** See net.Socket.setEncoding */ Terminal.prototype.setEncoding = function (encoding) { if (this._socket._decoder) { delete this._socket._decoder; } if (encoding) { this._socket.setEncoding(encoding); } }; Terminal.prototype.addListener = function (eventName, listener) { this.on(eventName, listener); }; Terminal.prototype.on = function (eventName, listener) { if (eventName === 'close') { this._internalee.on('close', listener); return; } this._socket.on(eventName, listener); }; Terminal.prototype.emit = function (eventName) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } if (eventName === 'close') { return this._internalee.emit.apply(this._internalee, arguments); } return this._socket.emit.apply(this._socket, arguments); }; Terminal.prototype.listeners = function (eventName) { return this._socket.listeners(eventName); }; Terminal.prototype.removeListener = function (eventName, listener) { this._socket.removeListener(eventName, listener); }; Terminal.prototype.removeAllListeners = function (eventName) { this._socket.removeAllListeners(eventName); }; Terminal.prototype.once = function (eventName, listener) { this._socket.once(eventName, listener); }; Terminal.prototype._close = function () { this._socket.readable = false; this.write = function () { }; this.end = function () { }; this._writable = false; this._readable = false; }; Terminal.prototype._parseEnv = function (env) { var keys = Object.keys(env || {}); var pairs = []; for (var i = 0; i < keys.length; i++) { if (keys[i] === undefined) { continue; } pairs.push(keys[i] + '=' + env[keys[i]]); } return pairs; }; return Terminal; }()); exports.Terminal = Terminal; //# sourceMappingURL=terminal.js.map
<reponame>Mamuya7/datrastoco-springboot-api package com.mamuya.datrastocospringbootapi.service.serviceImpl; import com.mamuya.datrastocospringbootapi.entities.Product; import com.mamuya.datrastocospringbootapi.repository.ProductRepository; import com.mamuya.datrastocospringbootapi.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class ProductServiceImpl implements ProductService { private ProductRepository productRepository; @Autowired public ProductServiceImpl(ProductRepository productRepository) { this.productRepository = productRepository; } @Override public Product save(Product product) { return productRepository.save(product); } @Override public Product findById(int id) { Optional<Product> product = productRepository.findById(id); return product.orElse(null); } @Override public boolean existsById(int id) { return productRepository.existsById(id); } @Override public List<Product> findAll() { return productRepository.findAll(); } @Override public long count() { return productRepository.count(); } @Override public void deleteById(int id) { productRepository.deleteById(id); } }
#!/bin/bash # ======================================================== # # | *** Parse Arguments *** | # # ======================================================== # while getopts ":h-:" OPTION do case "${OPTION}" in h) usage exit 2 ;; -) case "${OPTARG}" in # Input p_in_binding_train) p_in_binding_train="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; in_model_name) in_model_name="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; l_in_path_net_train) l_in_path_net_train="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; l_in_path_net_test) l_in_path_net_test="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; l_in_name_net) l_in_name_net="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; # Output p_out_pred_train) p_out_pred_train="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_out_pred_test) p_out_pred_test="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_out_model_summary) p_out_model_summary="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_out_model) p_out_model="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_out_optimal_lambda) p_out_optimal_lambda="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_out_dir) p_out_dir="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; # Singularity flag_singularity) flag_singularity="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_singularity_img) p_singularity_img="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_singularity_bindpath) p_singularity_bindpath="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; # SLURM flag_slurm) flag_slurm="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; slurm_nbr_tasks) slurm_nbr_tasks="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; # logistics p_src_code) p_src_code="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; flag_debug) flag_debug="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_progress) p_progress="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; nbr_job) nbr_job="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; # logistic regression flag_intercept) flag_intercept="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; # regularization flag_penalize) flag_penalize="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; p_dir_penalize) p_dir_penalize="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; penalize_nbr_fold) penalize_nbr_fold="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 )) ;; esac;; esac done # ======================================================== # # | *** Define Command *** | # # ======================================================== # # check if that's singularity/slurm run cmd="" if [ ${flag_singularity} == "ON" ]; then if [ ${flag_slurm} == "ON" ]; then source ${p_src_code}src/helper/load_singularity.sh; fi export SINGULARITY_BINDPATH=${p_singularity_bindpath} cmd+="singularity exec ${p_singularity_img} " elif [ ${flag_singularity} == "OFF" ]; then if [ ${flag_slurm} == "ON" ]; then source ${p_src_code}src/helper/load_modules.sh fi fi # continue defining command cmd+="Rscript ${p_src_code}src/combine_networks/code/train_test.R \ --p_in_binding_train ${p_in_binding_train} \ --l_in_name_net ${l_in_name_net} \ --l_in_path_net_train ${l_in_path_net_train} \ --l_in_path_net_test ${l_in_path_net_test} \ --in_model_name ${in_model_name} \ --p_out_pred_train ${p_out_pred_train} \ --p_out_pred_test ${p_out_pred_test} \ --p_out_model_summary ${p_out_model_summary} \ --p_out_model ${p_out_model} \ --p_out_optimal_lambda ${p_out_optimal_lambda} \ --p_src_code ${p_src_code} \ --nbr_job ${nbr_job} \ --nbr_cores ${slurm_nbr_tasks} \ --flag_intercept ${flag_intercept} \ --flag_penalize ${flag_penalize} \ --p_dir_penalize ${p_dir_penalize} \ --penalize_nbr_fold ${penalize_nbr_fold}" # ======================================================== # # | *** Run Command *** | # # ======================================================== # # run command if [ ${flag_debug} == "ON" ]; then printf "***R CMD***\n${cmd}\n" >> ${p_progress}; fi eval ${cmd}
def array_sum(arr): sum = 0 for i in range(0, len(arr)): sum += arr[i] return sum arr = [1,2,3,4,5] print(array_sum(arr))
var hashidEncoder = require('../lib/hashEncoderDecoder'); function getOrderedPlaces(destinationsForPlaces,taste,connection,placesDataCallback){ var CityIDsForPlaces=[]; var cityWisePlaces=[]; var tastesSubQuery='(Taste & '+connection.escape(taste.tasteInteger)+'!=0 )' var familyFriendsSubQuery = '(Taste & '+connection.escape(taste.familyFriendsInteger)+'!=0 )'; for(var i=0;i<destinationsForPlaces.destinations.length;i++) { CityIDsForPlaces.push(destinationsForPlaces.destinations[i].cityID); cityWisePlaces[i]=[]; } //CityIDsForPlacesDecrypted = hashidEncoder.CityIDsForPlaces var decodedCityIDsForPlaces=hashidEncoder.decodeCityID(CityIDsForPlaces); var queryString = "SELECT a.PlaceID, Taste, Name, Address, CityID, Description, Score, IF(("+tastesSubQuery+"),1,0) AS TasteOrderAttribute, IF(("+familyFriendsSubQuery+"),1,0) AS FamilyFriendsOrderAttribute, Latitude, Longitude, Time2Cover, UnescoHeritage, TimeStart, TimeEnd, Days, ChildCharge, AdultCharge, ForeignerCharge, NumberOfImages FROM " +"(SELECT * FROM Places WHERE CityID IN ("+connection.escape(decodedCityIDsForPlaces)+")) a LEFT OUTER JOIN " +"(SELECT * FROM Place_Charges WHERE PlaceID IN (SELECT PlaceId FROM Places WHERE CityID IN ("+connection.escape(decodedCityIDsForPlaces)+"))) b" +" ON (a.PlaceID = b.PlaceID) LEFT OUTER JOIN " +"(SELECT * FROM PlaceTimings WHERE PlaceID IN (SELECT PlaceId FROM Places WHERE CityID IN ("+connection.escape(decodedCityIDsForPlaces)+"))) c " +" ON (a.PlaceID = c.PlaceID)" +" ORDER BY TasteOrderAttribute DESC, FamilyFriendsOrderAttribute DESC, Score DESC, a.PlaceID DESC LIMIT 100;"; /*SELECT * FROM (SELECT * FROM `Places` WHERE `CityID`=6) a LEFT OUTER JOIN (SELECT * FROM Place_Charges WHERE PlaceID IN (SELECT PlaceId FROM `Places` WHERE `CityID`=6)) b ON (a.PlaceID = b.PlaceID) LEFT OUTER JOIN (SELECT * FROM PlaceTimings WHERE PlaceID IN (SELECT PlaceId FROM `Places` WHERE `CityID`=6)) c ON (a.PlaceID = c.PlaceID) LEFT OUTER JOIN (SELECT * FROM Place_Image WHERE PlaceID IN (SELECT PlaceId FROM `Places` WHERE `CityID`=6)) d ON (a.PlaceID = d.PlaceID)*/ console.time("dbsave"); console.log(":PLaces query"+queryString); connection.query(queryString, function(err, rows, fields) { console.timeEnd("dbsave"); if (err) { throw err; } else{ for (var i in rows) { rows[i].PlaceID= hashidEncoder.encodePlaceID(parseInt(rows[i].PlaceID)); rows[i].placeAdded = false; rows[i].PlaceTimings = []; rows[i].PlaceTimings.push({ TimeStart : rows[i].TimeStart, TimeEnd : rows[i].TimeEnd, Days : rows[i].Days }); delete rows[i].TimeStart; delete rows[i].TimeEnd; delete rows[i].Days; //console.log(rows[i]); var indexOfCity = decodedCityIDsForPlaces.indexOf(rows[i].CityID); if(cityWisePlaces[indexOfCity].length > 0 && cityWisePlaces[indexOfCity][cityWisePlaces[indexOfCity].length-1].PlaceID == rows[i].PlaceID) { cityWisePlaces[indexOfCity][cityWisePlaces[indexOfCity].length-1].PlaceTimings.push(rows[i].PlaceTimings[0]); } else { cityWisePlaces[indexOfCity].push(rows[i]); cityWisePlaces[indexOfCity][cityWisePlaces[indexOfCity].length - 1].placeIndex = cityWisePlaces[indexOfCity].length - 1; } } } placesDataCallback(null, cityWisePlaces); }); //connection.end(); } module.exports.getOrderedPlaces=getOrderedPlaces;
//package study.business.application.jobs.person; // //import javax.batch.api.partition.PartitionAnalyzer; //import javax.batch.runtime.BatchStatus; //import javax.enterprise.context.Dependent; //import javax.inject.Named; //import java.io.Serializable; // //@Dependent //@Named("PartitionAnalyzerImpl") //public class PartitionAnalyzerImpl implements PartitionAnalyzer { // @Override // public void analyzeCollectorData(Serializable data) throws Exception { // // } // // @Override // public void analyzeStatus(BatchStatus batchStatus, String exitStatus) throws Exception { // // } //}
<reponame>danielsan/resilient.js var Resilient = require('../') var client = Resilient({ balancer: { random: true, roundRobin: false }, discovery: { servers: [ 'http://localhost:8882/discovery/balancer' ], timeout: 1000, parallel: false } }) client.on('request:outgoing', function (opts) { console.log('Calling out to:', opts.url) }) for (let i = 1; i < 10; i += 1) { client.get('/hello').then(function (res) { console.log('Response:', res.status, res.request.method) console.log('Body:', res.data) }).catch(function (err) { console.error('Error:', err) }) }
package com.zhcs.dao; import java.util.List; import java.util.Map; import com.zhcs.entity.MailtemplateEntity; //***************************************************************************** /** * <p>Title:MailtemplateDao</p> * <p>Description: 邮件模板</p> * <p>Copyright: Copyright (c) 2017</p> * <p>Company: 深圳市智慧城市管家信息科技有限公司 </p> * @author 刘晓东 - Alter * @version v1.0 2017年2月23日 */ //***************************************************************************** public interface MailtemplateDao extends BaseDao<MailtemplateEntity> { List<Map<String, Object>> getSendTemplate(); }
#!/bin/bash set -e echo "Global config ..." #envsubst < /templates/global/koha-sites.conf.tmpl > /etc/koha/koha-sites.conf envsubst < /templates/global/passwd.tmpl > /etc/koha/passwd echo "Setting up local cronjobs ..." #envsubst < /cronjobs/deichman-koha-common.tmpl > /etc/cron.d/deichman-koha-common envsubst < /cronjobs/koha-common.tmpl > /etc/cron.d/koha-common #chmod 644 /etc/cron.d/deichman-koha-common echo "Setting up supervisord ..." envsubst < /templates/global/supervisord.conf.tmpl > /etc/supervisor/conf.d/supervisord.conf echo "Mysql server setup ..." if [ "$MYSQL_HOST" != "localhost" ]; then printf "Using linked mysql container $MYSQL_HOST\n" if ! ping -c 1 -W 1 $MYSQL_HOST; then echo "ERROR: Could not connect to remote mysql $MYSQL_HOST" exit 1 fi else printf "No linked mysql or unable to connect to linked mysql $MYSQL_HOST\n-- initializing local mysql ...\n" # overlayfs fix for mysql find /var/lib/mysql -type f -exec touch {} \; /etc/init.d/mysql start sleep 1 # waiting for mysql to spin up on slow computers echo "127.0.0.1 $MYSQL_HOST" >> /etc/hosts echo "CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD' ; \ CREATE USER '$MYSQL_USER'@'$MYSQL_HOST' IDENTIFIED BY '$MYSQL_PASSWORD' ; \ CREATE DATABASE IF NOT EXISTS koha_$KOHA_INSTANCE ; \ GRANT ALL ON koha_$KOHA_INSTANCE.* TO '$MYSQL_USER'@'%' WITH GRANT OPTION ; \ GRANT ALL ON koha_$KOHA_INSTANCE.* TO '$MYSQL_USER'@'$MYSQL_HOST' WITH GRANT OPTION ; \ FLUSH PRIVILEGES ;" | mysql -u root -p$MYSQL_PASSWORD fi echo "Initializing local instance ..." envsubst < /templates/instance/koha-common.cnf.tmpl > /etc/mysql/koha-common.cnf koha-create --request-db $KOHA_INSTANCE || true koha-create --populate-db $KOHA_INSTANCE echo "Configuring local instance ..." envsubst < /templates/instance/koha-conf.xml.tmpl > /etc/koha/sites/$KOHA_INSTANCE/koha-conf.xml envsubst < /templates/instance/log4perl.conf.tmpl > /etc/koha/sites/$KOHA_INSTANCE/log4perl.conf envsubst < /templates/instance/zebra.passwd.tmpl > /etc/koha/sites/$KOHA_INSTANCE/zebra.passwd envsubst < /templates/instance/apache.tmpl > /etc/apache2/sites-available/$KOHA_INSTANCE.conf echo "Configuring SIPconfig.xml from templates and data from csv ..." door=`awk -f /templates/instance/SIPconfig.template_account_dooraccess.awk /templates/instance/SIPconfig.dooraccess.csv` ; \ logins=`awk -f /templates/instance/SIPconfig.template_account.awk /templates/instance/SIPconfig.logins.csv` ; \ inst=`awk -f /templates/instance/SIPconfig.template_institution.awk /templates/instance/SIPconfig.institutions.csv` ; \ awk -v door="$door" -v logins="$logins" -v inst="$inst" \ '{gsub(/__TEMPLATE_DOOR_ACCOUNTS__/, door); gsub(/__TEMPLATE_LOGIN_ACCOUNTS__/, logins); gsub(/__TEMPLATE_INSTITUTIONS__/, inst) };1' \ /templates/instance/SIPconfig.xml.tmpl | envsubst > /etc/koha/sites/$KOHA_INSTANCE/SIPconfig.xml echo "Configuring languages ..." # Install languages in Koha for language in $KOHA_LANGS do koha-translate --install $language done ln -sf /usr/share/koha/api /api chmod 777 /var/log/koha/awen/opac-error.log chmod 777 /var/log/koha/awen/intranet-error.log echo "Restarting apache to activate local changes..." service apache2 restart sleep 1 # waiting for apache restart to finish #echo "Running db installer and applying local deichman mods - please be patient ..." #cd /usr/share/koha/lib && /installer/installer.sh #echo "Fixing bug in translated member search template in Norwegian..." #sed -i 's/l\xc3\xa5nenummer/borrowernumber/' /usr/share/koha/intranet/htdocs/intranet-tmpl/prog/nb-NO/modules/members/tables/members_results.tt || true echo "Enabling plack ..." koha-plack --enable "$KOHA_INSTANCE" echo "Installation finished - Stopping all services and giving supervisord control ..." service apache2 stop koha-indexer --stop "$KOHA_INSTANCE" koha-stop-zebra "$KOHA_INSTANCE" supervisord -c /etc/supervisor/conf.d/supervisord.conf
/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2012 <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ============================================================ */ #ifndef UPDATER_H #define UPDATER_H #include <QObject> #include "qz_namespace.h" class QNetworkReply; class QUrl; class QupZilla; class QT_QUPZILLA_EXPORT Updater : public QObject { Q_OBJECT public: explicit Updater(QupZilla* mainClass, QObject* parent = 0); ~Updater(); struct Version { bool isValid; int majorVersion; int minorVersion; int revisionNumber; QString specialSymbol; bool operator<(const Version &other) const { if (!this->isValid || !other.isValid) return false; if (this->majorVersion < other.majorVersion) return true; if (this->minorVersion < other.minorVersion) return true; if (this->revisionNumber < other.revisionNumber) return true; if (this->revisionNumber == other.revisionNumber) return !isBiggerThan_SpecialSymbol(this->specialSymbol, other.specialSymbol); return false; } bool operator>(const Version &other) const { return !operator<(other); } bool operator==(const Version &other) const { if (!this->isValid || !other.isValid) return false; return (this->majorVersion == other.majorVersion && this->minorVersion == other.minorVersion && this->revisionNumber == other.revisionNumber && this->specialSymbol == other.specialSymbol); } bool operator>=(const Version &other) const { if (*this == other) return true; return *this > other; } bool operator<=(const Version &other) const { if (*this == other) return true; return *this < other; } }; static Version parseVersionFromString(const QString &string); static bool isBiggerThan_SpecialSymbol(QString one, QString two); signals: private slots: void downCompleted(QNetworkReply* reply); void start(); void downloadNewVersion(); private: void startDownloadingUpdateInfo(const QUrl &url); QupZilla* p_QupZilla; }; #endif // UPDATER_H