text
stringlengths
1
1.05M
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Grocery } from './grocery'; import { CART } from './cart'; @Injectable() export class GroceryService { private cartUrl = 'api/cart'; private groceriesUrl = 'api/groceries'; constructor(private http: Http) { } getGroceries(): Promise<Grocery[]> { return this.http.get(this.groceriesUrl) .toPromise() .then(response => response.json().data as Grocery[]) .catch(this.handleError); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // for demo purposes only return Promise.reject(error.message || error); } getGrocery(id: number): Promise<Grocery> { const url = `${this.groceriesUrl}/${id}`; return this.http.get(url) .toPromise() .then(response => response.json().data as Grocery) .catch(this.handleError); } getCart(): Promise<Grocery[]> { return Promise.resolve(CART); } private headers = new Headers({'Content-Type': 'application/json'}); update(grocery: Grocery): Promise<Grocery> { const url = `${this.groceriesUrl}/${grocery.id}`; return this.http .put(url, JSON.stringify(grocery), {headers: this.headers}) .toPromise() .then(() => grocery) .catch(this.handleError); } create(name: string, price: number): Promise<Grocery> { return this.http .post(this.groceriesUrl, JSON.stringify({name: name, price: price}), {headers: this.headers}) .toPromise() .then(res => res.json().data as Grocery) .catch(this.handleError); } delete(id: number): Promise<void> { const url = `${this.groceriesUrl}/${id}`; return this.http.delete(url, {headers: this.headers}) .toPromise() .then(() => null) .catch(this.handleError); } deleteFromCart(grocery: Grocery): Promise<Grocery>{ CART.splice(CART.indexOf(grocery),1); return Promise.resolve(grocery); } addToCart(grocery: Grocery): Promise<Grocery> { CART.push(grocery); return Promise.resolve(grocery); } }
import java.util.Random; public class RandomNumberGenerator { public static void main(String[] args) { Random random = new Random(); // Generate 10 random numbers for (int i = 0; i < 10; i++) { int num = random.nextInt(100); System.out.println("Random number: " + num); } } }
<reponame>takuma-y/AutoReversi document.addEventListener("DOMContentLoaded", function(e) { let playerBlack = new Player(DISK_BLACK); let playerWhite = new Player(DISK_WHITE); const interval = 0; const black = function() { if(playerBlack.place()) { setTimeout(white, interval); }else{ setTimeout(black, interval); } } const white = function() { if(playerWhite.place()) { setTimeout(black, interval); }else{ setTimeout(white, interval); } } black(); });
root(){ cd $(git rev-parse --show-toplevel 2> /dev/null) }
from dataclasses import dataclass from typing import List from pnmap.resolve import * import subprocess, re @dataclass class CIDR: netid: str suffix: int def __str__(self): return f"{self.netid}/{self.suffix}" class Subnet: def __init__(self, netid, mask): self.netid = netid self.mask = mask self.cidr = self._calc_cidr() self.gateway = self._calc_gateway() @staticmethod def from_host(ip, mask): ip_oct = ip.split(".") mask_oct = mask.split(".") net_oct: List[str] = [] for i in range(4): net_oct.append(str(int(mask_oct[i]) & int(ip_oct[i]))) netid = ".".join(net_oct) return Subnet(netid, mask) def _calc_cidr(self) -> CIDR: total_len = 0 for oct in self.mask.split("."): total_len += bin(int(oct)).count("1") return CIDR(self.netid, total_len) def _calc_gateway(self) -> str: route = subprocess.check_output(["route", "-n"]).decode("utf-8") match = re.search(rf"0\.0\.0\.0\s*({IPV4r})", route) if match: return match.group(1) else: return "0.0.0.0" def contains(self, ip: str) -> bool: """ determines in a given IP falls with a subnet """ match = is_ipv4_address(ip) if not match: return False return self == Subnet.from_host(ip, self.mask) def __eq__(self, other): return str(self) == str(other) def __str__(self): return str(self.cidr) def determine_subnet(interface: str) -> Subnet: """ detemines the subnet of a given interface """ ifconfig_rez = subprocess.check_output(["sudo", "ifconfig", interface]).decode("utf-8") inet, mask = ("0.0.0.0", "255.255.255.255") match = re.search(rf"inet ({IPV4r})", ifconfig_rez) if match: inet = match.group(1) match = re.search(rf"netmask ({IPV4r})", ifconfig_rez) if match: mask = match.group(1) return Subnet.from_host(inet, mask)
///<reference path="..\collections\cache.ts" /> ///<reference path='..\..\lib\Underscore.js\underscore.js' /> module Treaty { // Rudimentary type syntax until TypeScript supports generics // TODO: Does not currently support type namespace export class Type { public static stringType: Type = new Type('String'); public static numberType: Type = new Type('Number'); public static booleanType: Type = new Type('Boolean'); public static arrayType: Type = new Type('Array'); public static objectType: Type = new Type('Object'); public static functionType: Type = new Type('Function'); public static undefinedType: Type = new Type('Undefined'); public static nullType: Type = new Type('Null'); private static registry: TypeRegistry; // Get the type for the given object public static of(obj: any): Type { var typeName = toType(obj); return create(typeName); } // Create an instance for the given type or return the same Type instance if already requested public static create(typeName: string): Type { this.registry = this.registry || new TypeRegistry(); return this.registry.lookup(typeName); } // Pseudo generic types // 'Token', 'ExampleClass', 'string' => 'Token<ExampleClass, string>' public static generic(typeName: string, type1: Type, type2?: Type, type3?: Type, type4?: Type, type5?: Type): Type { var args = _.filter([type1, type2, type3, type4, type5], (type: Type) => type !== undefined); return new Type(typeName + '<' + _.select(args, (type: Type) => type.name).join(', ') + '>', args); } private static toType(obj: any): string { if (obj === undefined) return 'Undefined'; if (obj === null) return 'Null'; return obj.constructor.name; } private isGeneric: bool; // Do not call constructor, use static create factory method constructor(public name: string, private genericArgs: Treaty.Type[] = []) { this.isGeneric = this.genericArgs.length > 0; } public isGenericType(): bool { return this.isGeneric; } public getGenericArguments(): Type[] { if (this.isGeneric) { return this.genericArgs; } throw 'Not a generic type'; } // Tuple<A, B> => 'Tuple<,>' public getGenericTypeDefinition(): string { if (this.isGeneric) { var type = this.name.substr(0, this.name.indexOf('<')); var args: string[] = []; _.each(this.genericArgs, (type: Type) => args.push('')) return type + '<' + args.join(',') + '>'; } throw 'Not a generic type'; } public equals(other: Type): bool { return this.name == other.name; } public not(other: Type): bool { return this.name != other.name; } public toString(): string { return this.name; } } export class TypeRegistry { private knownTypes: Treaty.Collections.Cache = new Treaty.Collections.Cache(); constructor() { this.register(Type.stringType); this.register(Type.numberType); this.register(Type.booleanType); this.register(Type.arrayType); this.register(Type.objectType); this.register(Type.functionType); this.register(Type.undefinedType); this.register(Type.nullType); } public lookup(typeName: string): Type { return this.knownTypes.getItem(typeName, name => new Type(name)); } private register(type: Type): void { this.knownTypes.insert(type.name, type); } } }
#!/usr/bin/env bash # THIS FILE IS GENERATED AUTOMATICALLY VENV=alignclf-venv/bin/activate . ${VENV} which python cd prom-nightly PYTHON=python RUN=../src/run.py CONFIG=../configs/BPI2018-net4-ILP/astar-generic_50-score-strict/configs.json LOGGINGCONFIGS=../src/logging.json TIME_FILE="../times.txt" N=1 for i in $(seq 1 $N) do echo "Iteration $i" ../scripts/time -a -o ${TIME_FILE} -f "Command: %C\n[mm:ss.ms]: %E\n" $PYTHON $RUN -c "${CONFIG}" -l "${LOGGINGCONFIGS}" sleep 5 done echo "All done!"
#pragma once #include <core/types.h> #include <core/platform.h> namespace core { #ifdef CORE_PLATFORM_WIN //code from: http://seanmiddleditch.com/journal/2011/05/compile-time-string-hashing-in-c0x/ // FNV-1a constants static const uint64_t fnv1a_basis = 14695981039346656037ULL; static const uint64_t fnv1a_prime = 1099511628211ULL; // compile-time hash helper function inline uint64_t hash_one_fnv1a(char c, const char* remain, uint64_t value) { return c == 0 ? value : hash_one_fnv1a(remain[0], remain + 1, (value ^ c) * fnv1a_prime); } // compile-time hash inline uint64_t hash_fnv1a(const char* str) { return hash_one_fnv1a(str[0], str + 1, fnv1a_basis); } #else //code from: http://seanmiddleditch.com/journal/2011/05/compile-time-string-hashing-in-c0x/ // FNV-1a constants static constexpr uint64_t fnv1a_basis = 14695981039346656037ULL; static constexpr uint64_t fnv1a_prime = 1099511628211ULL; // compile-time hash helper function constexpr uint64_t hash_one_fnv1a(char c, const char* remain, uint64_t value) { return c == 0 ? value : hash_one_fnv1a(remain[0], remain + 1, (value ^ c) * fnv1a_prime); } // compile-time hash constexpr uint64_t hash_fnv1a(const char* str) { return hash_one_fnv1a(str[0], str + 1, fnv1a_basis); } #endif }
#!/bin/bash mkdir ~/data mkdir ~/data/raw cd ~/data/raw/ echo -n "ISPRS username:" read username echo -n "ISPRS password:" read -s password if [ -f "ISPRS_semantic_labeling_Vaihingen_ground_truth_COMPLETE.zip" ]; then echo "ISPRS_semantic_labeling_Vaihingen_ground_truth_COMPLETE.zip exists" else wget ftp://$username:$password@ftp.ipi.uni-hannover.de/ISPRS_BENCHMARK_DATASETS/Vaihingen/ISPRS_semantic_labeling_Vaihingen_ground_truth_COMPLETE.zip fi mkdir ~/data/raw/gts unzip ISPRS_semantic_labeling_Vaihingen_ground_truth_COMPLETE.zip -d ~/data/raw/gts/ if [ -f "ISPRS_semantic_labeling_Vaihingen.zip" ]; then echo "ISPRS_semantic_labeling_Vaihingen.zip exists" else wget ftp://$username:$password@ftp.ipi.uni-hannover.de/ISPRS_BENCHMARK_DATASETS/Vaihingen/ISPRS_semantic_labeling_Vaihingen.zip fi unzip ISPRS_semantic_labeling_Vaihingen.zip
import React, { Component } from 'react'; import Location from './location_info'; import MethodPayments from './method_payments'; import Categories from './categories'; import Amounts from './amounts'; import Controls from './controls'; export default class extends Component { render() { return ( <div> <Location /> <MethodPayments /> <Amounts /> <Categories /> <Controls /> </div> ) } }
from core import * from torch_backend import * from td import Conv2d_TD, Linear_TD, Conv2d_col_TD # Network definition def conv_bn_TD(c_in, c_out, gamma=0.0, alpha=0.0, block_size=16): return { # 'conv': nn.Conv2d(c_in, c_out, kernel_size=3, stride=1, padding=1, bias=False), 'conv': Conv2d_TD(c_in, c_out, kernel_size=3, stride=1, padding=1, bias=False, gamma=gamma, alpha=alpha, block_size=block_size), 'bn': BatchNorm(c_out), 'relu': nn.ReLU(True) } def conv_bn(c_in, c_out): return { 'conv': nn.Conv2d(c_in, c_out, kernel_size=3, stride=1, padding=1, bias=False), 'bn': BatchNorm(c_out), 'relu': nn.ReLU(True) } def residual(c): return { 'in': Identity(), 'res1': conv_bn_TD(c, c), 'res2': conv_bn_TD(c, c), 'add': (Add(), ['in', 'res2/relu']), } def net(channels=None, weight=0.125, pool=nn.MaxPool2d(2), extra_layers=(), res_layers=('layer1', 'layer3'), gamma=0.0, alpha=0.0, block_size=16): channels = channels or {'prep': 64, 'layer1': 128, 'layer2': 256, 'layer3': 512} n = { 'input': (None, []), 'prep': conv_bn(3, channels['prep']), 'layer1': dict(conv_bn_TD(channels['prep'], channels['layer1'], gamma=gamma, alpha=alpha, block_size=block_size), pool=pool), 'layer2': dict(conv_bn_TD(channels['layer1'], channels['layer2'], gamma=gamma, alpha=alpha, block_size=block_size), pool=pool), 'layer3': dict(conv_bn_TD(channels['layer2'], channels['layer3'], gamma=gamma, alpha=alpha, block_size=block_size), pool=pool), 'pool': nn.MaxPool2d(4), 'flatten': Flatten(), 'linear': nn.Linear(channels['layer3'], 10, bias=False), 'logits': Mul(weight), } for layer in res_layers: n[layer]['residual'] = residual(channels[layer]) for layer in extra_layers: n[layer]['extra'] = conv_bn(channels[layer], channels[layer], gamma=gamma, alpha=alpha, block_size=block_size) return n
<reponame>xiapeng612430/guns package com.stylefeng.guns.api.cinema.vo; import java.io.Serializable; import lombok.Data; /** * Created by xianpeng.xia * on 2020/6/29 10:25 下午 */ @Data public class HallInfoVO implements Serializable { private String hallFieldId; private String hallName; private String price; private String seatFile; private String soldSeats; }
<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.android = void 0; var android = { "viewBox": "0 0 1408 1792", "children": [{ "name": "path", "attribs": { "d": "M493 483q16 0 27.5-11.5t11.5-27.5-11.5-27.5-27.5-11.5-27 11.5-11 27.5 11 27.5 27 11.5zM915 483q16 0 27-11.5t11-27.5-11-27.5-27-11.5-27.5 11.5-11.5 27.5 11.5 27.5 27.5 11.5zM103 667q42 0 72 30t30 72v430q0 43-29.5 73t-72.5 30-73-30-30-73v-430q0-42 30-72t73-30zM1163 686v666q0 46-32 78t-77 32h-75v227q0 43-30 73t-73 30-73-30-30-73v-227h-138v227q0 43-30 73t-73 30q-42 0-72-30t-30-73l-1-227h-74q-46 0-78-32t-32-78v-666h918zM931 281q107 55 171 153.5t64 215.5h-925q0-117 64-215.5t172-153.5l-71-131q-7-13 5-20 13-6 20 6l72 132q95-42 201-42t201 42l72-132q7-12 20-6 12 7 5 20zM1408 769v430q0 43-30 73t-73 30q-42 0-72-30t-30-73v-430q0-43 30-72.5t72-29.5q43 0 73 29.5t30 72.5z" } }] }; exports.android = android;
<gh_stars>10-100 const client = require("../index"); client.on("messageCreate", async (message) => { if (message.content === `<@${client.user.id}>` || message.content === `<@!${client.user.id}>`) return message.channel.send({ content: `Hi ${message.author} I'm **${client.user.username}**\nA powerful slash Moderation Discord bot` }) if ( message.author.bot || !message.guild ) return; });
<reponame>bulutcnsu/design-patterns<gh_stars>0 public class FartafelleMincedMeats extends PastaDish { @Override protected void addPasta() { System.out.println("Add fartafelle"); } @Override protected void addProtein() { System.out.println("Add minced meat"); } @Override protected void addSouce() { System.out.println("Add hot souce"); } }
import * as d3 from 'd3' // import './assets/css/chart1.css' // import './assets/css/chart2.css' // import './assets/css/chart3.css' window.d3 = d3 renderChart4() function renderChart1() { let data = [4, 8, 15, 16, 23, 42] d3.select('body').append(d3.creator('div')).attr('id', 'chart') .selectAll('div') .data(data) .enter() .append('div') .style('height', d => d + 'px') } function renderChart2() { let colorMap = d3.interpolateRgb( d3.rgb('#d6e685'), d3.rgb('#1e6823') ) let data = [.2, .4, 0, 0, .13, .92] d3.select('body').append(d3.creator('div')).attr('id', 'chart') .selectAll('div') .data(data) .enter() .append('div') .style('background-color', (d) => { return d === 0 ? '#eee' : colorMap(d) }) } function helloSvg() { let chart = d3.select('body').append(d3.creator('svg')).attr('id', 'chart').attr('width', 200).attr('height', 200) let data = [ { x: 100, y: 90 }, { x: 150, y: 30 }, { x: 50, y: 30 }, { x: 100, y: 90 } ] chart.append('circle') .attr('fill', '#3E5693') .attr('cx', 50) .attr('cy', 120) .attr('r', 20) chart.append('text') .attr('x', 100) .attr('y', 100) .text('Hello SVG!') let line = d3.line() .x(d => d.x) .y(d => 100 - d.y) chart.append('path') .attr('fill', '#BEDBC3') .attr('stroke', '#539E91') .attr('stroke-width', 3) .attr('d', line(data)) } function renderChart3() { let data = [{ label: "7am", sales: 20 }, { label: "8am", sales: 12 }, { label: "9am", sales: 8 }, { label: "10am", sales: 27 }] let g = d3.select('body').append(d3.creator('svg')).attr('id', 'chart').attr('width', 250).attr('height', 100) .selectAll('g') .data(data) .enter() .append('g') g.append('circle') .attr('cy', 40) .attr('cx', (d, i) => (i + 1) * 50) .attr('r', d => d.sales) g.append('text') .attr('y', 90) .attr('x', (d, i) => (i + 1) * 50) .text(d => d.label) } function renderChart4() { let data = [ { x: 0, y: 30 }, { x: 50, y: 20 }, { x: 100, y: 40 }, { x: 150, y: 80 }, { x: 200, y: 95 } ] let height = window.innerHeight let width = window.innerWidth let padding = 20 let xScale = d3.scaleLinear() .domain([0, 200]) .range([padding, width - padding]) let yScale = d3.scaleLinear() .domain([0, 100]) .range([height - padding, padding]) let line = d3.line() .x((d) => xScale(d.x)) .y((d) => yScale(d.y)) .curve(d3.curveLinear); let chart = d3.select('body').append(d3.creator('svg')).attr('id', 'chart').attr('width', width).attr('height', height) chart.append('path') .attr('fill', 'transparent') .attr('stroke', 'green') .attr('stroke-width', 2) .attr('d', line(data)) }
<filename>modules/component-web-core/src/main/java/com/nortal/spring/cw/core/web/component/step/StepHolderHelper.java package com.nortal.spring.cw.core.web.component.step; import com.nortal.spring.cw.core.web.component.ElementVisibility; import com.nortal.spring.cw.core.web.component.Hierarchical; import com.nortal.spring.cw.core.web.component.css.ButtonElementCssClass; import com.nortal.spring.cw.core.web.component.event.EventElementFactory; import com.nortal.spring.cw.core.web.component.event.EventElementFactory.Type; /** * Tegemist on sammuobjektiga toimetamist toetava abiklassiga * * @author <NAME> * */ public final class StepHolderHelper { private StepHolderHelper() { super(); } public static StepHolderComplexComponent addVormDokumentSaveAndPdfButtons(StepHolderComplexComponent holderComplexComponent) { holderComplexComponent.addMainButton(EventElementFactory.createButton(Type.SHOW_PDF, ButtonElementCssClass.BUTTON_ALT)); holderComplexComponent.addMainButton(EventElementFactory.createButton(Type.SAVE)).setVisibility(new ElementVisibility() { private static final long serialVersionUID = 1L; @Override public boolean isVisible(Hierarchical component) { StepHolderComplexComponent complexCopmpnent = (StepHolderComplexComponent) component; return complexCopmpnent.getActiveStepNr() < complexCopmpnent.getStepCount(); } }); holderComplexComponent.addMainButton(EventElementFactory.createButton(Type.SAVE_NEXT)).setVisibility(new ElementVisibility() { private static final long serialVersionUID = 1L; @Override public boolean isVisible(Hierarchical component) { StepHolderComplexComponent complexCopmpnent = (StepHolderComplexComponent) component; return complexCopmpnent.getActiveStepNr() < complexCopmpnent.getStepCount(); } }); return holderComplexComponent; } }
#!/bin/bash set -euo pipefail # restore_db.sh # This script will create a DynamoDB Table from a restore on an existing Backup. # NOTE: If there's an existing DynamoDB Table with the same name, the Table will # need to be deleted before the backup can be started. # Arguments: # -t|--target-table-name - Name of the DynamoDB Table to create # -l|--list-backups - Flag to list backups available for the DynamoDB Table provided # -b|--backup-arn - ARN of the DynamoDB Table Backup to restore from # -f|--force-delete-table - Flag to indicate a deletion of the DynamoDB Table if it exists # # Example: # # List available backups for table # ./restore_db.sh --target-table-name my-table-name --list-backups # # Target table doesn't exist, restore # ./restore_db.sh --target-table-name my-table-name --backup-arn arn:aws:dynamodb:us-east-1:123456789012:table/my-table-name/backup/5678901234-987654 # # Target table exists, force delete the table, restore # ./restore_db.sh --target-table-name my-table-name --backup-arn arn:aws:dynamodb:us-east-1:123456789012:table/my-table-name/backup/5678901234-987654 --force-delete-table # # Required tools on execution host: # Bourne Again SHell (documented for completeness) # aws - AWS Command Line Interface - https://aws.amazon.com/cli/ # Setup Parameters TARGET_TABLE_NAME="" LIST_BACKUPS="" BACKUP_ARN="" FORCE_DELETE_TABLE="" PARAMS="" while (( "$#" )); do case "$1" in -t|--target-table-name) TARGET_TABLE_NAME=$2 shift 2 ;; -l|--list-backups) LIST_BACKUPS=true shift 1 ;; -b|--backup-arn) BACKUP_ARN=$2 shift 2 ;; -f|--force-delete-table) FORCE_DELETE_TABLE=true shift 1 ;; -*|--*=) # unsupported flags echo "Error: Unsupported flag $1" >&2 exit 1 ;; *) # preserve positional arguments PARAMS="$PARAMS $1" shift ;; esac done # Verify Parameters if test -z "$TARGET_TABLE_NAME"; then echo "Please provide the argument '-t' or '--target-table-name' with the DynamoDB Table Name to restore to" exit 1 fi if test ! -z "$LIST_BACKUPS"; then echo "Listing backups for $TARGET_TABLE_NAME" aws dynamodb list-backups --table-name $TARGET_TABLE_NAME exit 0 fi if test -z "$BACKUP_ARN"; then echo "Please provide the arguments '-b|--backup-arn' to backup the DynamoDB Table from an existing Backup" echo "Listing backups for $TARGET_TABLE_NAME" aws dynamodb list-backups --table-name $TARGET_TABLE_NAME exit 1 fi # Check if Backup Exists echo "Checking Backup $BACKUP_ARN exists.." if aws dynamodb describe-backup --backup-arn $BACKUP_ARN; then # Backup Exists echo "Backup $BACKUP_ARN exists" else # Backup Doesn't Exist, exit echo "Backup $BACKUP_ARN doesn't exist, exiting" exit 1 fi # Check if Table Exists, Remove Table if so echo "Checking if Table $TARGET_TABLE_NAME exists" if aws dynamodb describe-table --table-name $TARGET_TABLE_NAME; then echo "Table $TARGET_TABLE_NAME exists" # Check if force flag is enable if test -z "$FORCE_DELETE_TABLE"; then # Force delete flag must be provided, exit echo "Cannot delete $TARGET_TABLE_NAME without 'f|--force-delete-table' flag, exiting" exit 1 fi # Delete Table echo "Deleting Table $TARGET_TABLE_NAME..." aws dynamodb delete-table --table-name $TARGET_TABLE_NAME # Loop until dynamodb is deleted while aws dynamodb describe-table --table-name $TARGET_TABLE_NAME > /dev/null; do echo "Waiting for deletion to complete..." sleep 5 done echo "Deleting Table $TARGET_TABLE_NAME complete" else # Table doesn't exist, no deletion echo "Table $TARGET_TABLE_NAME doesn't exist" fi # Restore DynamoDB Table to the latest restorable time echo "Start Restoration of Table $TARGET_TABLE_NAME with $BACKUP_ARN..." aws dynamodb restore-table-from-backup \ --target-table-name $TARGET_TABLE_NAME \ --backup-arn $BACKUP_ARN echo "Restoring Table $TARGET_TABLE_NAME with $BACKUP_ARN started" echo "Check Table Status with command 'aws dynamodb describe-table --table-name $TARGET_TABLE_NAME'"
class Program1 { public static void main(String[] args) { int n = Svetovid.in.readInt("Koliko karaktera unosite:"); Lista lista = new Lista(); for (int i = 0; i < n; i++) { lista.dodaj(Svetovid.in.readChar(String.format("Unesite %d. karakter:", i + 1))); } Svetovid.out.print("Velika slova: "); lista.ispisiVelika(); Svetovid.out.print("Lista pre izbacivanja malih: "); Svetovid.out.println(lista); lista.izbaciMala(); Svetovid.out.print("Lista posle izbacivanja malih: "); Svetovid.out.println(lista); Lista listaCifara = lista.izvdojiCifre(); Svetovid.out.print("Izdvojene cife u drugu listu: "); Svetovid.out.println(listaCifara); Svetovid.out.print("Originalna lista bez cifara: "); Svetovid.out.println(lista); } }
<filename>src/components/Select.tsx import * as React from 'react'; import { useIntl } from 'react-intl'; import debounce from '../utils/debounce-promise'; import { Select as CapSelect, AsyncSelect } from '@cap-collectif/ui'; export type Option = { value: string, label: string }; export type Value = string | Array<{ value: string }> | { value: string } | Option; const DEBOUNCE_MS = 400; export interface SelectProps { placeholder?: string; noOptionsMessage?: string; loadingMessage?: string; isMulti?: boolean; options?: Array<Option>; loadOptions?: (search: string) => Promise<(Option | undefined)[] | undefined>; onChange?: (value: Value) => void; value?: Value | Option; defaultOptions?: boolean; clearable?: boolean; role?: string; } export const Select: React.FC<SelectProps> = ({ loadOptions, options, onChange, noOptionsMessage, loadingMessage, value, clearable, ...rest }) => { const intl = useIntl(); if (loadOptions) { const loadOptionsDebounced = debounce(loadOptions, DEBOUNCE_MS, { leading: true, }); return ( <AsyncSelect {...rest} isClearable={clearable} value={value} loadOptions={loadOptionsDebounced} loadingMessage={() => loadingMessage || intl.formatMessage({ id: 'global.loading' }) } noOptionsMessage={() => noOptionsMessage || intl.formatMessage({ id: 'result-not-found' }) } placeholder={ rest.placeholder || intl.formatMessage({ id: 'admin.fields.menu_item.parent_empty' }) } onChange={newValue => { if (typeof onChange === 'function') { onChange(rest.isMulti ? newValue : newValue?.value || ''); } }} /> ); } return ( <CapSelect {...rest} isClearable={clearable} options={options} noOptionsMessage={() => noOptionsMessage || intl.formatMessage({ id: 'result-not-found' }) } placeholder={ rest.placeholder || intl.formatMessage({ id: 'admin.fields.menu_item.parent_empty' }) } value={options?.find(option => option.value === value)} onChange={newValue => { if (typeof onChange === 'function') { onChange(rest.isMulti ? newValue : newValue?.value || ''); } }} /> ); }; export default Select;
<reponame>nimoqqq/roses package cn.stylefeng.roses.kernel.system.integration.config; import cn.stylefeng.roses.kernel.system.integration.CustomErrorView; import cn.stylefeng.roses.kernel.system.integration.core.CustomBeetlGroupUtilConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 错误界面自动配置,一般用于404响应 * * @author fengshuonan * @date 2021/5/17 11:16 */ @Configuration @AutoConfigureBefore(ErrorMvcAutoConfiguration.class) public class BeetlErrorViewAutoConfiguration { /** * 默认错误页面,返回json * * @author fengshuonan * @date 2020/12/16 15:47 */ @Bean("error") public CustomErrorView error(CustomBeetlGroupUtilConfiguration customBeetlGroupUtilConfiguration) { CustomErrorView customErrorView = new CustomErrorView(); customErrorView.setUrl("/404.html"); customErrorView.setGroupTemplate(customBeetlGroupUtilConfiguration.getGroupTemplate()); return customErrorView; } }
myApp.compileProvider.directive("categotysDirective", function() { return { restrict: "E", templateUrl: '/app/components/directives/categoty/views/categorys-template.html', controller: 'categorysDirectiveController' }; }); myApp.controllerProvider.register("categorysDirectiveController", function( $scope, categoryService ) { async.auto({ startLoading : function(cb){ cb(null, true); }, getCategory : ['startLoading', function(cb, result){ var option = { data : {} }; categoryService.get_category(option).then(function(response){ console.log("response : ", response) cb(null, response); }).catch(function(err){ cb(err); }) }] }, function(err, result){ if(err){ }else{ $scope.categorys = result.getCategory['results']; } }); });
/* * Copyright (c) 2018 https://www.reactivedesignpatterns.com/ * * Copyright (c) 2018 https://rdp.reactiveplatform.xyz/ * */ package chapter03; // Listing 3.1 Unsafe, mutable message class, which may hide unexpected behavior // #snip import java.util.Date; public class Unsafe { private Date timestamp; private final StringBuffer message; public Unsafe(Date timestamp, StringBuffer message) { this.timestamp = timestamp; this.message = message; } public synchronized Date getTimestamp() { return timestamp; } public synchronized void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public StringBuffer getMessage() { return message; } } // #snip
/* * VMware SD-WAN * * data_source_ */ package velocloud import ( "context" //"strconv" "fmt" //"log" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "terraform-provider-velocloud/velocloud/vcoclient" ) func dataSourceVeloEdge() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceVeloEdgeRead, Schema: map[string]*schema.Schema{ "name": &schema.Schema{ Type: schema.TypeString, Required: true, Description: "edge name", }, "edge_id": &schema.Schema{ Type: schema.TypeInt, Computed: true, Description: "edge id", }, "activation_key": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "activation key", }, "build_number": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "software build number", }, "custom_info": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "custom info", }, "description": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "description", }, "device_family": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "device family", }, "device_id": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "device id", }, "edge_state": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "edge state", }, "endpoint_pki_mode": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "endpoint_pki_mode", }, "enterprise_id": &schema.Schema{ Type: schema.TypeInt, Computed: true, Description: "enterprise_id", }, "factory_software_version": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "factory software version", }, "factory_build_number": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "factory software build number", }, "ha_previous_state": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "ha_previous_state", }, "ha_serial_number": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "serial number of HA secundry device", }, "ha_state": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "HA status", }, "model_number": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "model number", }, "self_mac_address": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "mac address of device", }, "serial_number": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "serial number of device", }, "site_id": &schema.Schema{ Type: schema.TypeInt, Computed: true, Description: "site id of edge", }, "software_version": &schema.Schema{ Type: schema.TypeString, Computed: true, Description: "software version ", }, "is_hub": &schema.Schema{ Type: schema.TypeBool, Computed: true, Description: "true is configurated hub", }, "is_software_version_supported_by_vco": &schema.Schema{ Type: schema.TypeBool, Computed: true, Description: "If true, the device is using supoerted software version ", }, }, } } func dataSourceVeloEdgeRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { var diags diag.Diagnostics var edge *vcoclient.EnterpriseGetEnterpriseEdgesResultItem edge = nil name := d.Get("name").(string) c := m.(*vcoclient.APIClient) post := &vcoclient.EnterpriseGetEnterpriseEdges{ Id: 0, } a, _, err := c.EnterpriseApi.EnterpriseGetEnterpriseEdges(nil, *post) if err != nil { return diag.FromErr(err) } for _, v := range a { if v.Name == name { edge = &v break } } if edge == nil { return diag.Errorf("Not Found Edge[" + name + "]") } d.Set("edge_id", edge.Id) d.Set("activation_key", edge.ActivationKey) d.Set("build_number", edge.BuildNumber) d.Set("custom_info", edge.CustomInfo) d.Set("description", edge.Description) d.Set("device_family", edge.DeviceFamily) d.Set("device_id", edge.DeviceId) d.Set("edge_state", edge.EdgeState) d.Set("endpoint_pki_mode", edge.EndpointPkiMode) d.Set("enterprise_id", edge.EnterpriseId) d.Set("factory_software_version", edge.FactorySoftwareVersion) d.Set("factory_build_number", edge.FactoryBuildNumber) d.Set("ha_previous_state", edge.HaPreviousState) d.Set("ha_serial_number", edge.HaSerialNumber) d.Set("ha_state", edge.HaState) d.Set("model_number", edge.ModelNumber) d.Set("self_mac_address", edge.SelfMacAddress) d.Set("serial_number", edge.SerialNumber) d.Set("site_id", edge.SiteId) d.Set("software_version", edge.SoftwareVersion) d.Set("is_hub", edge.IsHub) d.Set("is_software_version_supported_by_vco", edge.IsSoftwareVersionSupportedByVco) d.SetId(fmt.Sprintf("%d", edge.Id)) return diags }
<gh_stars>0 function MaximumValue(number){ // transform in string var str = number.toString(); var result = ''; // Check that the First is bigger than Last value if(str[0] > str[str.length -1]){result = str.substring(0,str.length-1);} else{result = str.substring(1);} return parseInt(result); } console.log(MaximumValue(1000)); console.log(MaximumValue(1245)); console.log(MaximumValue(10));
export function makeErr(message: string): never { throw new Error(message); } export function isNullOrUndefined<T>(obj: T | null | undefined): obj is null | undefined { return typeof obj === 'undefined' || obj === null; }
from direct.showbase.ShowBaseGlobal import * from direct.directnotify.DirectNotifyGlobal import directNotify from otp.uberdog.RejectCode import RejectCode from otp.otpbase import OTPGlobals from otp.otpgui import OTPDialog from pirates.economy.EconomyGlobals import * from pirates.distributed import InteractGlobals from pirates.piratesbase import PiratesGlobals from pirates.piratesgui import PiratesGuiGlobals from pirates.economy import StoreGUI, AccessoriesStoreGUI, TattooStoreGUI, JewelryStoreGUI, BarberStoreGUI, MusicianGUI, StowawayGUI, SimpleStoreGUI from pirates.economy import ShipStoreGUI from pirates.uberdog.UberDogGlobals import * from pirates.uberdog.DistributedInventoryBase import DistributedInventoryBase from direct.interval.IntervalGlobal import * from pirates.piratesbase import PLocalizer from pirates.piratesgui import PDialog from pirates.pirate import AvatarTypes from pirates.piratesgui.ShipShoppingPanel import ShipShoppingPanel from pirates.economy.EconomyGlobals import * from pirates.economy import EconomyGlobals from pirates.ship.ShipGlobals import * from pirates.leveleditor import NPCList from pirates.makeapirate import ClothingGlobals from pirates.inventory import InventorySellConfirm from pirates.inventory import DropGlobals from pirates.inventory import InventoryGlobals from pirates.world.DistributedIsland import DistributedIsland class DistributedShopKeeper: notify = directNotify.newCategory('DistributedShopKeeper') shopCoins = None barberCoin = None blacksmithCoin = None gunsmithCoin = None jewelerCoin = None shipwrightCoin = None tailorCoin = None tattooCoin = None gypsyCoin = None trainerCoin = None pvpRewardsCoin = None musicianCoin = None stowawayCoin = None cannonCoin = None fishingCoin = None catalogrepCoin = None def __init__(self): self.shopInventory = [] self.shopCoin = None self.shopCoinGlow = None self._DistributedShopKeeper__invRequest = None self.storePush = False def generate(self): DistributedShopKeeper.notify.debug('generate(%s)' % self.doId) self.storeMenuGUI = None self.pickShipGUI = None self.confirmDialog = None self.fadeIval = None self.storeType = None def announceGenerate(self): DistributedShopKeeper.notify.debug('announceGenerate(%s)' % self.doId) self.loadShopCoin() if self.avatarType.isA(AvatarTypes.Cannoneer): self.shopInventory = CANNON_AMMO_SHELF_L1 + CANNON_AMMO_SHELF_L2 + CANNON_POUCH_SHELF elif self.avatarType.isA(AvatarTypes.Blacksmith): if base.config.GetBool('low-weapons-only', 0): self.shopInventory = MELEE_SHELF_L1 + MELEE_SHELF_L2 + DAGGER_AMMO_SHELF_L1 + DAGGER_AMMO_SHELF_L2 + DAGGER_POUCH_SHELF else: self.shopInventory = MELEE_SHELF_L1 + MELEE_SHELF_L2 + MELEE_SHELF_L3 + DAGGER_AMMO_SHELF_L1 + DAGGER_AMMO_SHELF_L2 + DAGGER_POUCH_SHELF elif self.avatarType.isA(AvatarTypes.Bartender): self.shopInventory = MELEE_SHELF_L1 + MISSILE_SHELF_L1 + BOMB_SHELF_L1 elif self.avatarType.isA(AvatarTypes.Gunsmith): if base.config.GetBool('low-weapons-only', 0): self.shopInventory = MISSILE_SHELF_L1 + MISSILE_SHELF_L2 + PISTOL_AMMO_SHELF_L1 + PISTOL_AMMO_SHELF_L2 + PISTOL_POUCH_SHELF + BOMB_SHELF_L1 + BOMB_SHELF_L2 + BOMB_AMMO_SHELF_L1 + BOMB_AMMO_SHELF_L2 + GRENADE_POUCH_SHELF + CANNON_AMMO_SHELF_L1 + CANNON_AMMO_SHELF_L2 + CANNON_POUCH_SHELF else: self.shopInventory = MISSILE_SHELF_L1 + MISSILE_SHELF_L2 + MISSILE_SHELF_L3 + PISTOL_AMMO_SHELF_L1 + PISTOL_AMMO_SHELF_L2 + PISTOL_POUCH_SHELF + BOMB_SHELF_L1 + BOMB_SHELF_L2 + BOMB_SHELF_L3 + BOMB_AMMO_SHELF_L1 + BOMB_AMMO_SHELF_L2 + GRENADE_POUCH_SHELF + CANNON_AMMO_SHELF_L1 + CANNON_AMMO_SHELF_L2 + CANNON_POUCH_SHELF elif self.avatarType.isA(AvatarTypes.Grenadier): self.shopInventory = BOMB_SHELF_L1 + BOMB_SHELF_L2 + BOMB_SHELF_L3 + BOMB_AMMO_SHELF_L1 + BOMB_AMMO_SHELF_L2 + GRENADE_POUCH_SHELF elif self.avatarType.isA(AvatarTypes.Gypsy): if base.config.GetBool('low-weapons-only', 0): self.shopInventory = TONIC_SHELF_L1 + TONIC_SHELF_L2 + MOJO_SHELF_L1 + MOJO_SHELF_L2 else: self.shopInventory = TONIC_SHELF_L1 + TONIC_SHELF_L2 + MOJO_SHELF_ALL elif self.avatarType.isA(AvatarTypes.Merchant): self.shopInventory = PISTOL_AMMO_SHELF_L1 + MELEE_SHELF_L1 + MISSILE_SHELF_L1 elif self.avatarType.isA(AvatarTypes.MedicineMan): self.shopInventory = TONIC_SHELF_L1 + TONIC_SHELF_L2 elif self.avatarType.isA(AvatarTypes.Musician): self.shopInventory = MUSIC_SHELF elif self.avatarType.isA(AvatarTypes.Stowaway): par = self.getParentObj() self.shopInventory = _[1] elif self.avatarType.isA(AvatarTypes.Fishmaster): self.shopInventory = FISHING_LURE_SHELF def loadShopCoin(self): if not DistributedShopKeeper.shopCoins: DistributedShopKeeper.shopCoins = loader.loadModel('models/textureCards/shopCoins') if not DistributedShopKeeper.barberCoin: DistributedShopKeeper.barberCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_barber') if not DistributedShopKeeper.blacksmithCoin: DistributedShopKeeper.blacksmithCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_blacksmith') if not DistributedShopKeeper.gunsmithCoin: DistributedShopKeeper.gunsmithCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_gunsmith') if not DistributedShopKeeper.jewelerCoin: DistributedShopKeeper.jewelerCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_jeweler') if not DistributedShopKeeper.shipwrightCoin: DistributedShopKeeper.shipwrightCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_shipwright') if not DistributedShopKeeper.tailorCoin: DistributedShopKeeper.tailorCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_tailor') if not DistributedShopKeeper.tattooCoin: DistributedShopKeeper.tattooCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_tattoo') if not DistributedShopKeeper.gypsyCoin: DistributedShopKeeper.gypsyCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_voodoo') if not DistributedShopKeeper.trainerCoin: DistributedShopKeeper.trainerCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_trainer') if not DistributedShopKeeper.pvpRewardsCoin: DistributedShopKeeper.pvpRewardsCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_jeweler') if not DistributedShopKeeper.musicianCoin: DistributedShopKeeper.musicianCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_music') if not DistributedShopKeeper.stowawayCoin: DistributedShopKeeper.stowawayCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_stowaway') if not DistributedShopKeeper.cannonCoin: DistributedShopKeeper.cannonCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_cannon') if not DistributedShopKeeper.fishingCoin: DistributedShopKeeper.fishingCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_fishing') if not DistributedShopKeeper.catalogrepCoin: DistributedShopKeeper.catalogrepCoin = DistributedShopKeeper.shopCoins.find('**/shopCoin_catalog') if not self.shopCoin: if DistributedShopKeeper.shopCoins: if self.avatarType.isA(AvatarTypes.Barber): tex = DistributedShopKeeper.barberCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Blacksmith): tex = DistributedShopKeeper.blacksmithCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Gunsmith): tex = DistributedShopKeeper.gunsmithCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Jeweler): tex = DistributedShopKeeper.jewelerCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Shipwright): tex = DistributedShopKeeper.shipwrightCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Tailor): tex = DistributedShopKeeper.tailorCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Tattoo): tex = DistributedShopKeeper.tattooCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Gypsy): tex = DistributedShopKeeper.gypsyCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Musician): tex = DistributedShopKeeper.musicianCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Trainer): tex = DistributedShopKeeper.trainerCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.PvPRewards): tex = DistributedShopKeeper.pvpRewardsCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Stowaway): tex = DistributedShopKeeper.stowawayCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Cannonmaster): tex = DistributedShopKeeper.cannonCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.Fishmaster): tex = DistributedShopKeeper.fishingCoin.copyTo(self.nametag3d) elif self.avatarType.isA(AvatarTypes.CatalogRep): tex = DistributedShopKeeper.catalogrepCoin.copyTo(self.nametag3d) else: tex = None if tex: self.shopCoin = tex if self.nametagIcon: self.shopCoin.setScale(2.0) self.shopCoin.setPos(0.0, 0.0, 7.0) else: self.shopCoin.setScale(2.5) self.shopCoin.setPos(0.0, 0.0, 3.5) self.shopCoin.reparentTo(self.getNameText()) self.shopCoin.setDepthWrite(0) self.shopCoinGlow = loader.loadModel('models/effects/lanternGlow') self.shopCoinGlow.reparentTo(self.nametag.getNameIcon()) self.shopCoinGlow.setColorScaleOff() self.shopCoinGlow.setFogOff() self.shopCoinGlow.setLightOff() if not self.nametagIcon: self.shopCoinGlow.setScale(20.0) self.shopCoinGlow.setPos(0, -0.050000000000000003, 3.0) else: self.shopCoinGlow.setScale(15.0) self.shopCoinGlow.setPos(0, -0.050000000000000003, 6.5) self.shopCoinGlow.setDepthWrite(0) self.shopCoinGlow.node().setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne)) self.shopCoinGlow.setColor(0.84999999999999998, 0.84999999999999998, 0.84999999999999998, 0.84999999999999998) elif self.nametagIcon: self.shopCoin.setScale(2.0) self.shopCoin.setPos(0.0, 0.0, 7.0) else: self.shopCoin.setScale(2.5) self.shopCoin.setPos(0.0, 0.0, 3.5) self.shopCoin.reparentTo(self.getNameText()) self.shopCoinGlow.reparentTo(self.nametag.getNameIcon()) if not self.nametagIcon: self.shopCoinGlow.setScale(20.0) self.shopCoinGlow.setPos(0, -0.050000000000000003, 3.0) else: self.shopCoinGlow.setScale(15.0) self.shopCoinGlow.setPos(0, -0.050000000000000003, 6.5) def disable(self): DistributedShopKeeper.notify.debug('disable(%s)' % self.doId) self.finishShopping() def delete(self): DistributedShopKeeper.notify.debug('delete(%s)' % self.doId) def resumeShopping(self): self.accept('makeSale', self.sendRequestMakeSale) self.acceptOnce('exitStore', self.finishShopping) self.acceptOnce('makeShipSale', self.sendRequestMakeShipSale) self.acceptOnce('purchaseAccessories', self.sendRequestAccessories) self.acceptOnce('requestMusic', self.sendRequestMusic) self.acceptOnce('requestStowaway', self.sendRequestStowaway) def startShopping(self, storeType): self.accept('makeSale', self.sendRequestMakeSale) self.acceptOnce('exitStore', self.finishShopping) self.acceptOnce('makeShipSale', self.sendRequestMakeShipSale) self.acceptOnce('purchaseAccessories', self.sendRequestAccessories) self.acceptOnce('requestMusic', self.sendRequestMusic) self.acceptOnce('requestStowaway', self.sendRequestStowaway) self.storeType = storeType simpleStoreList = getBase().config.GetString('want-simple-stores', '').lower() useSimpleStore = 1 if storeType == InteractGlobals.STORE: storeItems = DropGlobals.getStoreItems(self.uniqueId) inventory = ItemGlobals.getLegalStoreItems(storeItems) if not inventory: inventory = self.shopInventory[:] elif self.avatarType.isA(AvatarTypes.Blacksmith): inventory += DAGGER_AMMO_SHELF_L1 + DAGGER_AMMO_SHELF_L2 + DAGGER_POUCH_SHELF elif self.avatarType.isA(AvatarTypes.Gunsmith): inventory += PISTOL_AMMO_SHELF_L1 + PISTOL_AMMO_SHELF_L2 + PISTOL_POUCH_SHELF + BOMB_AMMO_SHELF_L1 + BOMB_AMMO_SHELF_L2 + GRENADE_POUCH_SHELF + CANNON_AMMO_SHELF_L1 + CANNON_AMMO_SHELF_L2 + CANNON_POUCH_SHELF elif self.avatarType.isA(AvatarTypes.Grenadier): inventory += BOMB_AMMO_SHELF_L1 + BOMB_AMMO_SHELF_L2 + GRENADE_POUCH_SHELF elif self.avatarType.isA(AvatarTypes.Merchant): inventory += PISTOL_AMMO_SHELF_L1 if hasattr(self.cr.distributedDistrict, 'siegeManager') and self.cr.distributedDistrict.siegeManager.getPvpEnabled() and self.cr.distributedDistrict.siegeManager.getUseRepairKit() and self.avatarType.isA(AvatarTypes.Gunsmith): inventory += SIEGE_SHELF if useSimpleStore: self.storeMenuGUI = SimpleStoreGUI.MerchantStoreGUI(inventory, PLocalizer.MerchantStore, self) else: self.storeMenuGUI = StoreGUI.StoreGUI(inventory, PLocalizer.MerchantStore) elif storeType == InteractGlobals.MUSICIAN: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() inventory = self.shopInventory[:] self.storeMenuGUI = MusicianGUI.MusicianGUI(inventory, PLocalizer.InteractMusician) elif storeType == InteractGlobals.STOWAWAY: inventory = self.shopInventory[:] self.storeMenuGUI = StowawayGUI.StowawayGUI(inventory, PLocalizer.StowawayMenuTitle) elif storeType == InteractGlobals.SHIPS: self.storeMenuGUI = ShipStoreGUI.ShipStoreGUI(SHIP_SHELF, PLocalizer.Shipyard) elif storeType == InteractGlobals.TRAIN: pass elif storeType == InteractGlobals.UPGRADE: pass elif storeType == InteractGlobals.ACCESSORIES_STORE: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() if useSimpleStore: self.storeMenuGUI = SimpleStoreGUI.AccessoriesStoreGUI(npc = self, shopId = self.getShopId()) else: self.storeMenuGUI = AccessoriesStoreGUI.AccessoriesStoreGUI(npc = self, shopId = self.getShopId()) elif storeType == InteractGlobals.TATTOO_STORE: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() if useSimpleStore: self.storeMenuGUI = SimpleStoreGUI.TattooStoreGUI(npc = self, shopId = self.getShopId()) else: self.storeMenuGUI = TattooStoreGUI.TattooStoreGUI(npc = self, shopId = self.getShopId()) elif storeType == InteractGlobals.JEWELRY_STORE: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() if useSimpleStore: self.storeMenuGUI = SimpleStoreGUI.JewelryStoreGUI(npc = self, shopId = self.getShopId()) else: self.storeMenuGUI = JewelryStoreGUI.JewelryStoreGUI(npc = self, shopId = self.getShopId()) elif storeType == InteractGlobals.BARBER_STORE: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() self.storeMenuGUI = BarberStoreGUI.BarberStoreGUI(npc = self, shopId = self.getShopId()) elif storeType == InteractGlobals.PVP_REWARDS_TATTOO: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() self.storeMenuGUI = TattooStoreGUI.TattooStoreGUI(npc = self, shopId = PiratesGlobals.PRIVATEER_TATTOOS) elif storeType == InteractGlobals.PVP_REWARDS_HATS: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() self.storeMenuGUI = AccessoriesStoreGUI.AccessoriesStoreGUI(npc = self, shopId = PiratesGlobals.PRIVATEER_HATS) elif storeType == InteractGlobals.PVP_REWARDS_COATS: self.fadeIval = Sequence(Func(self.setTransparency, 1.0), self.colorScaleInterval(1.0, VBase4(1.0, 1.0, 1.0, 0.0)), Func(self.hide)) self.fadeIval.start() self.storeMenuGUI = AccessoriesStoreGUI.AccessoriesStoreGUI(npc = self, shopId = PiratesGlobals.PRIVATEER_COATS) elif storeType == InteractGlobals.CATALOG_STORE: self.storeMenuGUI = SimpleStoreGUI.CatalogStoreGUI(npc = self, shopId = self.getShopId()) self.accept(InventoryGlobals.getCategoryChangeMsg(localAvatar.getInventoryId(), InventoryType.ItemTypeMoney), self.saleFinishedResponse) def finishShopping(self): if self.storePush and self.storeMenuGUI: if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None if self.interactGUI: self.interactGUI.hide() self.storeMenuGUI.show() self.storePush = False return None self.ignore('exitStore') self.ignore('makeSale') self.ignore('makeShipSale') self.ignore('purchaseAccessories') self.ignore('requestMusic') self.ignore('requestStowaway') messenger.send('stoppedShopping') self.ignore(InventoryGlobals.getCategoryChangeMsg(localAvatar.getInventoryId(), InventoryType.ItemTypeMoney)) if self._DistributedShopKeeper__invRequest: DistributedInventoryBase.cancelGetInventory(self._DistributedShopKeeper__invRequest) self._DistributedShopKeeper__invRequest = None if self.storeMenuGUI: self.storeMenuGUI.destroy() self.storeMenuGUI = None if self.pickShipGUI: self.pickShipGUI.destroy() self.pickShipGUI = None if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None self.setColorScale(1, 1, 1, 1) self.setTransparency(0) self.show() if self.fadeIval: self.fadeIval.pause() self.fadeIval = None def saleFinishedResponse(self, extraArgs = None): if self.storeMenuGUI: if self.storeType in (InteractGlobals.STORE, InteractGlobals.SHIPS, InteractGlobals.ACCESSORIES_STORE, InteractGlobals.CATALOG_STORE, InteractGlobals.JEWELRY_STORE, InteractGlobals.TATTOO_STORE, InteractGlobals.BARBER_STORE): self.storeMenuGUI.updateBalance() if self.storeType in (InteractGlobals.ACCESSORIES_STORE, InteractGlobals.JEWELRY_STORE, InteractGlobals.TATTOO_STORE): self.storeMenuGUI.changeMode(1, refresh = True) def sendRequestMakeSale(self, buying = [], selling = []): theBuying = prepareSwitchField(buying) theSelling = prepareSwitchField(selling) self.sendUpdate('requestMakeSale', [ theBuying, theSelling]) def sendRequestMakeShipSale(self, buying = [], selling = [], names = []): self.storeMenuGUI.hide() theBuying = prepareSwitchField(buying) theSelling = prepareSwitchField(selling) self.sendUpdate('requestMakeShipSale', [ theBuying, theSelling, names]) self.finishShopping() def sendRequestMusic(self, songId): self.storeMenuGUI.hide() self.sendUpdate('requestMusic', [ songId]) self.finishShopping() def sendRequestAccessoriesList(self, avId = None): if avId is None: avId = localAvatar.getDoId() self.sendUpdate('requestAccessoriesList', [ avId]) def sendRequestTattooList(self, avId = None): if avId is None: avId = localAvatar.getDoId() self.sendUpdate('requestTattooList', [ avId]) def sendRequestJewelryList(self, avId = None): if avId is None: avId = localAvatar.getDoId() self.sendUpdate('requestJewelryList', [ avId]) def responseClothingList(self, avId, accessories): if self.storeMenuGUI: self.storeMenuGUI.setWardrobe(accessories) def responseTattooList(self, avId, tattoos): if self.storeMenuGUI: self.storeMenuGUI.setWardrobe(tattoos) def responseJewelryList(self, avId, jewelry): if self.storeMenuGUI: self.storeMenuGUI.setWardrobe(jewelry) def sendRequestAccessories(self, purchases, selling): self.sendUpdate('requestAccessories', [ purchases, selling]) def sendRequestJewelry(self, purchases, selling): self.sendUpdate('requestJewelry', [ purchases, selling]) def sendRequestWeapon(self, purchases, selling): self.sendUpdate('requestWeapon', [ purchases, selling]) def sendRequestTattoo(self, purchases, selling): self.sendUpdate('requestTattoo', [ purchases, selling]) def sendRequestBarber(self, idx, color): self.sendUpdate('requestBarber', [ idx, color]) def makeTattooResponse(self, tattoo, zone, success): if self.storeMenuGUI and success: self.storeMenuGUI.tattooPurchase(zone, tattoo) def makeBarberResponse(self, uid, color, success): if self.storeMenuGUI and success: self.storeMenuGUI.barberPurchase(uid, color) def responseShipRepair(self, shipDoId): if self.pickShipGUI: self.pickShipGUI.updateShip(shipDoId) if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None self.confirmDialog = PDialog.PDialog(text = PLocalizer.ShipRepaired, style = OTPDialog.Acknowledge, command = self.handleRepairAcknowledge) def handleRepairAcknowledge(self, choice): if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None def makeSaleResponse(self, result): if result == RejectCode.OVERFLOW: localAvatar.guiMgr.createWarning(PLocalizer.TradeCannotHoldWarning, PiratesGuiGlobals.TextFG6) elif result == RejectCode.TIMEOUT: localAvatar.guiMgr.createWarning(PLocalizer.TradeTimeoutWarning, PiratesGuiGlobals.TextFG6) elif result == EconomyGlobals.RESULT_SUCCESS_UPGRADE_ROD: self.playQuestString(PLocalizer.FishmasterUpgradeRod, timeout = 10) localAvatar.guiMgr.createLevelUpText() localAvatar.guiMgr.levelUpLabel['text'] = PLocalizer.Minigame_Fishing_New_Rod localAvatar.guiMgr.levelUpIval.pause() localAvatar.guiMgr.levelUpIval.start() base.talkAssistant.receiveGameMessage(PLocalizer.Minigame_Fishing_New_Rod) elif result == 2: if self.storeMenuGUI: self.storeMenuGUI.updateBalance() self.storeMenuGUI.purchaseConfirmation() elif result != 1: localAvatar.guiMgr.createWarning(PLocalizer.TradeFailedWarning, PiratesGuiGlobals.TextFG6) else: localAvatar.guiMgr.combatTray.skillTray.updateSkillTrayAmounts() localAvatar.guiMgr.combatTray.tonicButton.getBestTonic() localAvatar.guiMgr.weaponPage.updateTonics() if self.storeMenuGUI: self.storeMenuGUI.updateBalance() self.storeMenuGUI.purchaseConfirmation() def startRepair(self, storeType): self.pickShipGUI = ShipShoppingPanel(PLocalizer.ShipRepair, doneCallback = self.confirmRepairShip, mode = 'repair') for shipId in base.localAvatar.getInventory().getShipDoIdList(): self.pickShipGUI.addOwnShip(shipId, self.confirmRepairShip) def confirmRepairShip(self, shipId = None): if not shipId: return None shipOV = self.cr.getOwnerView(shipId) if not shipOV: return None cost = ShipGlobals.getRepairCost(shipOV) r = Functor(self.sendRequestRepairShip, shipId) if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None self.confirmDialog = PDialog.PDialog(text = PLocalizer.RepairConfirmDialog % { 'gold': cost }, style = OTPDialog.YesNo, command = r) def sendRequestRepairShip(self, shipId, choice): shipOV = self.cr.getOwnerView(shipId) if not shipOV: return None cost = ShipGlobals.getRepairCost(shipOV) if choice == 1: inventory = base.localAvatar.getInventory() if inventory: if inventory.getGoldInPocket() < cost: base.localAvatar.guiMgr.createWarning(PLocalizer.NotEnoughMoneyWarning, PiratesGuiGlobals.TextFG6) return None self.sendUpdate('requestPurchaseRepair', [ shipId]) if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None def startSellShip(self, storeType): self.pickShipGUI = ShipShoppingPanel(PLocalizer.SellShip, doneCallback = self.confirmSellShip, mode = 'sell') def inventoryHere(inv): self._DistributedShopKeeper__invRequest = None if inv: for shipId in inv.getShipDoIdList(): self.pickShipGUI.addOwnShip(shipId, self.confirmSellShip) else: self.finishShopping() if self._DistributedShopKeeper__invRequest: DistributedInventoryBase.cancelGetInventory(self._DistributedShopKeeper__invRequest) self._DistributedShopKeeper__invRequest = DistributedInventoryBase.getInventory(localAvatar.getInventoryId(), inventoryHere) def confirmSellShip(self, shipId = None): if not shipId: return None shipOV = self.cr.getOwnerView(shipId) if not shipOV: return None if shipOV.state != 'Off': base.localAvatar.guiMgr.createWarning(PLocalizer.ShipNotInBottleWarning, PiratesGuiGlobals.TextFG6) return None modelType = ShipGlobals.getModelClass(shipOV.shipClass) cost = EconomyGlobals.getItemCost(modelType) / 2 r = Functor(self.doubleConfirmSellShip, shipId) if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None self.confirmDialog = PDialog.PDialog(text = PLocalizer.SellShipConfirmDialog % { 'gold': cost }, style = OTPDialog.YesNo, command = r) def doubleConfirmSellShip(self, shipId, choice): r = Functor(self.sendRequestSellShip, shipId) if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None if choice == 1: self.confirmDialog = PDialog.PDialog(text = PLocalizer.SellShipAreYouSureDialog, style = OTPDialog.YesNo, command = r) def sendRequestSellShip(self, shipId, choice): shipOV = self.cr.getOwnerView(shipId) if not shipOV: if self.pickShipGUI: self.pickShipGUI.hide() return None modelType = ShipGlobals.getModelClass(shipOV.shipClass) cost = EconomyGlobals.getItemCost(modelType) / 2 if choice == 1: inventory = base.localAvatar.getInventory() if inventory: if cost > 0 and inventory.getGoldInPocket() + cost > InventoryGlobals.GOLD_CAP: r = Functor(self.sendRequestSellShipGoldOverflow, shipId) if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None self.confirmDialog = PDialog.PDialog(text = PLocalizer.ExcessGoldLost, style = OTPDialog.YesNo, command = r) return None self.sendUpdate('requestSellShip', [ shipId]) if self.pickShipGUI: self.pickShipGUI.hide() self.finishShopping() def sendRequestSellShipGoldOverflow(self, shipId, choice): if self.pickShipGUI: self.pickShipGUI.hide() if choice == 1: self.sendUpdate('requestSellShip', [ shipId]) self.finishShopping() def startUpgrade(self, storeType): self.pickShipGUI = ShipShoppingPanel(PLocalizer.ShipOverhaul, doneCallback = self.openUpgradeShip, mode = 'upgrade') for shipId in base.localAvatar.getInventory().getShipDoIdList(): self.pickShipGUI.addOwnShip(shipId, self.openUpgradeShip, callbackCallback = self.returnAfterUpgrade) def returnAfterUpgrade(self, shipId = None): if self.pickShipGUI: self.pickShipGUI.show() if self.interactGUI: self.interactGUI.show() def leaveFromUpgradeSelect(self): if self.interactGUI: self.interactGUI.show() def openUpgradeShip(self, shipId = None, callback = None): if not shipId: self.leaveFromUpgradeSelect() return None shipOV = self.cr.getOwnerView(shipId) if not shipOV: self.leaveFromUpgradeSelect() return None localAvatar.guiMgr.openShipUpgrades(shipId, callback) self.pickShipGUI.hide() self.interactGUI.hide() def startOverhaul(self, storeType): self.pickShipGUI = ShipShoppingPanel(PLocalizer.ShipOverhaul, doneCallback = self.confirmOverhaulShip, mode = 'overhaul') for shipId in base.localAvatar.getInventory().getShipDoIdList(): self.pickShipGUI.addOwnShip(shipId, self.confirmOverhaulShip) def confirmOverhaulShip(self, shipId = None): if not shipId: return None shipOV = self.cr.getOwnerView(shipId) if not shipOV: return None if shipOV.state != 'Off': base.localAvatar.guiMgr.createWarning(PLocalizer.ShipNotInBottleWarning, PiratesGuiGlobals.TextFG6) return None shipClass = shipOV.getShipClass() cost = EconomyGlobals.getItemCost(shipClass) * EconomyGlobals.OVERHAUL_COST_PERCENTAGE if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None self.confirmDialog = PDialog.PDialog(text = PLocalizer.OverhaulConfirmDialog % { 'gold': cost }, style = OTPDialog.YesNo, command = self.sendRequestOverhaulShip, extraArgs = [ shipId]) def sendRequestOverhaulShip(self, choice, extraArgs): if self.pickShipGUI: self.pickShipGUI.hide() shipId = extraArgs[0] shipOV = self.cr.getOwnerView(shipId) if not shipOV: return None shipClass = shipOV.getShipClass() cost = EconomyGlobals.getItemCost(shipClass) * EconomyGlobals.OVERHAUL_COST_PERCENTAGE if choice == 1: inventory = base.localAvatar.getInventory() if inventory: if inventory.getGoldInPocket() < cost: base.localAvatar.guiMgr.createWarning(PLocalizer.NotEnoughMoneyWarning, PiratesGuiGlobals.TextFG6) return None self.sendUpdate('requestPurchaseOverhaul', [ shipId]) self.finishShopping() def startSellItems(self, storeType = None, push = False): base.localAvatar.guiMgr.setIgnoreAllKeys(False) base.localAvatar.guiMgr.setSeaChestAllowed(True) base.localAvatar.guiMgr.showInventoryBagPanel() base.localAvatar.guiMgr.setIgnoreAllKeys(True) base.localAvatar.guiMgr.setSeaChestAllowed(False) self.storePush = push self.accept('sellItem', self.sendRequestSellItem) if self.confirmDialog: self.confirmDialog.destroy() self.confirmDialog = None self.confirmDialog = InventorySellConfirm.InventorySellConfirm(base.localAvatar.guiMgr.inventoryUIManager, self.finishShopping, pos = (-1.0, 0, -0.20000000000000001)) def finishSelling(self): pass def sendRequestSellItem(self, item, amount = 1): if item[0] == InventoryType.ItemTypeClothing: amount = item[3] if item: self.sendUpdate('requestSellItem', [ item[0], item[1], item[2], amount]) def sendRequestStowaway(self, destUID): self.sendUpdate('requestStowaway', [ destUID])
#!/bin/bash if [ "$(id -u)" != "0" ] then echo "Please make sure you are running this installer with sudo or as root." 1>&2 exit 1 fi if type "xamarin-android-uninstall" > /dev/null 2>&1 then echo "Previous version detected, uninstalling..." xamarin-android-uninstall fi echo "Copying Xamarin.Android binaries..." cp -rf mono-android/ /opt/mono-android/ ln -s /opt/mono-android/lib/xamarin.android/xbuild/Xamarin/ /usr/lib/mono/xbuild/Xamarin ln -s /opt/mono-android/lib/xamarin.android/xbuild/Novell/ /usr/lib/mono/xbuild/Novell ln -s /opt/mono-android/lib/xamarin.android/xbuild-frameworks/MonoAndroid/ /usr/lib/mono/xbuild-frameworks/MonoAndroid echo "Adding terminal commands..." cp xamarin-android-uninstall /usr/bin/xamarin-android-uninstall chmod +x /usr/bin/xamarin-android-uninstall
<filename>docussandra-domain/src/main/java/com/pearson/docussandra/domain/Constants.java package com.pearson.docussandra.domain; public class Constants { public static final String NAME_MESSAGE = "is web-safe. It may contain only lower-case letters, numbers or hyphens ('-') or underscores ('_')"; public static final String NAME_PATTERN = "[a-z_\\-0-9]+"; }
import Koa from 'koa'; import cors from 'kcors'; import koaRouter from 'koa-router'; import {getCities, getCity, getStations, getStation, getSensors, getSensor, getReadings} from './db'; export function createServer(connection, dbName) { const router = koaRouter() .get('/rest/cities/', async(ctx) => { const cities = await getCities(connection, dbName); ctx.body = JSON.stringify({cities}); }) .get('/rest/cities/:id/', async(ctx) => { const city = await getCity(connection, dbName, ctx.params.id); city ? ctx.body = JSON.stringify(city) : ctx.status = 404; }) .get('/rest/stations/', async(ctx) => { const stations = await getStations(connection, dbName); ctx.body = JSON.stringify({stations}); }) .get('/rest/stations/:id/', async(ctx) => { const station = await getStation(connection, dbName, ctx.params.id); station ? ctx.body = JSON.stringify(station) : ctx.status = 404; }) .get('/rest/stations/:id/sensors/', async(ctx) => { const sensors = await getSensors(connection, dbName, ctx.params.id); ctx.body = JSON.stringify({sensors}); }) .get('/rest/sensors/:id/', async(ctx) => { const sensor = await getSensor(connection, dbName, ctx.params.id); sensor ? ctx.body = JSON.stringify(sensor) : ctx.status = 404; }) .get('/rest/sensors/:id/readings/', async(ctx) => { const readings = await getReadings(connection, dbName, ctx.params.id); ctx.body = JSON.stringify({readings}); }); const app = new Koa(); app.use(cors()); app.use(router.routes()); return app; }
#!/bin/bash pathogen="https://raw.githubusercontent.com/tpope/vim-pathogen/master/autoload/pathogen.vim" mkdir vim/.vim/autoload curl "$pathogen" > vim/.vim/autoload/pathogen.vim
<reponame>minuk8932/Algorithm_BaekJoon<filename>src/prefix_sum/Boj19584.java package prefix_sum; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; /** * * @author exponential-e * 백준 19584번: 난개발 * * @see https://www.acmicpc.net/problem/19584 * */ public class Boj19584 { private static PriorityQueue<Coordinate> primary = new PriorityQueue<>(); private static int[] range; private static long[] cost; private static int size; private static class Coordinate implements Comparable<Coordinate>{ int index; int height; public Coordinate(int index, int height) { this.index = index; this.height = height; } @Override public int compareTo(Coordinate c) { return this.height < c.height ? -1: 1; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); range = new int[N]; for(int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); st.nextToken(); primary.offer(new Coordinate(i, Integer.parseInt(st.nextToken()))); } levelArrangement(N); cost = new long[size + 2]; while(M-- > 0) { st = new StringTokenizer(br.readLine()); int u = Integer.parseInt(st.nextToken()) - 1; int v = Integer.parseInt(st.nextToken()) - 1; long c = Long.parseLong(st.nextToken()); makeRailRoad(range[u], range[v], c); // cost check and save } System.out.println(getMax()); } private static void levelArrangement(int n) { int h = Integer.MIN_VALUE; size = -1; while(!primary.isEmpty()) { // find same level & compression Coordinate current = primary.poll(); if(current.height != h){ h = current.height; size++; } range[current.index] = size; } } private static void makeRailRoad(int u, int v, long c) { cost[Math.min(u, v)] += c; // current cost[Math.max(u, v) + 1] -= c; // next } private static long getMax() { long result = cost[0]; for(int i = 1; i < cost.length; i++){ cost[i] += cost[i - 1]; // make accumulation by prefix sum result = Math.max(result, cost[i]); } return result; } }
import { Injectable } from '@angular/core'; import { ASWorkbook } from '../../model/asworkbook'; import { KeyPair } from '../../model/keypair'; @Injectable({ providedIn: 'root' }) export class ColumnComparisonService { mode: string; copyColumns(keyPair: KeyPair, currentWorkbooks: Array<ASWorkbook>, toHeader: string, fromHeader: string, genericMap: any) { const primaryWorkbook = this.getWorkbookByFile(currentWorkbooks, keyPair.primaryFile); const editArray = this.createEditArray(keyPair, currentWorkbooks, toHeader, fromHeader); this.createRowMap(genericMap, editArray, toHeader, fromHeader, primaryWorkbook); } createEditArray(keyPair: KeyPair, workbooks: Array<ASWorkbook>, toHeader: string, fromHeader: string) { const primaryWorkbook = this.getWorkbookByFile(workbooks, keyPair.primaryFile); const secondaryWorkbook = this.getWorkbookByFile(workbooks, keyPair.secondaryFile); const primaryRows = primaryWorkbook['rows']; const secondaryRows = secondaryWorkbook['rows']; const headerNameTo = toHeader.split(':')[1]; const headerNameFrom = fromHeader.split(':')[1]; const editArray = []; for (const primaryRowObject of primaryRows) { const primaryKeyValue = primaryRowObject[keyPair.primaryHeader]; // Get row with value regardless of whether or not it's a formula const value = secondaryRows.filter(rowObj => { if (!rowObj[keyPair.secondaryHeader]) { return false; } if (rowObj[keyPair.secondaryHeader].hasOwnProperty('result')) { return rowObj[keyPair.secondaryHeader]['result'] === primaryKeyValue; } else { return rowObj[keyPair.secondaryHeader] === primaryKeyValue; } }); // value is a row, and is actually just very poorly named if (!value.length) { continue; } const row = value[0]; row['mappedRow'] = primaryRowObject['rowNumber']; if (primaryRowObject[headerNameTo] !== null && primaryRowObject[headerNameTo].hasOwnProperty('result')) { row['mappedRowOldValue'] = primaryRowObject[headerNameTo]['result']; } else { row['mappedRowOldValue'] = primaryRowObject[headerNameTo]; } editArray.push(row); } return editArray; } createRowMap(genericMap: any, editArray: Array<any>, toHeader: string, fromHeader: string, primaryWorkbook: ASWorkbook) { // This is all still based on JavaScript's call by sharing. // I'm not entirely sure if I still use that or find a more // readable way to use the genericMap const headerNameTo = toHeader.split(':')[1]; const headerNameFrom = fromHeader.split(':')[1]; const columnNumber = primaryWorkbook['headerToColumnNumber'][headerNameTo]; genericMap[headerNameTo] = {}; editArray.forEach( rowObj => { let newValue: any; const newMappedRow = {}; if (!rowObj[headerNameFrom]) { return; } if (rowObj[headerNameFrom].hasOwnProperty('result')) { newValue = rowObj[headerNameFrom]['result']; } else { newValue = rowObj[headerNameFrom]; } if (this.mode === 'copy') { const sheetInt = primaryWorkbook.currentSheetInt; primaryWorkbook.workbook.getWorksheet(sheetInt + 1).getRow(rowObj.mappedRow).getCell(columnNumber).value = newValue; } newMappedRow['mappedRow'] = rowObj['rowNumber']; newMappedRow['rowNumber'] = rowObj['mappedRow']; newMappedRow['newValue'] = isNaN(newValue) ? newValue : Number(newValue); newMappedRow['oldValue'] = isNaN(rowObj['mappedRowOldValue']) ? rowObj['mappedRowOldValue'] : Number(rowObj['mappedRowOldValue']); genericMap[headerNameTo][rowObj['mappedRow']] = newMappedRow; }); } // Small wrapper to make this look less ugly getWorkbookByFile(workbooks: Array<ASWorkbook>, filename: string) { const wb = workbooks.filter(workbook => { return workbook.filename === filename; })[0]; return wb; } }
#!/bin/bash function usage() { echo "Usage: bash ./tools/install.sh" } function judge_ret() { if [[ $1 == 0 ]]; then echo "Passed: $2" echo "" else echo "Failed: $2" exit 5 fi } function install_third_part_lib() { # install cmake and gnu tools ${use_sudo} apt install -y build-essential cmake ${use_sudo} apt-get install -y pkg-config # install python3, numpy, pip3, required for Python API ${use_sudo} apt install -y python3-dev python3-numpy python3-pip pip3 install gluoncv --user pip3 install opencv-contrib-python --user pip3 install PyYAML --user pip3 install numpy --user pip3 install opencv-python --user # install Sphinx, required for Python API document. pip3 install sphinx sphinx-autobuild sphinx_rtd_theme recommonmark --user } function install_opencv3_from_source() { # build opencv3 from source if needed workspace=$(cd "$(dirname "$0")";pwd) cd "${workspace}" opencv_version=$(pkg-config opencv --modversion) opencv_version=${opencv_version:0:3} if [ "${opencv_version}" == "3.4" ];then echo "opencv3.4 already install.." else git clone https://github.com/opencv/opencv cd opencv git fetch && git checkout 3.4 mkdir build && cd build cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local .. make -j4 && ${use_sudo} make install cd ../.. && rm -rf opencv fi } function install_bmsdk() { python3 -c "import bmnetc" if [[ $? == 0 ]]; then echo "found bmnetc in python3" pip3 uninstall bmnetc -y echo "" fi pushd "${BMSDK_PATH}" pip3 install bmnetc/bmnetc-?.?.?-py2.py3-none-any.whl --user popd python3 -c "import bmnett" if [[ $? == 0 ]]; then echo "found bmnett in python3" pip3 uninstall bmnett -y echo "" fi pushd "${BMSDK_PATH}" pip3 install bmnett/bmnett-?.?.?-py2.py3-none-any.whl --user popd python3 -c "import bmnetm" if [[ $? == 0 ]]; then echo "found bmnetm in python3" pip3 uninstall bmnetm -y echo "" fi pushd "${BMSDK_PATH}" pip3 install bmnetm/bmnetm-?.?.?-py2.py3-none-any.whl --user popd python3 -c "import bmnetp" if [[ $? == 0 ]]; then echo "found bmnetp in python3" pip3 uninstall bmnetp -y echo "" fi pushd "${BMSDK_PATH}" pip3 install bmnetp/bmnetp-?.?.?-py2.py3-none-any.whl --user popd } BMSDK_PATH="$REL_TOP" if [ -z "$BMSDK_PATH" ]; then echo "Error: $BMSDK_PATH not exists!" echo "Please 'cd bmsdk_path && source envsetup.sh'" fi if [ ! -d "$BMSDK_PATH" ]; then echo "Error: $BMSDK_PATH not exists!" usage exit 3 fi if [[ ${BMSDK_PATH:0:1} != "/" ]]; then echo "Error: $BMSDK_PATH is not absolute path!" usage exit 4 fi echo "BMNNSDK_PATH = $BMSDK_PATH" who=`whoami` use_sudo=sudo if [ "${who}" == "root" ];then use_sudo= fi install_third_part_lib install_opencv3_from_source install_bmsdk
// Fall 2018 #include <iostream> #include <glm/ext.hpp> #include "Ray.hpp" #include "DEBUG.hpp" Ray::Ray(const glm::vec3 &org, const glm::vec3 &dir, bool is_inside) : org(org), dir(dir), inside_shape(is_inside) { } void Ray::setTransform(const glm::mat4& trans){ glm::vec3 point2 = org + dir; org = glm::vec3(trans * glm::vec4(org, 1)); dir = glm::vec3(trans * glm::vec4(point2, 1)) - org; } std::ostream& operator<<(std::ostream& out, const Ray& r) { out << "R[" << glm::to_string(r.org) << ", " << glm::to_string(r.dir) << ", "; for (int i = 0; i < 3; i++) { if (i > 0) out << ", "; // out << l.falloff[i]; } out << "]"; return out; }
#!/bin/sh if [ ! -e compiler.jar ]; then wget http://dl.google.com/closure-compiler/compiler-latest.zip unzip compiler-latest.zip compiler.jar rm compiler-latest.zip fi java -jar compiler.jar --js calendar.js jdate-class.js \ --js_output_file jdate.min.js \ --summary_detail_level 4 \ --compilation_level ADVANCED_OPTIMIZATIONS \ --output_wrapper "(function(){%output%}());"
<filename>app/src/main/java/com/cjy/flb/customView/OsiEditSpinnerText.java package com.cjy.flb.customView; import android.content.Context; import android.text.InputType; import android.text.SpannableString; import android.text.Spanned; import android.text.SpannedString; import android.text.style.AbsoluteSizeSpan; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.cjy.flb.R; import com.cjy.flb.utils.CommonAdapter; import com.cjy.flb.utils.ViewHolder; import java.util.Arrays; import java.util.List; /** * 自定义的EditText布局 * 用于登陆注册等 * Created by Administrator on 2015/11/26 0026. */ public class OsiEditSpinnerText extends RelativeLayout implements View.OnFocusChangeListener, CompoundButton.OnCheckedChangeListener { private Context context; private Spinner spiTitle; private EditText etContent; private ImageView imgLine; private CheckBox cbTail; private ImageView imgSearch; private Button btnClock; public OsiEditSpinnerText(Context context) { this(context, null, 0); } public OsiEditSpinnerText(Context context, AttributeSet attrs) { this(context, attrs, 0); } public OsiEditSpinnerText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; initView(); initListener(); } public void setSpinnerDatas(Context context, List<String> spinnerDatas) { SpinnerAdapter spinnerAdapter = new SpinnerAdapter(context, spinnerDatas, R.layout.edittext_spinner_osi_item); spiTitle.setAdapter(spinnerAdapter); } public class SpinnerAdapter extends CommonAdapter<String> { public SpinnerAdapter(Context context, List<String> mDatas, int itemLayoutId) { super(mDatas, context, itemLayoutId); } @Override public void convert(ViewHolder helper, String item, int positon) { helper.getTextView(R.id.tv_title_item).setText(mDatas.get(positon) + ""); } } /** * 初始化布局 */ public void initView() { View.inflate(getContext(), R.layout.edittext_spinner_osi, this); spiTitle = (Spinner) findViewById(R.id.spi_title); etContent = (EditText) findViewById(R.id.et_content); cbTail = (CheckBox) findViewById(R.id.cb_tail); imgLine = (ImageView) findViewById(R.id.img_focus); imgSearch = (ImageView) findViewById(R.id.imag_search); btnClock = (Button) findViewById(R.id.btn_clock); cbTail.setVisibility(View.GONE); } private void initListener() { etContent.setOnFocusChangeListener(this); cbTail.setOnCheckedChangeListener(this); } /** * 设置Title的值 * * @param title */ public void setTitle(String title) { // spiTitle.setText(title); } public void setImagViewVisib() { imgSearch.setVisibility(View.VISIBLE); } public void setEtContent(String content) { etContent.setText(content); } /** * 设置EditText的hint * * @param hint */ public void setContentHint(String hint) { // 新建一个可以添加属性的文本对象 SpannableString ss = new SpannableString(hint); // 新建一个属性对象,设置文字的大小 AbsoluteSizeSpan ass = new AbsoluteSizeSpan(14, true); // 附加属性到文本 ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置hint etContent.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失 // etContent.setHint(hint); } public String getTitleValue() { return spiTitle.getSelectedItem().toString(); } /** * 得到EditText输入的文字 * * @return */ public String getEditText() { return etContent.getText().toString().trim(); } public EditText getEtContentOnly() { return etContent; } /** * 初始化Tail的图标,同时设置输入框为密码隐藏状态 */ public void initTail() { cbTail.setVisibility(View.VISIBLE); etContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { imgLine.setBackgroundColor(context.getResources().getColor(R.color.btn_green_normal)); setLine(1); } else { imgLine.setBackgroundColor(context.getResources().getColor(R.color.et_Line)); setLine(1); } } /** * 设置底部的线条颜色大小变化 * * @param line */ private void setLine(int line) { LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imgLine.getLayoutParams(); layoutParams.height = line; imgLine.setLayoutParams(layoutParams); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { etContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL); } else { etContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } /** * 添加TvTitle隐藏 */ public void setTvTitleToGone() { // tvTitle.setVisibility(View.GONE); } /** * 显示错误 * * @param err */ public void showError(String err) { etContent.setError(err); } }
#!/usr/bin/env bash SCRIPT_ACTION=$1 ZALENIUM_DOCKER_IMAGE=$2 INTEGRATION_TO_TEST=$3 # In OSX install gtimeout through `brew install coreutils` function mtimeout() { if [ "$(uname -s)" = 'Darwin' ]; then gtimeout "$@" else timeout "$@" fi } # Actively waits for Zalenium to fully starts # you can copy paste this in your Jenkins scripts WaitZaleniumStarted() { DONE_MSG="Zalenium is now ready!" while ! docker logs zalenium | grep "${DONE_MSG}" >/dev/null; do echo -n '.' sleep 0.2 done } export -f WaitZaleniumStarted StartUp() { DOCKER_SELENIUM_IMAGE_COUNT=$(docker images | grep "elgalu/selenium" | wc -l) if [ ${DOCKER_SELENIUM_IMAGE_COUNT} -eq 0 ]; then echo "Seems that docker-selenium's image has not been downloaded yet, please run 'docker pull elgalu/selenium' first" exit 1 fi CONTAINERS=$(docker ps -a -f name=zalenium -q | wc -l) if [ ${CONTAINERS} -gt 0 ]; then echo "Removing exited docker-selenium containers..." docker rm -f $(docker ps -a -f name=zalenium -q) fi VIDEOS_FOLDER=${project.build.directory}/videos mkdir -p "${VIDEOS_FOLDER}" if [ "$INTEGRATION_TO_TEST" = sauceLabs ]; then echo "Starting Zalenium in docker with Sauce Labs..." SAUCE_USERNAME="${SAUCE_USERNAME:=abc}" SAUCE_ACCESS_KEY="${SAUCE_ACCESS_KEY:=abc}" if [ "$SAUCE_USERNAME" = abc ]; then echo "SAUCE_USERNAME environment variable is not set, cannot start Sauce Labs node, exiting..." exit 2 fi if [ "$SAUCE_ACCESS_KEY" = abc ]; then echo "SAUCE_ACCESS_KEY environment variable is not set, cannot start Sauce Labs node, exiting..." exit 3 fi docker run -d -ti --name zalenium -p 4444:4444 -p 5555:5555 \ -e HOST_UID="$(id -u)" \ -e HOST_GID="$(id -g)" \ -e SAUCE_USERNAME -e SAUCE_ACCESS_KEY \ -v ${VIDEOS_FOLDER}:/home/seluser/videos \ -v /var/run/docker.sock:/var/run/docker.sock \ ${ZALENIUM_DOCKER_IMAGE} start --sauceLabsEnabled true --startTunnel true fi if [ "$INTEGRATION_TO_TEST" = browserStack ]; then echo "Starting Zalenium in docker with BrowserStack..." BROWSER_STACK_USER="${BROWSER_STACK_USER:=abc}" BROWSER_STACK_KEY="${BROWSER_STACK_KEY:=abc}" if [ "$BROWSER_STACK_USER" = abc ]; then echo "BROWSER_STACK_USER environment variable is not set, cannot start Browser Stack node, exiting..." exit 4 fi if [ "$BROWSER_STACK_KEY" = abc ]; then echo "BROWSER_STACK_KEY environment variable is not set, cannot start Browser Stack node, exiting..." exit 5 fi docker run -d -ti --name zalenium -p 4444:4444 -p 5555:5555 \ -e HOST_UID="$(id -u)" \ -e HOST_GID="$(id -g)" \ -e BROWSER_STACK_USER -e BROWSER_STACK_KEY \ -v ${VIDEOS_FOLDER}:/home/seluser/videos \ -v /var/run/docker.sock:/var/run/docker.sock \ ${ZALENIUM_DOCKER_IMAGE} start --browserStackEnabled true --startTunnel true fi if [ "$INTEGRATION_TO_TEST" = testingBot ]; then echo "Starting Zalenium in docker with TestingBot..." TESTINGBOT_KEY="${TESTINGBOT_KEY:=abc}" TESTINGBOT_SECRET="${TESTINGBOT_SECRET:=abc}" if [ "$TESTINGBOT_KEY" = abc ]; then echo "TESTINGBOT_KEY environment variable is not set, cannot start TestingBot node, exiting..." exit 6 fi if [ "$TESTINGBOT_SECRET" = abc ]; then echo "TESTINGBOT_SECRET environment variable is not set, cannot start TestingBot node, exiting..." exit 7 fi docker run -d -ti --name zalenium -p 4444:4444 -p 5555:5555 \ -e HOST_UID="$(id -u)" \ -e HOST_GID="$(id -g)" \ -e TESTINGBOT_KEY -e TESTINGBOT_SECRET \ -v ${VIDEOS_FOLDER}:/home/seluser/videos \ -v /var/run/docker.sock:/var/run/docker.sock \ ${ZALENIUM_DOCKER_IMAGE} start --testingBotEnabled true --startTunnel true fi if ! mtimeout --foreground "2m" bash -c WaitZaleniumStarted; then echo "Zalenium failed to start after 2 minutes, failing..." exit 8 fi echo "Zalenium in docker started!" } ShutDown() { docker stop zalenium docker rm zalenium } case ${SCRIPT_ACTION} in start) StartUp ;; stop) ShutDown ;; esac
module Awsm class AutoScalingGroups def initialize @client = Aws::AutoScaling::Client.new @asg_map = {} load_auto_scaling_groups end def find_for( elb_name ) @asg_map[ elb_name ] end def load_auto_scaling_groups @client.describe_auto_scaling_groups.each_page do |p| p.auto_scaling_groups.map do |asg| asg.load_balancer_names.each do |elb_name| @asg_map[elb_name] = [] if @asg_map[elb_name].nil? @asg_map[elb_name] << { asg_name: asg.auto_scaling_group_name, instances: asg.instances.map{ |i| i.to_h }, instance_ids: asg.instances.map { |i| i.instance_id } } end end end end end end
<filename>utils/generateMarkdown.js // TODO: Create a function that returns a license badge based on which license is passed in // If there is no license, return an empty string function renderLicenseBadge(license) { } // TODO: Create a function that returns the license link // If there is no license, return an empty string function renderLicenseLink(license) { console.log("temp: "+license); // https://img.shields.io/static/v1?label=<LABEL>&message=<MESSAGE>&color=<COLOR> return "![license]( https://img.shields.io/static/v1?label=license&message="+license+"&color=green)"; //return"![license](https://img.shields.io/apm/l/vim-mode?style=plastic);" } // return the badge with the last commit time/ month function lastCommit(username,repo){ console.log("length: "+repo.length); console.log("repo: "+repo); if(repo.length==0 ){ return ""; } else{ return"![lastCommit](https://img.shields.io/github/last-commit/"+username+"/"+repo+")"; } } //github issues open function githubIssueOpened(username, repo){ if(repo.length==0 ){ return ""; } else{ return"![githubIssues](https://img.shields.io/github/issues/"+username+"/"+repo+")"; } } //github isses closed function githubUsseClosed(username,repo){ if(repo.length==0 ){ return ""; } else{ return"![githubIssuesClosed](https://img.shields.io/github/issues-closed/"+username+"/"+repo+")"; } } //github follower function follower(username){ return"![follower](https://img.shields.io/github/followers/"+username+"?style=social)"; } //github fork function fork(username,repo){ if(repo.length==0 ){ return ""; } else{ return"![githubIssuesClosed](https://img.shields.io/github/forks/"+username+"/"+repo+")"; } } // TODO: Create a function that returns the license section of README // If there is no license, return an empty string function renderLicenseSection(license) { } // TODO: Create a function to generate markdown for README function generateMarkdown(response) { //console.log("title: "+response.title); return ` ## project: ${response.title} ### Developer: ${response.username} <a name="description"/> </a> ## Description: ### Project Description: ${response.description} <br/> ## Table of Content<br/> * [Description](#description)<br/> * [Installation](#installation)<br/> * [Usage Information](#usageInfo)<br/> * [License](#license)<br/> * [Contribution](#contribution)<br/> * [Test](#test)<br/> * [Questions](#questions)<br/> ## License of the project: ${renderLicenseLink(response.license)}<br/> ${follower(response.username)}<br/> ${lastCommit(response.username,response.repo)}<br/> ${githubIssueOpened(response.username, response.repo)}<br/> ${githubUsseClosed(response.username,response.repo)}<br/> ${fork(response.username,response.repo)}<br/> <a name="installation"> </a> ## Installation: ### Project Installation: ${response.installation} <br/> <a name="usageInfo"/> </a> ## Usage: ### Project Usage Information: ${response.usageInfo} <br/> <a name="license"/> </a> ## License: ### Project License: ${response.license} <br/> <a name="contribution"/> </a> ## Contribution: ### Project Contribution: ${response.contribution} <br/> <a name="test"/> </a> ## Test: ### Project Test: ${response.test} <br/> <a name="questions"/> </a> ## Questions: ### Github Username: [${response.username}](https://github.com/${response.username}) <br/> <a name="email"/> </a> ### Developer Email: Email me if you have any questions: ${response.email} <br/> `; } module.exports = generateMarkdown;
#!/bin/bash # Copyright 2017 Google Inc. All Rights Reserved. # # 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. set -e source `dirname "$0"`/../install_helper_functions.sh SOURCE_DIR=$(readlink -f `dirname $0`) # Feature flags SERVER=true CLIENT=true DASHBOARDS=true # Variables for Server Configuration # explicit prometheus versions because its not available with apt-get # grafana will be latest version in apt-get PROMETHEUS_VERSION=prometheus-2.2.1.linux-amd64 NODE_EXPORTER_VERSION=node_exporter-0.15.2.linux-amd64 PUSHGATEWAY_VERSION=pushgateway-0.4.0.linux-amd64 PROMETHEUS_PORT=${PROMETHEUS_PORT:-9090} GRAFANA_PORT=${GRAFANA_PORT:-3000} GCE_CONFIG=false OVERWRITE=false # Variables for Client Configuration CLIENT_HOST="not specified" # Variables for Client and Server configuration GATEWAY_URL= if [[ $USE_SYSTEMD ]]; then AUTOSTART_SOURCE_DIR=${SOURCE_DIR}/systemd else AUTOSTART_SOURCE_DIR=${SOURCE_DIR}/upstart fi function show_usage() { cat <<EOF Usage: $0 [<CONTROL_OPTIONS>] [<CONFIG_OPTIONS>] Installation scripts specific to Prometheus monitoring support for Spinnaker. Currently this also requires installing the spinnaker-monitoring-daemon package, usually on each machine running a Spinnaker microservice. The daemon can be installed by running apt-get install spinnaker-monitoring-daemon. See the --client_only option for more information. <CONTROL_OPTIONS> specify which installations to perform. By default it will install client, server, and dashboards. When configuring a client, this script will make changes into the spinnaker-monitoring daemon's spinnaker-monitoring.yml configuration file and may install local components (such as prometheus node_extractor) When configuring a server, this script will install various prometheus infrastructure (prometheus, grafana, optiona gateway server) as well as start these services and configure upstart to restart them on a reboot. When configuring dashboards, this will install various canned dashboards into Grafana as well as the prometheus datasource being used. This requires access to port 3000, which will be present if you are installing server too. --no_client Dont install the client-side components for spinnaker. --client_only Only install the server-side components for spinnaker. --no_server Dont install the server-side components. --server_only Only install the server-side components. --no_dashboards Dont install the dashboard (and datasource) data. --dashboards_only Only install the dashboard (and datasource) data. These require connectivity to grafana (port 3000) <CONFIG_OPTIONS> are: --user=USER The grafana user name when installing dashboards. or --user USER --password=PASSWORD The grafana user password when installing or --password PASSWORD dashboards. --gateway=URL Configure prometheus to use the pushgateway. or --gateway URL If using the gateway, both client and server need this. Generally, the gateway is a last-resort config option. --gce Configure prometheus to discovery monitoring daemons in GCE VMs within this project and region. This is a server configuration only, though clients should use --client_host to expose the port externally. --overwrite Ovewrite existing dashboards if found. This is false by default. If true, existing dashboards will upgrade with any changes made, however will lose any local changes that might have been added to the previous installation. --client_host IP Configure the spinnaker-monitoring daemon to use or --client_host=IP the designated NIC. Clients are configured to use localhost by default. Specifying "" will enable all NICs. WARNING: Depending on your network and its firewall rules, this may make the daemon visible to any external host. Example usage: $0 Installs everything on the local machine. This is suitable when you are running a single-instance all-in-one spinnaker deployment with everything on it. $0 --no_client --gce Installs prometheus (and grafana) on the local machine, with canned dashboards, and configure prometheus to scan this project, in this region, for VMs that are running the spinnaker-monitoring daemon (and/or node_exporter) and monitor those. This assumes that you have run the client-side install where the daemon is. $0 --client_only Installs and configures the client side components. You should already have installed the spinnaker-monitoring-daemon package so that it can configure the spinnaker-monitoring.yml file. If not, then you will have to edit it manually later, or re-run this install with --client_only. EOF } GRAFANA_USER=${GRAFANA_USER:-admin} GRAFANA_PASSWORD=${GRAFANA_PASSWORD:-admin} # We are going to use this file as a template for the prometheus.yml # file we give to configure Prometheus. # We will add additional scrape_configs for Spinnaker itself depending # on which deployment strategy we take. PROMETHEUS_YML_TEMPLATE=$(cat<<EOF global: scrape_interval: 15s evaluation_interval: 15s external_labels: monitor: "spinnaker-monitor" rule_files: # - "first.rules" scrape_configs: - job_name: 'prometheus' static_configs: - targets: ['localhost:9090'] EOF ) # This is the scrape_config for the spinnaker-daemon. # it is incomplete because it lacks the protocol and endpoint to use # that will vary depending on how we configure it later. SPINNAKER_YML_CONFIG=$(cat<<EOF - job_name: 'spinnaker' metrics_path: '/prometheus_metrics' honor_labels: true EOF ) # This is the scrape_config for the prometheus node_extractor. # it is incomplete because it lacks the protocol and endpoint to use # that will vary depending on how we configure it later. NODE_EXTRACTOR_YML_CONFIG=$(cat<<EOF - job_name: 'node' EOF ) function process_args() { while [[ $# > 0 ]]; do local key="$1" shift case $key in --help) show_usage exit 0 ;; --user=*) GRAFANA_USER="${key#*=}" # See --user ;; --user) GRAFANA_USER="$1" # Only used for dashboards (and source) shift ;; --password=*) GRAFANA_PASSWORD="${key#*=}" # See --user ;; --password) GRAFANA_PASSWORD="$1" # Only used for dashboards (and source) shift ;; --gateway=*) GATEWAY_URL="${key#*=}" # See --gateway ;; --gateway) GATEWAY_URL="$1" # Used both client and server side shift ;; --gce) GCE_CONFIG=true # Only used when installing the server side ;; --client_host=*) CLIENT_HOST="${key#*=}" # See --client_host ;; --client_host) CLIENT_HOST="$1" # host in client side spinnaker-monitoring.yml shift ;; --server_only) CLIENT=false DASHBOARDS=false ;; --no_server) SERVER=false ;; --client_only) SERVER=false DASHBOARDS=false ;; --no_client) CLIENT=false ;; --dashboards_only) SERVER=false CLIENT=false ;; --overwrite) OVERWRITE=true ;; --no_dashboards) DASHBOARDS=false ;; *) show_usage >&2 echo "Unrecognized argument '$key'." exit -1 esac done } function extract_version_number() { echo "$1" | sed 's/^[^0-9]\+\([0-9]\+\.[0-9]\+\.[0-9]\+\).*/v\1/' } function configure_gce_prometheus() { local path="$1" local project=$(gce_project_or_empty) local zone_list=$(gce_zone_list_or_empty) if [[ -z $project ]]; then >&2 echo "You are not on GCE so must manually configure $path" return fi # # We are going to configure both spinnaker and node_extractor # such that there is an entry for every zone. # We'll build both these lists in one loop # for each zone in our region (and project). # spinnaker_zone_configs=" gce_sd_configs:" node_zone_configs=" gce_sd_configs:" for zone in $zone_list do # Note that the indent of the data block is intentional local spinnaker_entry=$(cat<<EOF - project: '$project' zone: '$zone' port: 8008 EOF ) # Note that the indent of the data block is intentional local node_entry=$(cat<<EOF - project: '$project' zone: '$zone' port: 9100 EOF ) spinnaker_zone_configs="$spinnaker_zone_configs $spinnaker_entry" node_zone_configs="$node_zone_configs $node_entry" done # # Now put it all together to generate the file. # cat <<EOF > $path $PROMETHEUS_YML_TEMPLATE $SPINNAKER_YML_CONFIG $spinnaker_zone_configs $NODE_EXTRACTOR_YML_CONFIG $node_zone_configs EOF chown spinnaker:spinnaker $path >& /dev/null || true chmod 644 $path } function configure_gateway_prometheus() { local path="$1" gateway_configs=$(cat<<EOF - job_name: 'pushgateway' honor_labels: true static_configs: - targets: ['localhost:9091'] EOF ) echo "$PROMETHEUS_YML_TEMPLATE $gateway_configs" > $path chown spinnaker:spinnaker $path >& /dev/null || true chmod 644 $path } function configure_local_prometheus() { local path="$1" local spinnaker_target=$(cat<<EOF static_configs: - targets: ['localhost:8008'] EOF ) local node_target=$(cat<<EOF static_configs: - targets: ['localhost:9100'] EOF ) cat <<EOF > "$path" $PROMETHEUS_YML_TEMPLATE $SPINNAKER_YML_CONFIG $spinnaker_target $NODE_EXTRACTOR_YML_CONFIG $node_target EOF chown spinnaker:spinnaker $path >& /dev/null || true chmod 644 $path } function install_prometheus() { local old_conf_file_path="" local old_data_path="" local autostart_config_path=$(determine_autostart_config_path "prometheus") if [[ -f $autostart_config_path ]]; then old_data_path=$(grep storage.tsdb.path $autostart_config_path \ | sed "s/.*--storage.tsdb.path *\([^ ]*\).*/\1/") old_conf_file_path=$(grep config.file $autostart_config_path \ | sed "s/.*-config.file *\([^ ]*\).*/\1/") fi curl -s -S -L -o /tmp/prometheus.gz \ https://github.com/prometheus/prometheus/releases/download/$(extract_version_number $PROMETHEUS_VERSION)/${PROMETHEUS_VERSION}.tar.gz local version_dir=/opt/$PROMETHEUS_VERSION mkdir -p $version_dir tar xzf /tmp/prometheus.gz -C $(dirname $version_dir) rm -f /opt/prometheus ln -fs $version_dir /opt/prometheus rm /tmp/prometheus.gz cp "$AUTOSTART_SOURCE_DIR/$(basename $autostart_config_path)" $autostart_config_path if [[ "$old_data_path" != "" ]]; then echo "Configuring existing non-standard datastore $old_data_path" sed "s/\/opt\/prometheus-data/${old_data_path//\//\\\/}/" \ -i $autostart_config_path fi if [[ "$GCE_CONFIG" == "true" ]]; then sed "s/spinnaker-prometheus\.yml/gce-prometheus\.yml/" \ -i $autostart_config_path configure_gce_prometheus "$version_dir/gce-prometheus.yml" elif [[ ! -z $GATEWAY_URL ]]; then sed "s/spinnaker-prometheus\.yml/pushgateway-prometheus\.yml/" \ -i $autostart_config_path configure_gateway_prometheus "$version_dir/pushgateway-prometheus.yml" else sed "s/spinnaker-prometheus\.yml/local-prometheus\.yml/" \ -i $autostart_config_path configure_local_prometheus "$version_dir/local-prometheus.yml" fi # Keep old configuration file as backup if it contains # customizations that may need to be re-added. if [[ "$old_conf_file_path" != "" ]]; then local old_backup="/opt/prometheus/$(basename $old_conf_file_path).old" if [[ ! -f $old_backup ]]; then echo "Copying $old_conf_file_path to $old_backup" cp $old_conf_file_path $old_backup else echo "Copying $old_backup already exists." fi fi restart_service "prometheus" } function install_node_exporter() { curl -s -S -L -o /tmp/node_exporter.gz \ https://github.com/prometheus/node_exporter/releases/download/$(extract_version_number $NODE_EXPORTER_VERSION)/${NODE_EXPORTER_VERSION}.tar.gz local node_dir=/opt/${NODE_EXPORTER_VERSION} mkdir -p $node_dir tar xzf /tmp/node_exporter.gz -C $(dirname $node_dir) rm -f /usr/bin/node_exporter ln -fs $node_dir /opt/node_exporter ln -fs $node_dir/node_exporter /usr/bin/node_exporter rm /tmp/node_exporter.gz local autostart_config_path=$(determine_autostart_config_path "node_exporter") cp $AUTOSTART_SOURCE_DIR/$(basename $autostart_config_path) $autostart_config_path restart_service "node_exporter" } function install_push_gateway() { curl -s -S -L -o /tmp/pushgateway.gz \ https://github.com/prometheus/pushgateway/releases/download/$(extract_version_number $PUSHGATEWAY_VERSION)/${PUSHGATEWAY_VERSION}.tar.gz local gateway_dir=/opt/$PUSH_GATEWAY_VERSION mkdir -p $gateway_dir tar xzf /tmp/pushgateway.gz -C $(dirname $gateway_dir) rm -f /usr/bin/pushgateway ln -fs $gateway_dir/pushgateway /usr/bin/pushgateway rm /tmp/pushgateway.gz local autostart_config_path=$(determine_autostart_config_path "pushgateway") cp $AUTOSTART_SOURCE_DIR/$(basename $autostart_config_path) $autostart_config_path restart_service "pushgateway" } function install_grafana() { echo "deb https://packagecloud.io/grafana/stable/debian/ jessie main" \ > /etc/apt/sources.list.d/grafana.list curl -s -S https://packagecloud.io/gpg.key | sudo apt-key add - sudo apt-get update -y sudo apt-get install grafana -y --force-yes update-rc.d grafana-server defaults sed -e "s/^;admin_user *=.*/admin_user = $GRAFANA_USER/" \ -e "s/^;admin_password *=.*/admin_password = ${GRAFANA_PASSWORD//\\//\\\/}/" \ -i /etc/grafana/grafana.ini restart_service "grafana-server" } function add_grafana_userdata() { echo "Adding datasource" PAYLOAD="{'name':'Spinnaker','type':'prometheus','url':'http://localhost:${PROMETHEUS_PORT}','access':'direct','isDefault':true}" curl -s -S -u "$GRAFANA_USER:$GRAFANA_PASSWORD" \ http://localhost:${GRAFANA_PORT}/api/datasources \ -H "Content-Type: application/json" \ -X POST \ -d "${PAYLOAD//\'/\"}" for dashboard in ${SOURCE_DIR}/*-dashboard.json; do echo "Installing $(basename $dashboard)" x=$(sed -e "/\"__inputs\"/,/],/d" \ -e "/\"__requires\"/,/],/d" \ -e "s/\${DS_SPINNAKER\}/Spinnaker/g" < "$dashboard") temp_file=$(mktemp) echo "{ \"dashboard\": $x, \"overwrite\": $OVERWRITE }" > $temp_file curl -s -S -u "$GRAFANA_USER:$GRAFANA_PASSWORD" \ http://localhost:${GRAFANA_PORT}/api/dashboards/import \ -H "Content-Type: application/json" \ -X POST \ -d @${temp_file} rm -f $temp_file done } function enable_spinnaker_monitoring_config() { local config_path=$(find_config_path) if [[ -f "$config_path" ]]; then echo "Enabling prometheus in $config_path" chmod 600 "$config_path" sed -e "s/^\( *\)#\( *- prometheus$\)/\1\2/" -i "$config_path" if [[ "$CLIENT_HOST" != "not specified" ]]; then sed -e "s/\(^ *host:\).*/\1 $CLIENT_HOST/" -i "$config_path" fi if [[ $GATEWAY_URL != "" ]]; then escaped_url=${GATEWAY_URL//\//\\\/} sed -e "s/^\( *push_gateway:\)/\1 $escaped_url/" -i "$config_path" fi else echo "" echo "You will need to edit $config_path" echo " and add prometheus as a monitor_store before running spinnaker-monitoring" if [[ $GATEWAY_URL != "" ]]; then echo " and also set prometheus to $GATEWAY_URL" fi fi } process_args "$@" if $CLIENT || $SERVER; then if [[ $(id -u) -ne 0 ]]; then >&2 echo "This command must be run as root. Try again with sudo." exit -1 fi fi if $SERVER; then if [[ -z $GATEWAY_URL ]]; then install_node_exporter else install_push_gateway fi install_prometheus install_grafana fi if $DASHBOARDS; then TRIES=0 until nc -z localhost $GRAFANA_PORT || [[ $TRIES -gt 5 ]]; do sleep 1 let TRIES+=1 done add_grafana_userdata fi if $CLIENT; then # 20170226 # Moved this from the daemon requirements for consistency with datadog. sudo apt-get update -y sudo apt-get install python-pip -y --force-yes pip install -r "$SOURCE_DIR/requirements.txt" enable_spinnaker_monitoring_config fi
package contractor import ( "github.com/pachisi456/Sia/build" "github.com/pachisi456/Sia/modules" "github.com/pachisi456/Sia/types" ) // Constants related to contract formation parameters. var ( // consecutiveRenewalsBeforeReplacement is the number of times a contract // attempt to be renewed before it is marked as !goodForRenew. consecutiveRenewalsBeforeReplacement = build.Select(build.Var{ Dev: types.BlockHeight(12), Standard: types.BlockHeight(12), // ~2h Testing: types.BlockHeight(12), }).(types.BlockHeight) // fileContractMinimumFunding is the lowest percentage of an allowace (on a // per-contract basis) that is allowed to go into funding a contract. If the // allowance is 100 SC per contract (5,000 SC total for 50 contracts, or // 2,000 SC total for 20 contracts, etc.), then the minimum amount of funds // that a contract would be allowed to have is fileContractMinimumFunding * // 100SC. fileContractMinimumFunding = float64(0.15) // minContractFundRenewalThreshold defines the ratio of remaining funds to // total contract cost below which the contractor will prematurely renew a // contract. minContractFundRenewalThreshold = float64(0.03) // 3% // randomHostsBufferForScore defines how many extra hosts are queried when trying // to figure out an appropriate minimum score for the hosts that we have. randomHostsBufferForScore = build.Select(build.Var{ Dev: 2, Standard: 10, Testing: 1, }).(int) ) // Constants related to the safety values for when the contractor is forming // contracts. var ( maxCollateral = types.SiacoinPrecision.Mul64(1e3) // 1k SC maxDownloadPrice = maxStoragePrice.Mul64(3 * 4320) maxStoragePrice = build.Select(build.Var{ Dev: types.SiacoinPrecision.Mul64(30e4).Div(modules.BlockBytesPerMonthTerabyte), // 1 order of magnitude greater Standard: types.SiacoinPrecision.Mul64(30e3).Div(modules.BlockBytesPerMonthTerabyte), // 30k SC / TB / Month Testing: types.SiacoinPrecision.Mul64(30e5).Div(modules.BlockBytesPerMonthTerabyte), // 2 orders of magnitude greater }).(types.Currency) maxUploadPrice = build.Select(build.Var{ Dev: maxStoragePrice.Mul64(30 * 4320), // 1 order of magnitude greater Standard: maxStoragePrice.Mul64(3 * 4320), // 3 months of storage Testing: maxStoragePrice.Mul64(300 * 4320), // 2 orders of magnitude greater }).(types.Currency) // scoreLeeway defines the factor by which a host can miss the goal score // for a set of hosts. To determine the goal score, a new set of hosts is // queried from the hostdb and the lowest scoring among them is selected. // That score is then divided by scoreLeeway to get the minimum score that a // host is allowed to have before being marked as !GoodForUpload. scoreLeeway = types.NewCurrency64(100) )
<filename>lib/bosh_release_diff/deployment_manifest/file_reader.rb require "bosh_release_diff/error" require "bosh_release_diff/deployment_manifest/deployment_manifest" module BoshReleaseDiff::DeploymentManifest class FileReader def initialize(file_path, logger) @file_path = File.expand_path(file_path, Dir.pwd) @logger = logger end def read begin hash = YAML.load_file(@file_path) rescue Exception => e raise BoshReleaseDiff::Error, e.inspect end @logger.debug("Building deployment manifest from #{hash.inspect}") DeploymentManifest.new(hash, File.basename(@file_path)) end end end
const path = require('path'); const merge = require('webpack-merge'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const baseConfig = require('./base.config.js'); module.exports = merge(baseConfig, { output: { path: path.resolve(__dirname, '../../dist'), }, plugins: [ new CopyWebpackPlugin({ patterns: [ { from: 'tests/test.html'}, { from: 'node_modules/mocha', to: 'test-resources/mocha' }, { from: 'node_modules/chai', to: 'test-resources/chai' }, ] }) ], entry: { 'tc': 'src/index.js', 'tests': 'tests/source-map-wrapped.js', }, });
#!/bin/bash # Copyright © 2021 Alibaba Group Holding 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. # Open ipvs modprobe -- ip_vs modprobe -- ip_vs_rr modprobe -- ip_vs_wrr modprobe -- ip_vs_sh # 1.20 need ope br_netfilter modprobe -- br_netfilter modprobe -- bridge version_ge(){ test "$(echo "$@" | tr ' ' '\n' | sort -rV | head -n 1)" == "$1" } disable_selinux(){ if [ -s /etc/selinux/config ] && grep 'SELINUX=enforcing' /etc/selinux/config; then sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config setenforce 0 fi } kernel_version=$(uname -r | cut -d- -f1) if version_ge "${kernel_version}" 4.19; then modprobe -- nf_conntrack else modprobe -- nf_conntrack_ipv4 fi cat <<EOF > /etc/sysctl.d/k8s.conf net.bridge.bridge-nf-call-ip6tables = 1 net.bridge.bridge-nf-call-iptables = 1 net.ipv4.conf.all.rp_filter=0 EOF sysctl --system sysctl -w net.ipv4.ip_forward=1 # systemctl stop firewalld && systemctl disable firewalld swapoff -a disable_selinux exit 0
package com.appsrox.my_notes.model; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.appsrox.my_notes.common.Util; public class Attachment extends AbstractModel { public static final String TABLE_NAME = "attachment"; public static final String COL_ID = AbstractModel.COL_ID; public static final String COL_NOTEID = "note_id"; public static final String COL_NAME = "name"; public static final String COL_URI = "uri"; static String getSql() { return Util.concat("CREATE TABLE ", TABLE_NAME, " (", COL_ID, " INTEGER PRIMARY KEY AUTOINCREMENT, ", COL_NOTEID, " INTEGER, ", COL_NAME, " TEXT, ", COL_URI, " TEXT", ");"); } long save(SQLiteDatabase db) { ContentValues cv = new ContentValues(); cv.put(COL_NOTEID, noteId); cv.put(COL_NAME, name==null ? "" : name); cv.put(COL_URI, uri==null ? "" : uri); return db.insert(TABLE_NAME, null, cv); } boolean update(SQLiteDatabase db) { ContentValues cv = new ContentValues(); cv.put(COL_ID, id); if (noteId > 0) cv.put(COL_NOTEID, noteId); if (name != null) cv.put(COL_NAME, name); if (uri != null) cv.put(COL_URI, uri); return db.update(TABLE_NAME, cv, COL_ID+" = ?", new String[]{String.valueOf(id)}) == 1 ? true : false; } public boolean load(SQLiteDatabase db) { Cursor cursor = db.query(TABLE_NAME, null, COL_ID+" = ?", new String[]{String.valueOf(id)}, null, null, null); try { if (cursor.moveToFirst()) { reset(); id = cursor.getLong(cursor.getColumnIndex(COL_ID)); noteId = cursor.getLong(cursor.getColumnIndex(COL_NOTEID)); name = cursor.getString(cursor.getColumnIndex(COL_NAME)); uri = cursor.getString(cursor.getColumnIndex(COL_URI)); return true; } return false; } finally { cursor.close(); } } public static Cursor list(SQLiteDatabase db, String noteId) { if (noteId != null) return db.query(TABLE_NAME, null, COL_NOTEID+" = ?", new String[]{noteId}, null, null, COL_ID+" ASC"); else return null; } public boolean delete(SQLiteDatabase db) { return db.delete(TABLE_NAME, COL_ID+" = ?", new String[]{String.valueOf(id)}) == 1 ? true : false; } //-------------------------------------------------------------------------- private long noteId; private String name; private String uri; public void reset() { id = 0; noteId = 0; name = null; uri = null; } public long getNoteId() { return noteId; } public void setNoteId(long noteId) { this.noteId = noteId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Attachment() {} public Attachment(long id) { this.id = id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || (obj.getClass() != this.getClass())) return false; return id == ((Attachment)obj).id; } @Override public int hashCode() { return 1; } }
#!/bin/sh # If we're cross compiling use that path for nm if [ "$CROSS_COMPILE_ARCH" != "" ]; then NM=$ALT_COMPILER_PATH/nm else NM=nm fi $NM -Uj $* | awk ' { if ($3 ~ /^_ZTV/ || $3 ~ /^gHotSpotVM/) print "\t" $3 } '
<filename>apps/system/js/external_storage_monitor.js 'use strict'; /* global Notification, MozActivity */ (function(exports) { /** * ExternalStorageMonitor listenes to external storage(should be * insterted/removed SD card slot) for the volume chagne event. * According to the status activity, we use regular expression to indentify * storage actions. * @class ExternalStorageMonitor */ function ExternalStorageMonitor() { // We will monitor external storage. And the external storage should be // removable. var storages = navigator.getDeviceStorages('sdcard'); // If there are two storages, the name of first storage name is 'sdcard'. // But it's an internal storage. The storage name is mapping to // a hard code name. Because name of some external storages are different. // Such as, Flame: 'external', Helix: 'extsdcard'. // XXX: Bug 1033952 - Implement "isRemovable" API for device storage // Once "isRemovable" attribute is ready, we can remove the dirty check here if (storages.length > 1) { storages.some(function(storage) { if (storage.storageName != 'sdcard' && storage.canBeMounted) { this._storage = storage; } }.bind(this)); } else { this._storage = storages[0]; } } const RESET_JUST_ENTER_IDLE_STATUS_MILLISECONDS = 1000; ExternalStorageMonitor.prototype = { /** * ums.mode setting value when the automounter is disabled. * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ statusStack: [], /** * Volume state "Init". * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Init: -1, /** * Volume state "NoMedia"(Removed). * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ NoMedia: 0, /** * Volume state "Idle"(Unmounted). * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Idle: 1, /** * Volume state "Pending". * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Pending: 2, /** * Volume state "Checking". * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Checking: 3, /** * Volume state "Mounted". * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Mounted: 4, /** * Volume state "Unmounting". * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Unmounting: 5, /** * Volume state "Formatting". * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Formatting: 6, /** * Volume state "Shared"(Unmounted in shared mode). * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ Shared: 7, /** * Volume state "Shared-Mounted". * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ // It's defined in android storage void. But never see the event comes. // Shared-Mounted: 8, /** * Volume RegExp "actionRecognised". * If a user inserted formatted and raedable SD card, * Volume State Machine will run in this flow. * State flow: * NoMedia --> Pending --> Idle(Unmounted) --> Checking --> Mounted * * Enumerate value: * 0 --> 2 --> 1 --> 3 --> 4 * * @memberof ExternalStorageMonitor.prototype * @type {RegExp} */ actionRecognised: /02134$/, /** * Volume RegExp "actionUnrecognised". * If a user inserted an unformatted or can not readable format SD card, * Volume State Machine will run in this flow. * State flow: * NoMedia --> Idle(Unmounted) --> Checking --> Idle(Unmounted) * * Enumerate value: * 0 --> 1 --> 3 --> 1 * * @memberof ExternalStorageMonitor.prototype * @type {RegExp} */ actionUnrecognised: /0131$/, /** * Volume RegExp "actionRemoved". * If a user unmount SD card successfully, * Volume State Machine will run in this flow. * State flow: * Mounted --> Unmounting --> Idle(Unmounted) --> NoMedia * * Enumerate value: * 4 --> 5 --> 1 --> 0 * * @memberof ExternalStorageMonitor.prototype * @type {RegExp} */ actionRemoved: /4510$/, /** * A flag to identify the storage status has been into Idle(Unmounted). * We will use the flag to distinguish removal SD card manually or not. * * @memberof ExternalStorageMonitor.prototype * @type {Boolean} */ justEnterIdleLessThanOneSecond: null, /** * An integer with the ID value of the timer that is set. * We will clean the timer if create a new timer. * * @memberof ExternalStorageMonitor.prototype * @type {Integer} */ resetJustEnterIdleFlagTimer: null, /** * An variable for maintain the storage status. * * @memberof ExternalStorageMonitor.prototype * @type {Object} */ _storage: null, /** * Listene to storage 'change' event. * @memberof ExternalStorageMonitor.prototype * @private */ start: function() { if (!this._storage) { return; } this._storage.addEventListener('storage-state-change', this); var msg = '[ExternalStorageMonitor] initEvent(): ' + 'monitor external storage name = ' + this._storage.storageName + ', canBeMounted = ' + this._storage.canBeMounted; this.debug(msg); }, /** * Push latest storage status in statusStack * @memberof ExternalStorageMonitor.prototype * @param {string} str The value we are pushing in stack. The string is * mapping to the storage status. And the status are defined in * ExternalStorageMonitor property. */ pushStatus: function(status) { this.statusStack.push(this[status]); }, /** * The function keep the latest storage status. And put the status be the * the first element in a new array. * @memberof ExternalStorageMonitor.prototype */ clearStatus: function() { this.statusStack = [this.statusStack.pop()]; var actionsFlags = this.statusStack.join(''); var msg = '[ExternalStorageMonitor] clearStatus(): ' + 'actionsFlags = ' + actionsFlags; this.debug(msg); }, /** * Trigger a timer to set flag 'justEnterIdleLessThanOneSecond' be true. * We will use the flag to speculate the action of storage removal manually * or not. * @memberof ExternalStorageMonitor.prototype * @param {} str The value we are pushing in stack. */ enableEnterIdleStateTimer: function() { this.justEnterIdleLessThanOneSecond = true; if (this.resetJustEnterIdleFlagTimer) { clearTimeout(this.resetJustEnterIdleFlagTimer); } // reset the flag after 1000 milliseconds this.resetJustEnterIdleFlagTimer = setTimeout(function() { this.justEnterIdleLessThanOneSecond = false; }.bind(this), RESET_JUST_ENTER_IDLE_STATUS_MILLISECONDS); }, /** * Recognise storage actions. * @memberof ExternalStorageMonitor.prototype * @private */ recogniseStorageActions: function() { var actionsFlags = this.statusStack.join(''); var msg = '[ExternalStorageMonitor] recogniseStorageActions(): ' + 'actionsFlags = ' + actionsFlags; this.debug(msg); if (actionsFlags.match(this.actionRecognised)) { this.clearStatus(); // notify SD card detected this.createMessage('detected-recognised'); } else if (actionsFlags.match(this.actionUnrecognised)) { this.clearStatus(); // notify unknown SD card detected this.createMessage('detected-unrecognised'); } else if (actionsFlags.match(this.actionRemoved)) { this.clearStatus(); if (!this.justEnterIdleLessThanOneSecond) { // notify SD card safely removed this.createMessage('normally-removed'); } else { // notify SD card unexpectedly removed this.createMessage('unexpectedly-removed'); } } }, /** * Create message for the storage activity. * @memberof ExternalStorageMonitor.prototype * @param {action} str The string we figure out the storage action */ createMessage: function(action) { var msg = '[ExternalStorageMonitor] createMessage(): action = ' + action; this.debug(msg); var _ = navigator.mozL10n.get; // Prepare message for fire notification. var title, body; switch (action) { case 'detected-recognised': this.getTotalSpace(function(totalSpace) { title = _('sdcard-detected-title'); body = _('sdcard-total-size-body', { size: totalSpace.size, unit: totalSpace.unit }); this.fireNotification(title, body, true); }.bind(this)); break; case 'detected-unrecognised': title = _('sdcard-detected-title'); body = _('sdcard-unknown-size-tap-to-format-body'); this.fireNotification(title, body, true); break; case 'normally-removed': title = _('sdcard-removed-title'); body = _('sdcard-removed-eject-successfully'); this.fireNotification(title, body); break; case 'unexpectedly-removed': title = _('sdcard-removed-title'); body = _('sdcard-removed-not-eject-properly'); this.fireNotification(title, body); break; } }, /** * Notify user what the storage is activate. * @memberof ExternalStorageMonitor.prototype * @param {title} str The string we show on the title of notification * @param {body} str The string we show on the body of notification */ fireNotification: function(title, body, openSettings) { var iconUrl = window.location.origin + '/style/storage_status/' + 'notification_sd_card.png'; // We always use tag "sdcard-storage-status" to manage these notifications var notificationId = 'sdcard-storage-status'; var options = { body: body, icon: iconUrl, tag: notificationId }; var notification = new Notification(title, options); // set onclick handler for the notification notification.onclick = this.notificationHandler.bind(this, notification, openSettings); }, /** * Handle notification while it be triggered 'onclick' event. * @memberof ExternalStorageMonitor.prototype * @private */ notificationHandler: function(notification, openSettings) { // close the notification notification.close(); // request configure activity for settings media storage if (!openSettings) { return; } var activityOptions = { name: 'configure', data: { target: 'device', section: 'mediaStorage' } }; var activityReq = new MozActivity(activityOptions); activityReq.onerror = function(e) { var msg = '[ExternalStorageMonitor] configure activity error:' + activityReq.error.name; this.debug(msg); }.bind(this); activityReq.onsuccess = function(e) { var msg = '[ExternalStorageMonitor] configure activity onsuccess'; this.debug(msg); }.bind(this); }, /** * General event handler interface. * @memberof ExternalStorageMonitor.prototype * @param {DOMEvent} evt The event. */ handleEvent: function(e) { switch (e.type) { case 'storage-state-change': var storageStatus = e.reason; var msg = '[ExternalStorageMonitor] received ' + '"storage-state-change" event ' + 'storageStatus = ' + storageStatus; this.debug(msg); this.pushStatus(storageStatus); // checking 'Idle' state for set flag on if (storageStatus === 'Idle') { this.enableEnterIdleStateTimer(); } // recognise storage actions this.recogniseStorageActions(); break; } }, /** * Get total space via the sum of the used space and free space. * @memberof ExternalStorageMonitor.prototype * @param {callback} function The callback will be run while get total space */ getTotalSpace: function(callback) { var usedSpace, freeSpace; var self = this; this._storage.usedSpace().onsuccess = function(e) { usedSpace = e.target.result; self._storage.freeSpace().onsuccess = function(e) { freeSpace = e.target.result; var totalSpace = self.formatSize(usedSpace + freeSpace); if (callback) { callback(totalSpace); } }; }; }, /** * Helper function to format the value returned by the * nsIDOMDeviceStorage.freeSpace call in a more readable way. * @memberof ExternalStorageMonitor.prototype * @param {size} bytes The size of specific storage space */ formatSize: function(size) { if (size === undefined || isNaN(size)) { return; } var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; var i = 0; while (size >= 1024 && i < (units.length) - 1) { size /= 1024; ++i; } var sizeDecimal = i < 2 ? Math.round(size) : Math.round(size * 10) / 10; var _ = navigator.mozL10n.get; return { size: sizeDecimal, unit: _('byteUnit-' + units[i]) }; }, /** * On/Off flag for enable debug message. * @memberof ExternalStorageMonitor.prototype */ _debug: false, /** * Dump console log for debug message. * @memberof ExternalStorageMonitor.prototype * @param {string} str The error message for debugging. */ debug: function(msg) { if (this._debug) { console.log(msg); } } }; exports.ExternalStorageMonitor = ExternalStorageMonitor; }(window));
<reponame>xiaoyueyue165/The-code-in-the-book <!DOCTYPE html> <html> <body> </body> </html>
SELECT orders.customer_name, items.item_name, items.quantity FROM orders INNER JOIN items ON orders.id = items.order_id
firebase.initializeApp({ apiKey: "<KEY>", authDomain: "iesvillaverdetic.firebaseapp.com", projectId: "iesvillaverdetic" }); function buscar_en_firestore(){ var key=document.getElementById("keyquestion").value; //alert(key); var db = firebase.firestore(); db.collection("test").add({ first: key, last: "Lovelace", born: 1815 }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); }); }
#!/usr/bin/env bats # # Copyright (c) 2019 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # # # Test that IP addresses/connections of PODS are routed/exposed correctly # via a loadbalancer service. load "${BATS_TEST_DIRNAME}/../../.ci/lib.sh" load "${BATS_TEST_DIRNAME}/../../lib/common.bash" setup() { export KUBECONFIG="$HOME/.kube/config" deployment="hello-world" service="my-service" get_pod_config_dir } @test "Expose IP Address" { wait_time=20 sleep_time=2 # Create deployment kubectl create -f "${pod_config_dir}/deployment-expose-ip.yaml" # Check deployment creation cmd="kubectl wait --for=condition=Available deployment/${deployment}" waitForProcess "$wait_time" "$sleep_time" "$cmd" # Check pods are running cmd="kubectl get pods -o jsonpath='{.items[*].status.phase}' | grep Running" waitForProcess "$wait_time" "$sleep_time" "$cmd" # Expose deployment kubectl expose deployment/${deployment} --type=LoadBalancer --name=${service} # There appears to be no easy way to formally wait for a loadbalancer service # to become 'ready' - there is no service.status.condition field to wait on. # Now obtain the local IP:port pair of the loadbalancer service and ensure # we can curl from it, and get the expected result svcip=$(kubectl get service ${service} -o=json | jq '.spec.clusterIP' | sed 's/"//g') svcport=$(kubectl get service ${service} -o=json | jq '.spec.ports[].port') # And check we can curl the expected response from that IP address echo_msg="hello,world" curl http://$svcip:$svcport/echo?msg=${echo_msg} | grep "$echo_msg" # NOTE - we do not test the 'public IP' address of the node balancer here as # that may not be set up, as it may require an IP/DNS allocation and local # routing and firewall rules to access. } teardown() { kubectl delete services ${service} kubectl delete deployment ${deployment} }
#!/usr/bin/env bash # Exit script as soon as a command fails. set -eo pipefail # Executes cleanup function at script exit. trap cleanup EXIT cleanup() { # Kill the GSN relay server that we started (if we started one and if it's still running). if [ -n "$gsn_relay_server_pid" ] && ps -p $gsn_relay_server_pid > /dev/null; then kill $gsn_relay_server_pid fi # Kill the ganache instance that we started (if we started one and if it's still running). if [ -n "$ganache_pid" ] && ps -p $ganache_pid > /dev/null; then kill -9 $ganache_pid fi # #Kill the provable oracle instance that we started (if we started one and if it's still running). # if [ -n "$provable_oracle_pid" ] && ps -p $provable_oracle_pid > /dev/null; then # Kill -9 $provable_oracle_pid # fi } ganache_port=8545 ganache_url="http://localhost:$ganache_port" relayer_port=8090 relayer_url="http://localhost:${relayer_port}" ganache_running() { nc -z localhost "$ganache_port" } relayer_running() { nc -z localhost "$relayer_port" } start_ganache() { npx ganache-cli --port "$ganache_port" -g 20000000000 -d --noVMErrorsOnRPCResponse &> /dev/null & ganache_pid=$! echo "Waiting for ganache to launch on port "$ganache_port"..." while ! ganache_running; do sleep 0.1 # wait for 1/10 of the second before check again done echo "Ganache launched!" } #--detach --quiet setup_gsn_relay() { echo "Launching GSN relay server" gsn_relay_server_pid=$(npx oz-gsn run-relayer --ethereumNodeURL $ganache_url --port $relayer_port --detach --quiet) echo "GSN relay server launched!" } setup_provable_oracle(){ echo "Starting Provable Oracle Ethereum Bridge" ethereum-bridge -H localhost:8545 -a 9 </dev/null &>/dev/null & provable_oracle_pid=$! sleep 60 ps -p $provable_oracle_pid echo "Provable Oracle Ethereum Bridge Launched!" } # Main if ganache_running; then echo "Using existing ganache instance" else echo "Starting our own ganache instance" start_ganache fi setup_gsn_relay setup_provable_oracle env PROVIDER_URL=$ganache_url RELAYER_URL=$relayer_url ./node_modules/.bin/truffle test --network test $@
// Based on CodeMirror's source. // https://github.com/codemirror/CodeMirror/blob/master/src/model/document_data.js // Required to be able to replay code changes on both server and client. function linesFor (text, start, end) { let result = []; for (let i = start; i < end; ++i) result.push(text[i]); return result; } export function performEditorChange (input, change) { let lines = input.split('\n'); let { from, to, text } = change; let firstLine = lines[from.line] || ''; let lastLine = lines[to.line] || ''; let nlines = to.line - from.line; let lastText = text[text.length - 1]; if (change.full) { return text.join('\n'); } if (from.line === to.line) { if (text.length === 1) { lines[from.line] = firstLine.slice(0, from.ch) + lastText + firstLine.slice(to.ch); } else { let added = linesFor(text, 1, text.length - 1); added.push(lastText + firstLine.slice(to.ch)); lines[from.line] = firstLine.slice(0, from.ch) + text[0]; lines = lines.slice(0, from.line + 1).concat(added).concat(lines.slice(from.line + 1)); } } else if (text.length === 1) { lines[from.line] = firstLine.slice(0, from.ch) + text[0] + lastLine.slice(to.ch); lines.splice(from.line + 1, nlines); } else { lines[from.line] = firstLine.slice(0, from.ch) + text[0]; lines[to.line] = lastText + lastLine.slice(to.ch); let added = linesFor(text, 1, text.length - 1); if (nlines > 1) lines.splice(from.line + 1, nlines - 1); lines = lines.slice(0, from.line + 1).concat(added).concat(lines.slice(from.line + 1)); } return lines.join('\n'); }
import type { ForEachFn, FoldFn, MapFn, PredicateFn, CompareFn, KeyFn, ScanFn, EqualFn } from './types/functions/mod.ts'; import { compare } from './lib/compare/mod.ts'; import { next_async, sequence } from './lib/iterable/mod.ts'; import { Flatten, Pair, pair, Nullable } from './types/mod.ts'; import { all, any, average, chain, collect, count, cycle, enumerate, filter, filterMap, find, findMap, flatMap, flatten, fold, fold1, forEach, head, inspect, last, map, max, maxBy, maxByKey, min, minBy, minByKey, nth, nub, nubBy, partition, position, product, reverse, scan, scan1, skip, skipWhile, stepBy, sum, take, takeWhile, unzip, zip, } from './methods/mod.ts'; // prettier-ignore export type ToAsyncIterator<T> = T extends number ? IAsyncIterator_number : T extends Pair<infer A, infer B> ? IAsyncIterator_zip<A, B> : IAsyncIterator_<T>; export interface IAsyncIterator_<T> extends AsyncIterableIterator<T> { /** * @see https://tc39.es/proposal-iterator-helpers/#sec-asynciteratorprototype-@@tostringtag */ [Symbol.toStringTag]: string; /** * similar Array.prototype.every * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.all */ all(fn: PredicateFn<T>): Promise<boolean>; /** * similar Array.prototype.some * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.any */ any(fn: PredicateFn<T>): Promise<boolean>; /** * similar concat * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.chain */ chain(other: Iterable<T | Promise<T>> | AsyncIterable<T | Promise<T>>): ToAsyncIterator<T>; /** * @description * Convert AsyncIterator_ to Array * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect */ collect(): Promise<T[]>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.count */ count(): Promise<number>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.cycle */ cycle(): ToAsyncIterator<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.enumerate */ enumerate(): ToAsyncIterator<Pair<number, T>>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter */ filter(predicate: PredicateFn<T>): ToAsyncIterator<T>; /** * @description * do not catch error * * filter only `null | undefined | NaN` * * @example * ['a', 'b', '1', 'c', '2', '3'] * .iter() * .filterMap(e => parseInt(e, 10)) * .collect(); // [1, 2, 3] * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter_map */ filterMap<R>(fn: MapFn<T, Nullable<R>>): ToAsyncIterator<R>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.find */ find(predicate: PredicateFn<T>): Promise<T | undefined>; /** * @description * do not catch error * * filter only `null | undefined | NaN` * * @example * ['a', 'b', '1', 'c', '2'] * .iter() * .findMap(e => parseInt(e, 10)); // 1 * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.find_map */ findMap<R>(fn: MapFn<T, Nullable<R>>): Promise<R | undefined>; /** * @example * [`it's Sunny in`, '', 'California'] * .iter() * .flatMap(e => e.split(' ')) * .collect(); // [`it's`, 'Sunny', 'in', '', 'California'] * * @see https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map */ flatMap<R extends Iterable<any> | AsyncIterable<any>>(fn: MapFn<T, R>): ToAsyncIterator<Flatten<R>>; /** * @example * [[1], [Promise.resolve(2), 3], 4, 5] * .iter() * .flatten() * .collect(); // [1, 2, 3, 4, 5] * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.flatten */ flatten(): ToAsyncIterator<Flatten<T>>; /** * @see http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:foldl */ fold<U>(init: U | Promise<U>, fn: FoldFn<T, U>): Promise<U>; /** * @throws empty iterator * * @see http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:foldl1 */ fold1(fn: FoldFn<T, T>): Promise<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.for_each */ forEach(fn: ForEachFn<T>): Promise<void>; /** * @description * if empty iterator, return undefined * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#tymethod.next */ head(): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.inspect */ inspect(fn: ForEachFn<T>): ToAsyncIterator<T>; /** * @description * if empty iterator, return undefined * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.last */ last(): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.map */ map<R>(fn: MapFn<T, R>): ToAsyncIterator<R>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max */ max(): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max_by */ maxBy(fn: CompareFn<T>): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.max_by_key */ maxByKey<K>(keyFn: KeyFn<T, K>, cmpFn?: CompareFn<K>): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min */ min(): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min_by */ minBy(fn: CompareFn<T>): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.min_by_key */ minByKey<K>(keyFn: KeyFn<T, K>, cmpFn?: CompareFn<K>): Promise<T | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.nth */ nth(n: number): Promise<T | undefined>; /** * @see https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:nub */ nub(): ToAsyncIterator<T>; /** * @see https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:nubBy */ nubBy(fn: EqualFn<T>): ToAsyncIterator<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.partition */ partition(fn: PredicateFn<T>): Promise<Pair<ToAsyncIterator<T>, ToAsyncIterator<T>>>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.position */ position(fn: PredicateFn<T>): Promise<number | undefined>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.rev */ reverse(): ToAsyncIterator<T>; /** * @see http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:scanl */ scan<U>(init: U | Promise<U>, fn: ScanFn<T, U>): ToAsyncIterator<U>; /** * @see http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:scanl1 */ scan1(fn: ScanFn<T, T>): ToAsyncIterator<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.skip */ skip(count_: number): ToAsyncIterator<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.skip_while */ skipWhile(predicate: PredicateFn<T>): ToAsyncIterator<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.step_by */ stepBy(step: number): ToAsyncIterator<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.take */ take(count_: number): ToAsyncIterator<T>; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.take_while */ takeWhile(predicate: PredicateFn<T>): ToAsyncIterator<T>; toString(): string; /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.zip */ zip<U>(other: Iterable<U | Promise<U>> | AsyncIterable<U | Promise<U>>): ToAsyncIterator<Pair<T, U>>; } export interface IAsyncIterator_number extends IAsyncIterator_<number> { /** * @example * [1, 2, 3, 4, 5] * .iter() * .average(); // 3 * * ([] as number[]) * .iter() * .average(); // 0 */ average(): Promise<number>; /** * @example * [1, 2, 3, 4, 5] * .iter() * .product(); // 120 * * ([] as number[]) * .iter() * .product(); // 1 * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.product */ product(): Promise<number>; /** * @example * [1, 2, 3, 4, 5] * .iter() * .sum(); // 15 * * ([] as number[]) * .iter() * .sum(); // 0 * * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.sum */ sum(): Promise<number>; } export interface IAsyncIterator_zip<T, U> extends IAsyncIterator_<Pair<T, U>> { /** * @see https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.unzip */ unzip(): Promise<Pair<ToAsyncIterator<T>, ToAsyncIterator<U>>>; } export class AsyncIterator_<T> implements IAsyncIterator_<T> { constructor(iter: AsyncIterable<T | Promise<T>>) { this._iter = { async *[Symbol.asyncIterator]() { yield* iter; }, }; Object.defineProperty(this, '_iter', { configurable: false, enumerable: false, writable: false, }); Object.defineProperty(this, Symbol.toStringTag, { configurable: true, enumerable: false, writable: false, }); } private readonly _iter: AsyncIterable<T>; public readonly [Symbol.toStringTag] = 'Async Iterator' as const; public [Symbol.asyncIterator]() { return this; } public async next() { const { done, value } = await next_async(this._iter); return { done, value, }; } public all(fn: PredicateFn<T>) { return all<T>(fn, this); } public any(fn: PredicateFn<T>) { return any<T>(fn, this); } public average() { return average(this as any); } public chain(other: Iterable<T | Promise<T>> | AsyncIterable<T | Promise<T>>) { return (new AsyncIterator_<T>(chain<T>(other, this)) as unknown) as ToAsyncIterator<T>; } public collect() { return collect<T>(this); } public count() { return count<T>(this); } public cycle() { return (new AsyncIterator_<T>(cycle<T>(this)) as unknown) as ToAsyncIterator<T>; } public enumerate() { return (new AsyncIterator_<Pair<number, T>>(enumerate<T>(this)) as unknown) as ToAsyncIterator<Pair<number, T>>; } public filter(predicate: PredicateFn<T>) { return (new AsyncIterator_<T>(filter<T>(predicate, this)) as unknown) as ToAsyncIterator<T>; } public filterMap<R>(fn: MapFn<T, Nullable<R>>) { return (new AsyncIterator_<R>(filterMap<T, R>(fn, this)) as unknown) as ToAsyncIterator<R>; } public find(predicate: PredicateFn<T>) { return find<T>(predicate, this); } public findMap<R>(fn: MapFn<T, Nullable<R>>) { return findMap<T, R>(fn, this); } public flatMap<R extends Iterable<any> | AsyncIterable<any>>(fn: MapFn<T, R>) { return (new AsyncIterator_<Flatten<R>>(flatMap<T, R>(fn, this)) as unknown) as ToAsyncIterator<Flatten<R>>; } public flatten() { return (new AsyncIterator_<Flatten<T>>(flatten<T>(this)) as unknown) as ToAsyncIterator<Flatten<T>>; } public fold<U>(init: U | Promise<U>, fn: FoldFn<T, U>) { return fold<T, U>(fn, init, this); } public fold1(fn: FoldFn<T, T>) { return fold1<T>(fn, this); } public forEach(fn: ForEachFn<T>) { return forEach<T>(fn, this); } public head() { return head<T>(this); } public inspect(fn: ForEachFn<T>) { return (new AsyncIterator_<T>(inspect<T>(fn, this)) as unknown) as ToAsyncIterator<T>; } public last() { return last<T>(this); } public map<R>(fn: MapFn<T, R>) { return (new AsyncIterator_<R>(map<T, R>(fn, this)) as unknown) as ToAsyncIterator<R>; } public max() { return max<T>(this); } public maxBy(fn: CompareFn<T>) { return maxBy<T>(fn, this); } public maxByKey<K>(keyFn: KeyFn<T, K>, cmpFn: CompareFn<K> = compare) { return maxByKey<T, K>(keyFn, cmpFn, this); } public min() { return min<T>(this); } public minBy(fn: CompareFn<T>) { return minBy<T>(fn, this); } public minByKey<K>(keyFn: KeyFn<T, K>, cmpFn: CompareFn<K> = compare) { return minByKey<T, K>(keyFn, cmpFn, this); } public nth(n: number) { return nth<T>(n, this); } public nub() { return (new AsyncIterator_<T>(nub<T>(this)) as unknown) as ToAsyncIterator<T>; } public nubBy(fn: EqualFn<T>) { return (new AsyncIterator_<T>(nubBy<T>(fn, this)) as unknown) as ToAsyncIterator<T>; } public async partition(fn: PredicateFn<T>) { const [left, right] = await partition(fn, this); return (pair(new AsyncIterator_<T>(left), new AsyncIterator_<T>(right)) as unknown) as Pair<ToAsyncIterator<T>, ToAsyncIterator<T>>; } public position(fn: PredicateFn<T>) { return position<T>(fn, this); } public product() { return product(this as any); } public reverse() { return (new AsyncIterator_<T>(reverse<T>(this)) as unknown) as ToAsyncIterator<T>; } public scan<U>(init: U | Promise<U>, fn: ScanFn<T, U>) { return (new AsyncIterator_<U>(scan<T, U>(fn, init, this)) as unknown) as ToAsyncIterator<U>; } public scan1(fn: ScanFn<T, T>) { return (new AsyncIterator_<T>(scan1<T>(fn, this)) as unknown) as ToAsyncIterator<T>; } public skip(count_: number) { return (new AsyncIterator_<T>(skip<T>(count_, this)) as unknown) as ToAsyncIterator<T>; } public skipWhile(predicate: PredicateFn<T>) { return (new AsyncIterator_<T>(skipWhile<T>(predicate, this)) as unknown) as ToAsyncIterator<T>; } public stepBy(step: number) { return (new AsyncIterator_<T>(stepBy<T>(step, this)) as unknown) as ToAsyncIterator<T>; } public sum() { return sum(this as any); } public take(count_: number) { return (new AsyncIterator_<T>(take<T>(count_, this)) as unknown) as ToAsyncIterator<T>; } public takeWhile(predicate: PredicateFn<T>) { return (new AsyncIterator_<T>(takeWhile<T>(predicate, this)) as unknown) as ToAsyncIterator<T>; } public async unzip() { const [left, right] = await unzip<any, any>(this as any); return (pair(new AsyncIterator_<any>(left), new AsyncIterator_<any>(right)) as unknown) as Pair<ToAsyncIterator<any>, ToAsyncIterator<any>>; } public zip<U>(other: Iterable<U | Promise<U>> | AsyncIterable<U | Promise<U>>) { return (new AsyncIterator_<Pair<T, U>>(zip<T, U>(other, this)) as unknown) as ToAsyncIterator<Pair<T, U>>; } } export function iterator<T>(iter: Iterable<T | Promise<T>> | AsyncIterable<T | Promise<T>>) { const it = sequence(iter); return (new AsyncIterator_<T>(it) as unknown) as ToAsyncIterator<T>; }
def classify_data(data): positive_data = [] negative_data = [] for item in data: if item in ['good','excellent','high quality']: positive_data.append(item) elif item in ['bad', 'poor', 'mediocre']: negative_data.append(item) return positive_data, negative_data
import React from "react" import Img from "gatsby-image" import styled from 'styled-components'; import ImageAll from './helpers/ImageAll'; import ImagePortraits from './helpers/ImagePortraits'; const StyledImg = styled(Img)` border-radius: 4px; ` const Image = ({name = null, typeOfImages = null}) => { if (typeOfImages && typeOfImages === 'portraits') { console.log('Executing Portraiture Component') return <ImagePortraits /> } return <ImageAll /> } export default Image
/** * Copyright 2021 The IcecaneDB Authors. All rights reserved. * * 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 * * https://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 mvcc import ( "bytes" "os" "testing" "github.com/dr0pdb/icecanedb/pkg/storage" "github.com/dr0pdb/icecanedb/test" "github.com/stretchr/testify/assert" ) func TestTxnKeyEncodingDecoding(t *testing.T) { for i := uint64(1); i <= 1000; i++ { txnID := uint64(100) txnKey := newTxnKey(test.TestKeys[i%5], txnID) assert.Equal(t, test.TestKeys[i%5], txnKey.userKey(), "decoded user key doesn't match") assert.Equal(t, txnID, txnKey.txnID(), "decoded txnId doesn't match") } } // harness to test the txn key comparator and scan operations behaviour type txnKeyComparatorTestHarness struct { s *storage.Storage } func newTxnKeyComparatorTestHarness() *txnKeyComparatorTestHarness { txnComp := NewtxnKeyComparator() os.MkdirAll(testDirectory, os.ModePerm) s, _ := storage.NewStorageWithCustomComparator(testDirectory, "testdb", txnComp, &storage.Options{CreateIfNotExist: true}) s.Open() return &txnKeyComparatorTestHarness{ s: s, } } func (h *txnKeyComparatorTestHarness) cleanup() { h.s.Close() os.RemoveAll(testDirectory) } // A single txn should get the writes for the increasing keys in the same order func TestTxnKeyComparatorScanSingleTxn(t *testing.T) { h := newTxnKeyComparatorTestHarness() defer h.cleanup() txnID := uint64(99) for i := 0; i < 5; i++ { txnKey := newTxnKey(test.TestKeys[i], txnID) err := h.s.Set(txnKey, test.TestValues[i], nil) assert.Nil(t, err, "Unexpected error during set request") } startTxnKey := newTxnKey(test.TestKeys[0], txnID) itr := h.s.Scan(startTxnKey) idx := uint64(0) for { if itr.Valid() { txnKey := TxnKey(itr.Key()) assert.Equal(t, test.TestKeys[idx], txnKey.userKey(), "user key from decoded key doesn't match the original") assert.Equal(t, txnID, txnKey.txnID(), "txn id from decoded key doesn't match with original") assert.Equal(t, test.TestValues[idx], itr.Value(), "value from decoded key doesn't match with original") itr.Next() idx++ } else { break } } assert.Equal(t, uint64(5), idx, "expected a total of 5 kv pairs") } // Multiple txns writing to the same key should be sorted in decreasing order of txn id func TestTxnKeyComparatorScanSingleKey(t *testing.T) { h := newTxnKeyComparatorTestHarness() defer h.cleanup() for i := uint64(1); i <= 100; i++ { txnKey := newTxnKey(test.TestKeys[0], i) err := h.s.Set(txnKey, test.TestValues[0], nil) assert.Nil(t, err, "Unexpected error during set request") } startTxnKey := newTxnKey(test.TestKeys[0], uint64(100)) itr := h.s.Scan(startTxnKey) idx := uint64(100) // should be in decreasing order to txn id for { if itr.Valid() { txnKey := TxnKey(itr.Key()) assert.Equal(t, test.TestKeys[0], txnKey.userKey(), "user key from decoded key doesn't match the original") assert.Equal(t, idx, txnKey.txnID(), "txn id from decoded key doesn't match with original") assert.Equal(t, test.TestValues[0], itr.Value(), "value from decoded key doesn't match with original") itr.Next() idx-- } else { break } } assert.Equal(t, uint64(0), idx, "expected a total of 100 kv pairs") } // Multiple txns writing to the multiple keys // Keys should be first sorted by user keys in increasing order // Same keys should be sorted in decreasing order according to txn id func TestTxnKeyComparatorScanMultipleKeyMultipleTxns(t *testing.T) { h := newTxnKeyComparatorTestHarness() defer h.cleanup() for txnID := uint64(1); txnID <= 100; txnID++ { for keyId := uint64(0); keyId < 5; keyId++ { txnKey := newTxnKey(test.TestKeys[keyId], txnID) err := h.s.Set(txnKey, test.TestValues[keyId], nil) assert.Nil(t, err, "Unexpected error during set request") } } for keyId := uint64(0); keyId < 5; keyId++ { startTxnKey := newTxnKey(test.TestKeys[keyId], uint64(100)) itr := h.s.Scan(startTxnKey) idx := uint64(100) // should be in decreasing order to txn id for { if itr.Valid() { txnKey := TxnKey(itr.Key()) if !bytes.Equal(txnKey.userKey(), test.TestKeys[keyId]) { break } assert.Equal(t, test.TestKeys[keyId], txnKey.userKey(), "user key from decoded key doesn't match the original") assert.Equal(t, idx, txnKey.txnID(), "txn id from decoded key doesn't match with original") assert.Equal(t, test.TestValues[keyId], itr.Value(), "value from decoded key doesn't match with original") itr.Next() idx-- } else { break } } assert.Equal(t, uint64(0), idx, "expected a total of 100 kv pairs for the single user key") } }
import time def calculate_average_time(iterations): start = time.time() for step in range(iterations): # Perform the specific operation here # Example: train_model() end = time.time() time_taken = end - start start = time.time() # Reset start time for the next iteration # Accumulate training cost using TensorFlow's tf.summary.Summary() # Example: cost_summ.value.add(tag='Train_Cost', simple_value=float(train_cost)) average_time = time_taken / iterations return average_time
<gh_stars>1-10 package greedy; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 18230번: 2xN 에쁜 타일링 * * @see https://www.acmicpc.net/problem/18230/ * */ public class Boj18230 { private static PriorityQueue<Long> pqA = new PriorityQueue<>(); private static PriorityQueue<Long> pqB = new PriorityQueue<>(); public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); input(A, br.readLine(), pqA); input(B, br.readLine(), pqB); System.out.println(search(N)); } private static void input(int n, String line, PriorityQueue<Long> pq) { StringTokenizer st = new StringTokenizer(line); for(int i = 0; i < n; i++){ pq.offer(-Long.parseLong(st.nextToken())); } } private static long search(int n) { long max = 0; while(n > 0) { if(n % 2 == 1) { // odd size max -= pqA.poll(); n--; } else { if(pqA.size() < 2) { if(pqB.isEmpty()) continue; max -= pqB.poll(); n -= 2; } else if(pqB.isEmpty()) { if(pqA.size() < 2) continue; max -= (pqA.poll() + pqA.poll()); n -= 2; } else { long peek = pqA.poll(); long a = peek + pqA.peek(); long b = pqB.peek(); if (a < b) { // compare one B two A pqA.poll(); max -= a; } else { pqA.offer(peek); max -= pqB.poll(); } n -= 2; } } } return max; } }
void nonlinear_step(std::shared_ptr<const DefaultExecutor> exec, int n, double nonlinear_scale, double potential_scale, double time_scale, const gko::matrix::Dense<double>* potential, gko::matrix::Dense<std::complex<double>>* ampl) { using device_complex = device_type<std::complex<double>>; run_kernel( exec, GKO_KERNEL(auto i, auto j, auto n, auto nonlinear_scale, auto potential_scale, auto time_scale, auto potential, auto ampl) { // Implement the nonlinear step operation using the provided parameters // and the given kernel // Pseudocode: // for each element in ampl: // ampl[i][j] = nonlinear_scale * potential_scale * time_scale * potential[i][j] * ampl[i][j] }); }
fn foo<'a,'b,F>(p: Path<'a, 'b>, mut f: F) where F: for<'c> FnMut(Path<'a, 'c>) { let mut current_path = Some(p); while let Some(path) = current_path { f(path); current_path = path.tail; } }
<reponame>Shasthojoy/cartodb var $ = require('jquery'); var Backbone = require('backbone'); var UserAssetsListView = require('builder/components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view'); var AssetsCollection = require('builder/data/assets-collection'); var ConfigModel = require('builder/data/config-model'); var UserModel = require('builder/data/user-model'); var OrganizationAssetsCollection = require('builder/data/organization-assets-collection'); var AssetModel = require('builder/data/asset-model'); describe('components/form-components/editors/fill/input-color/assets-picker/user-assets-list-view', function () { beforeEach(function () { this.model = new Backbone.Model({ image: '/image.png' }); this.selectedAsset = new Backbone.Model(); this.configModel = new ConfigModel({ base_url: '/u/pepe' }); this.userModel = new UserModel({}, { configModel: this.configModel }); var asset1 = new AssetModel({ item: 1, state: '', public_url: 'one.jpg' }); var asset2 = new AssetModel({ item: 2, state: '', public_url: 'two.png' }); var asset3 = new AssetModel({ item: 3, state: '', public_url: 'three.gif' }); this._userAssetCollection = new AssetsCollection([asset1, asset2, asset3], { configModel: this.configModel, userModel: this.userModel }); this.view = new UserAssetsListView({ title: 'Title', model: this.model, userAssetCollection: this._userAssetCollection, selectedAsset: this.selectedAsset, userModel: this.userModel }); this.view.render(); }); it('should render the assets', function () { expect(this.view.$el.find('.js-asset').length).toBe(this._userAssetCollection.size() + 1); }); it('should render the add button', function () { expect(this.view.$el.find('.AssetsList-item--text .js-asset').text().trim()).toBe('+'); expect(this.view.$el.find('.AssetsList-item--text .js-asset').length).toBe(1); }); it('should trigger an upload event when clicking the add button', function () { var triggered = false; this.view.bind('init-upload', function () { triggered = true; }, this); this.view.$el.find('.AssetsList-item--text .js-asset').click(); expect(triggered).toBeTruthy(); }); it('should select an asset', function () { this._userAssetCollection.at(0).set('state', ''); this._userAssetCollection.at(1).set('state', ''); this._userAssetCollection.at(2).set('state', ''); expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(0); $(this.view.$('.js-asset')[1]).click(); expect(this.view.$('.is-selected').length).toBe(1); expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(1); expect(this._userAssetCollection.at(0).get('state')).toBe('selected'); }); it('should select all the assets', function () { this._userAssetCollection.at(0).set('state', 'selected'); this.view.$('.js-select-all').click(); expect(this.view.$('.is-selected').length).toBe(3); expect(this._userAssetCollection.at(0).get('state')).toBe('selected'); expect(this._userAssetCollection.at(1).get('state')).toBe('selected'); expect(this._userAssetCollection.at(2).get('state')).toBe('selected'); }); it('should deselect all the assets', function () { this._userAssetCollection.at(0).set('state', 'selected'); this._userAssetCollection.at(1).set('state', 'selected'); this._userAssetCollection.at(2).set('state', 'selected'); this.view.$('.js-deselect-all').click(); expect(this._userAssetCollection.at(0).get('state')).toBe(''); expect(this._userAssetCollection.at(1).get('state')).toBe(''); expect(this._userAssetCollection.at(2).get('state')).toBe(''); expect(this.view.$('.is-selected').length).toBe(0); }); describe('when user is inside organization', function () { var view; beforeEach(function () { spyOn(this.userModel, 'isInsideOrg').and.returnValue(true); this._organizationAssetCollection = new OrganizationAssetsCollection([{ item: 1, state: '' }, { item: 2, state: '' }, { item: 3, state: '' }], { configModel: this.configModel, orgId: this.userModel }); view = new UserAssetsListView({ title: 'Title', model: this.model, userAssetCollection: this._userAssetCollection, organizationAssetCollection: this._organizationAssetCollection, selectedAsset: this.selectedAsset, userModel: this.userModel }); view.render(); }); it('should select an asset and deselect all the organization assets', function () { this._organizationAssetCollection.at(0).set('state', 'selected'); expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(0); expect(this._userAssetCollection.at(0).get('state')).toBe(''); expect(this._organizationAssetCollection.where({ state: 'selected' }).length).toBe(1); expect(this._organizationAssetCollection.at(0).get('state')).toBe('selected'); $(view.$('.js-asset')[1]).click(); expect(this.view.$('.is-selected').length).toBe(1); expect(this._userAssetCollection.where({ state: 'selected' }).length).toBe(1); expect(this._userAssetCollection.at(0).get('state')).toBe('selected'); expect(this._organizationAssetCollection.where({ state: 'selected' }).length).toBe(0); expect(this._organizationAssetCollection.at(0).get('state')).toBe(''); }); }); it('should remove selected assets', function () { this._userAssetCollection.at(0).set('state', 'selected'); this._userAssetCollection.at(1).set('state', 'selected'); this._userAssetCollection.at(2).set('state', ''); this.view.$('.js-remove').click(); expect(this._userAssetCollection.size()).toBe(1); }); it('should unset the selected asset', function () { var self = this; AssetModel.prototype.destroy = function () { self.view._onDestroyFinished({ status: 200 }); }; this._userAssetCollection.at(0).set('state', 'selected'); this._userAssetCollection.at(1).set('state', ''); this._userAssetCollection.at(2).set('state', ''); expect(this.selectedAsset.get('url')).toBe('one.jpg'); expect(this.selectedAsset.get('kind')).toBe('custom-marker'); this.view.$('.js-remove').click(); expect(this.selectedAsset.get('url')).toBe(undefined); expect(this.selectedAsset.get('kind')).toBe(undefined); }); it('should not have leaks', function () { expect(this.view).toHaveNoLeaks(); }); afterEach(function () { this.view.clean(); }); });
package transform_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/c0nscience/yastgt/pkg/parse/transform" ) func Test_Parse(t *testing.T) { t.Run("should return a matrix", func(t *testing.T) { s := "matrix(2,3,4,5,6,7)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 2.0, subj.At(0, 0), delta) assert.InDelta(t, 3.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 4.0, subj.At(0, 1), delta) assert.InDelta(t, 5.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 6.0, subj.At(0, 2), delta) assert.InDelta(t, 7.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a matrix with space separated list", func(t *testing.T) { s := "matrix(2 3 4 5 6 7)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 2.0, subj.At(0, 0), delta) assert.InDelta(t, 3.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 4.0, subj.At(0, 1), delta) assert.InDelta(t, 5.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 6.0, subj.At(0, 2), delta) assert.InDelta(t, 7.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a translation matrix with tx and ty", func(t *testing.T) { s := "translate(2,3)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 1.0, subj.At(0, 0), delta) assert.InDelta(t, 0.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.0, subj.At(0, 1), delta) assert.InDelta(t, 1.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 2.0, subj.At(0, 2), delta) assert.InDelta(t, 3.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a translation matrix with tx and ty if space included", func(t *testing.T) { s := "translate(2, 3)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 1.0, subj.At(0, 0), delta) assert.InDelta(t, 0.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.0, subj.At(0, 1), delta) assert.InDelta(t, 1.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 2.0, subj.At(0, 2), delta) assert.InDelta(t, 3.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a translation matrix with tx and ty if space and decimal digits included", func(t *testing.T) { s := "translate(2.64, 3.78)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 1.0, subj.At(0, 0), delta) assert.InDelta(t, 0.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.0, subj.At(0, 1), delta) assert.InDelta(t, 1.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 2.64, subj.At(0, 2), delta) assert.InDelta(t, 3.78, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a translation matrix with ty as 0 if only one number found", func(t *testing.T) { s := "translate(2)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 1.0, subj.At(0, 0), delta) assert.InDelta(t, 0.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.0, subj.At(0, 1), delta) assert.InDelta(t, 1.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 2.0, subj.At(0, 2), delta) assert.InDelta(t, 0.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a scaling matrix with sx and sy", func(t *testing.T) { s := "scale(4,5)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 4.0, subj.At(0, 0), delta) assert.InDelta(t, 0.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.0, subj.At(0, 1), delta) assert.InDelta(t, 5.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 0.0, subj.At(0, 2), delta) assert.InDelta(t, 0.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a scaling matrix with sy is equal to sx", func(t *testing.T) { s := "scale(4)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 4.0, subj.At(0, 0), delta) assert.InDelta(t, 0.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.0, subj.At(0, 1), delta) assert.InDelta(t, 4.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 0.0, subj.At(0, 2), delta) assert.InDelta(t, 0.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a rotate matrix with an angle", func(t *testing.T) { s := "rotate(40)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 0.7660444, subj.At(0, 0), delta) assert.InDelta(t, 0.6427876, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, -0.6427876, subj.At(0, 1), delta) assert.InDelta(t, 0.7660444, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 0.0, subj.At(0, 2), delta) assert.InDelta(t, 0.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a rotate matrix with an angle and a rotation point", func(t *testing.T) { s := "rotate(40, 6, 7)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 0.7660444, subj.At(0, 0), delta) assert.InDelta(t, 0.6427876, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, -0.6427876, subj.At(0, 1), delta) assert.InDelta(t, 0.7660444, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 5.9032466, subj.At(0, 2), delta) assert.InDelta(t, -2.2190367, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a skewX matrix with an angle", func(t *testing.T) { s := "skewX(40)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 1.0, subj.At(0, 0), delta) assert.InDelta(t, 0.0, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.839099, subj.At(0, 1), delta) assert.InDelta(t, 1.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 0.0, subj.At(0, 2), delta) assert.InDelta(t, 0.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return a skewY matrix with an angle", func(t *testing.T) { s := "skewY(40)" subj := transform.ParseTypes(s)[0] assert.InDelta(t, 1.0, subj.At(0, 0), delta) assert.InDelta(t, 0.839099, subj.At(1, 0), delta) assert.InDelta(t, 0.0, subj.At(2, 0), delta) assert.InDelta(t, 0.0, subj.At(0, 1), delta) assert.InDelta(t, 1.0, subj.At(1, 1), delta) assert.InDelta(t, 0.0, subj.At(2, 1), delta) assert.InDelta(t, 0.0, subj.At(0, 2), delta) assert.InDelta(t, 0.0, subj.At(1, 2), delta) assert.InDelta(t, 1.0, subj.At(2, 2), delta) }) t.Run("should return no transforms for an unknown type", func(t *testing.T) { s := "unknown(5,4)" subj := transform.ParseTypes(s) assert.Empty(t, subj) }) t.Run("should return multiple transforms from one string", func(t *testing.T) { s := "translate(2,3)skewY(40)" subj := transform.ParseTypes(s) assert.InDelta(t, 1.0, subj[0].At(0, 0), delta) assert.InDelta(t, 0.0, subj[0].At(1, 0), delta) assert.InDelta(t, 0.0, subj[0].At(2, 0), delta) assert.InDelta(t, 0.0, subj[0].At(0, 1), delta) assert.InDelta(t, 1.0, subj[0].At(1, 1), delta) assert.InDelta(t, 0.0, subj[0].At(2, 1), delta) assert.InDelta(t, 2.0, subj[0].At(0, 2), delta) assert.InDelta(t, 3.0, subj[0].At(1, 2), delta) assert.InDelta(t, 1.0, subj[0].At(2, 2), delta) assert.InDelta(t, 1.0, subj[1].At(0, 0), delta) assert.InDelta(t, 0.839099, subj[1].At(1, 0), delta) assert.InDelta(t, 0.0, subj[1].At(2, 0), delta) assert.InDelta(t, 0.0, subj[1].At(0, 1), delta) assert.InDelta(t, 1.0, subj[1].At(1, 1), delta) assert.InDelta(t, 0.0, subj[1].At(2, 1), delta) assert.InDelta(t, 0.0, subj[1].At(0, 2), delta) assert.InDelta(t, 0.0, subj[1].At(1, 2), delta) assert.InDelta(t, 1.0, subj[1].At(2, 2), delta) }) t.Run("should return multiple transforms from one string with spaces", func(t *testing.T) { s := "translate(2,3) skewY(40)" subj := transform.ParseTypes(s) assert.InDelta(t, 1.0, subj[0].At(0, 0), delta) assert.InDelta(t, 0.0, subj[0].At(1, 0), delta) assert.InDelta(t, 0.0, subj[0].At(2, 0), delta) assert.InDelta(t, 0.0, subj[0].At(0, 1), delta) assert.InDelta(t, 1.0, subj[0].At(1, 1), delta) assert.InDelta(t, 0.0, subj[0].At(2, 1), delta) assert.InDelta(t, 2.0, subj[0].At(0, 2), delta) assert.InDelta(t, 3.0, subj[0].At(1, 2), delta) assert.InDelta(t, 1.0, subj[0].At(2, 2), delta) assert.InDelta(t, 1.0, subj[1].At(0, 0), delta) assert.InDelta(t, 0.839099, subj[1].At(1, 0), delta) assert.InDelta(t, 0.0, subj[1].At(2, 0), delta) assert.InDelta(t, 0.0, subj[1].At(0, 1), delta) assert.InDelta(t, 1.0, subj[1].At(1, 1), delta) assert.InDelta(t, 0.0, subj[1].At(2, 1), delta) assert.InDelta(t, 0.0, subj[1].At(0, 2), delta) assert.InDelta(t, 0.0, subj[1].At(1, 2), delta) assert.InDelta(t, 1.0, subj[1].At(2, 2), delta) }) }
<filename>offer/src/main/java/com/java/study/algorithm/zuo/cadvanced/advanced_class_07/Code_02_LIS.java package com.java.study.algorithm.zuo.cadvanced.advanced_class_07; /** * 最长递增子序列 * 【题目】 * 给定数组arr,返回arr的最长递增子序列。 * 【举例】 arr=[2,1,5,3,6,4,8,9,7],返回的最长递增子序列为 [1,3,4,8,9]。 * 【要求】 如果arr长度为N,请实现时间复杂度为O(NlogN)的方法。 */ public class Code_02_LIS{ }
#!/bin/sh # CYBERWATCH SAS - 2017 # # Security fix for CESA-2014:0866 # # Security announcement date: 2014-07-09 18:25:19 UTC # Script generation date: 2017-01-01 21:11:06 UTC # # Operating System: CentOS 5 # Architecture: x86_64 # # Vulnerable packages fix on version: # - samba3x-winbind.i386:3.6.6-0.140.el5_10 # - samba3x-winbind-devel.i386:3.6.6-0.140.el5_10 # - samba3x.x86_64:3.6.6-0.140.el5_10 # - samba3x-client.x86_64:3.6.6-0.140.el5_10 # - samba3x-common.x86_64:3.6.6-0.140.el5_10 # - samba3x-doc.x86_64:3.6.6-0.140.el5_10 # - samba3x-domainjoin-gui.x86_64:3.6.6-0.140.el5_10 # - samba3x-swat.x86_64:3.6.6-0.140.el5_10 # - samba3x-winbind.x86_64:3.6.6-0.140.el5_10 # - samba3x-winbind-devel.x86_64:3.6.6-0.140.el5_10 # # Last versions recommanded by security team: # - samba3x-winbind.i386:3.6.23-12.el5_11 # - samba3x-winbind-devel.i386:3.6.23-12.el5_11 # - samba3x.x86_64:3.6.23-12.el5_11 # - samba3x-client.x86_64:3.6.23-12.el5_11 # - samba3x-common.x86_64:3.6.23-12.el5_11 # - samba3x-doc.x86_64:3.6.23-12.el5_11 # - samba3x-domainjoin-gui.x86_64:3.6.23-12.el5_11 # - samba3x-swat.x86_64:3.6.23-12.el5_11 # - samba3x-winbind.x86_64:3.6.23-12.el5_11 # - samba3x-winbind-devel.x86_64:3.6.23-12.el5_11 # # CVE List: # - CVE-2014-0244 # - CVE-2014-3493 # # More details: # - https://www.cyberwatch.fr/vulnerabilites # # Licence: Released under The MIT License (MIT), See LICENSE FILE sudo yum install samba3x-winbind.i386-3.6.23 -y sudo yum install samba3x-winbind-devel.i386-3.6.23 -y sudo yum install samba3x.x86_64-3.6.23 -y sudo yum install samba3x-client.x86_64-3.6.23 -y sudo yum install samba3x-common.x86_64-3.6.23 -y sudo yum install samba3x-doc.x86_64-3.6.23 -y sudo yum install samba3x-domainjoin-gui.x86_64-3.6.23 -y sudo yum install samba3x-swat.x86_64-3.6.23 -y sudo yum install samba3x-winbind.x86_64-3.6.23 -y sudo yum install samba3x-winbind-devel.x86_64-3.6.23 -y
const express = require('express') const { createReadStream } = require('fs') const app = express() const port = 5001 app.use(function (req, res, next) { res.setHeader( 'Content-Security-Policy', "default-src 'self' https://www.adweek.com/; script-src 'self' 'unsafe-inline'" ); next(); }); app.get('/', (req, res) => { createReadStream('files/my.html').pipe(res) }) app.listen(port, () => { console.log(`My Server 1 is listening at http://localhost:${port}`) }) app.use(express.static('files'))
#!/usr/bin/env bash set -eu bosh -n create-release --dir bosh-src --tarball source-release/release.tgz
import React, { useState, useEffect } from 'react' import { Link } from 'react-router-dom' import { useAuth } from '../contexts/AuthContext' import { db, storage } from '../firebase/index' import Loading from './Loading' import defDrink from '../assets/icons/def-drink.svg' const reviewsRef = db.collection('reviews') const shopsRef = db.collection('shops') const Reviews = () => { const { currentUser } = useAuth() const [reviews, setReviews] = useState([]) const [deleteReviewId, setDeleteReviewId] = useState('') const [deleteShopId, setDeleteShopId] = useState('') const [isLoading, setIsLoading] = useState(true) const [popupOpen, setPopupOpen] = useState(false) const [isOnline, setNetwork] = useState(window.navigator.onLine) const updateNetwork = () => setNetwork(window.navigator.onLine) useEffect(() => { window.addEventListener('offline', updateNetwork) window.addEventListener('online', updateNetwork) return () => { window.removeEventListener('offline', updateNetwork) window.removeEventListener('online', updateNetwork) } }, []) useEffect(() => { reviewsRef .get() .then(snapshot => { snapshot.forEach(reviewDoc => { const newReview = { ref: reviewDoc.ref, ...reviewDoc.data() } if (newReview.user.id === currentUser.uid) { shopsRef .doc(newReview.shop.id) .get() .then(shopDoc => { const shop = shopDoc.data() if (!isOnline || !newReview.fullPath) { setReviews(reviews => [...reviews, { ...newReview, shop, img: defDrink }]) setIsLoading(false) } else { storage .ref(newReview.fullPath) .getDownloadURL() .then(url => { setReviews(reviews => [...reviews, { ...newReview, shop, img: url }]) setIsLoading(false) }) .catch(err => { console.log('Error downloading file:', err) setReviews(reviews => [...reviews, { ...newReview, shop, img: defDrink }]) setIsLoading(false) }) } }) .catch(err => { console.log('Error getting document:', err) setIsLoading(false) }) } }) }) .catch(err => { console.log('Error getting collection:', err) setIsLoading(false) }) }, []) const handlePopupOpen = review => { setPopupOpen(true) setDeleteReviewId(review.ref.id) setDeleteShopId(review.shop.id) } const handlePopupClose = () => { setPopupOpen(false) setDeleteReviewId('') setDeleteShopId('') } const handleDelete = (reviewId, shopId) => { handlePopupClose() reviewsRef .doc(reviewId) .delete() .then(() => { const newReviews = reviews.filter(review => review.ref.id !== reviewId) setReviews(newReviews) const shopRef = shopsRef.doc(shopId) reviewsRef .where('shop', '==', shopRef) .get() .then(querySnapshot => { if (querySnapshot.empty) { shopRef.delete() } }) .catch(err => console.log('Error getting documents: ', err)) }) } const Popup = () => { return ( <div className="overlay--trans"> <div className="popup"> <p className="popup-message">Are you sure to delete this review?</p> <div className="btn-area--half"> <button onClick={handlePopupClose} className="btn--secondary btn--half"> Cancel </button> <button onClick={() => handleDelete(deleteReviewId, deleteShopId)} className="btn--primary btn--half" > Delete </button> </div> </div> </div> ) } const reviewItems = reviews.map((review, i) => { return ( <div className="reviews-background reviews-area profile-review" key={review.ref.id}> <div className="review-img-container"> <img src={review.img} className={review.img === defDrink ? 'review-icon' : 'review-img'} alt="drink" /> </div> <div className="layout-grid"> <h2 className="u-text-small"> {review.drink_name}&#160;<span className="normal-font-weight">at</span>{' '} {review.shop.name} </h2> <p className="category">{review.drink_category}</p> <p className="price">{review.price} CAD</p> {(() => { const rating = review.rating const noRating = 5 - rating let star = '' let hollowStars = '' for (let i = 0; i < rating; i++) { star = star + '★' } for (let i = 0; i < noRating; i++) { hollowStars = hollowStars + '☆' } return ( <p className="rating"> {star} {hollowStars} </p> ) })()} </div> <p className="comment"> <span>"</span> {review.comment} <span>"</span> </p> <div className="bottom-row"> <div className="delete-edit-wrapper"> <button className="btn--secondary btn--xs btn--link"> <Link to={'/review/edit/' + review.ref.id}>Edit</Link> </button> <button onClick={() => handlePopupOpen(review)} className="btn--tertiary btn--xs"> Delete </button> </div> </div> </div> ) }) if (isLoading) return <Loading /> if (reviewItems.length) { return ( <> {popupOpen ? <Popup /> : null} <div className="review-wrapper">{reviewItems}</div> </> ) } else { return <div className="reviews-background no-reviews-container">Your Reviews are not found</div> } } export default Reviews
<reponame>felixrieseberg/find-npm-windows 'use strict' const mockery = require('mockery') const ChildProcessMock = require('../fixtures/child_process') describe('Find-Npm', () => { let passedArgs let passedProcess let passedCmd let execReturnValue const cpMock = { spawn(_process, _args) { passedProcess = _process passedArgs = _args return new ChildProcessMock({ stdout: 'C:\\test-ps1\\nodejs\\npm.cmd' }) }, exec(_cmd, _cb) { passedCmd = _cmd _cb(null, execReturnValue) } } before(() => process.env.quiet = true) afterEach(() => { mockery.deregisterAll() mockery.disable() passedArgs = undefined passedProcess = undefined passedCmd = undefined execReturnValue = undefined }) beforeEach(() => { mockery.enable({ useCleanCache: true, warnOnUnregistered: false }) }) it('should attempt to find a path if none is given', (done) => { const fsMock = { accessSync: () => true } mockery.registerMock('child_process', cpMock) mockery.registerMock('fs', fsMock) const findNpm = require('../../lib/find-npm') execReturnValue = 'C:\\test\\' findNpm() .then(() => { const expectedCmd = 'npm config --global get prefix' const expectedProcess = 'powershell.exe' const expectedPsArgs = 'Get-Command npm | Select-Object -ExpandProperty Definition' const expectedArgs = ['-NoProfile', '-NoLogo', expectedPsArgs] passedCmd.should.be.equal(expectedCmd) passedProcess.should.be.equal(expectedProcess) passedArgs.should.be.deep.equal(expectedArgs) done() }) .catch(err => console.log(err)) }) it(`should remove newlines from npm's output`, (done) => { const utilMock = { isPathExists: (path) => path.includes('test-npm') } mockery.registerMock('child_process', cpMock) mockery.registerMock('./utils', utilMock) const findNpm = require('../../lib/find-npm') execReturnValue = 'C:\\test-npm\n' findNpm() .then(result => { const containsOnlyOneNewline = result.message.includes('C:\\test-npm\n\u001b') containsOnlyOneNewline.should.be.equal.true done() }) .catch(err => console.log(err)) }) it(`should prefer PowerShell over npm (if both exist)`, (done) => { const fsMock = { accessSync: (path) => true } mockery.registerMock('child_process', cpMock) mockery.registerMock('fs', fsMock) const utils = require('../../lib/utils') const findNpm = require('../../lib/find-npm') execReturnValue = 'C:\\test-npm\n' findNpm() .then(result => { result.path.should.equal('C:\\test-ps1\\nodejs') done() }) .catch(err => console.log(err)) }) it(`should prefer npm over PowerShell (if PowerShell does not exist)`, (done) => { const utilMock = { isPathExists: (path) => (path.includes('test-npm')) } mockery.registerMock('child_process', cpMock) mockery.registerMock('./utils', utilMock) const findNpm = require('../../lib/find-npm') execReturnValue = 'C:\\test-npm\n' findNpm() .then(result => { result.path.should.equal('C:\\test-npm') done() }) .catch(err => console.log(err)) }) it(`should prefer PowerShell (if it can't confirm either)`, (done) => { const utilMock = { isPathExists: () => false } mockery.registerMock('child_process', cpMock) mockery.registerMock('./utils', utilMock) execReturnValue = 'C:\\test-npm\n' const findNpm = require('../../lib/find-npm') findNpm() .then(result => { result.path.should.equal('C:\\test-ps1\\nodejs') done() }) .catch(err => console.log(err)) }) it(`should check if a given path exists`, (done) => { const fsMock = { lstat: (path, cb) => cb(null, { isDirectory: () => true }) } mockery.registerMock('fs', fsMock) const findNpm = require('../../lib/find-npm') findNpm('C:\\test-path') .then(result => { result.path.should.equal('C:\\test-path') done() }) .catch(err => console.log(err)) }) })
<reponame>josesentis/react-graphql-boilerplate import styled from 'styled-components'; import { media } from '../../utils/media-queries'; import { space } from '../../utils/mixins'; import { colors, typography } from '../../utils/settings'; const HeaderStyled = styled.header` position: fixed; top: 0; left: 0; width: 100%; will-change: transform; z-index: 9; .dark & { background-color: ${colors.base100}; } .header { align-items: flex-start; color: ${colors.base500}; display: flex; font-family: ${typography.secondaryFontFamily.join(', ')}; justify-content: space-between; padding: ${space()} 0; transition: transform 0s; .home & { transform: translateY(-100%); } &.loaded-enter-done { transition: transform .7s cubic-bezier(.215, .61, .355, 1); transform: translateY(0); } > div { max-width: 150px; } a { background-color: transparent !important; color: ${colors.base500} !important; text-decoration: none; &::after { display: none; } span { display: block; } } ${media.min('phone')` justify-content: flex-start; > div:first-child { margin-right: ${space(2)}; } `}; ${media.min('maxWidth')` padding: ${space(1.25)} 0; `}; } `; export default HeaderStyled;
#!/bin/bash : "${CK8S_CONFIG_PATH:?Missing CK8S_CONFIG_PATH}" OLD_SECRETS="${CK8S_CONFIG_PATH}/secrets.env" NEW_SECRETS="${CK8S_CONFIG_PATH}/secrets.yaml" sops -d "${OLD_SECRETS}" | \ sed 's/^\([^=]\+\)/\L\1/' | \ sed 's/tf_var_//' | \ sed 's/=/: /' | \ sops --config "${CK8S_CONFIG_PATH}/.sops.yaml" --input-type yaml --output-type yaml -e /dev/stdin > "${NEW_SECRETS}"
<reponame>kdaemonv/arquillian-cube package org.arquillian.cube.impl.client; import java.util.List; import org.arquillian.cube.spi.Cube; import org.arquillian.cube.spi.CubeRegistry; import org.jboss.arquillian.core.api.annotation.Observes; import org.jboss.arquillian.test.spi.event.suite.BeforeSuite; public class ForceStopDockerContainersShutdownHook { public void attachShutDownHookForceStopDockerContainers(@Observes(precedence = 200) BeforeSuite event, final CubeRegistry cubeRegistry) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { final List<Cube<?>> cubes = cubeRegistry.getCubes(); for (Cube cube : cubes) { cube.stop(); cube.destroy(); } })); } }
#!/usr/bin/env bash : "cleanup packages" \ && zypper clean -a # vim:set et sts=4 ts=4 tw=80:
#!/bin/bash # # Copyright (c) 2019 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 set -o errexit set -o nounset set -o pipefail SCRIPT_PATH=$(dirname "$(readlink -f "$0")") http_proxy="${http_proxy:-}" https_proxy="${https_proxy:-}" DOCKERFILE_PATH="${SCRIPT_PATH}/Dockerfile" declare -a OS_DISTRIBUTION=( \ 'ubuntu:16.04' \ 'ubuntu:18.04' \ 'fedora:30' \ 'opensuse/leap:15.1' \ 'debian:9' \ 'debian:10' \ 'centos:7' \ ) install_packages() { for i in "${OS_DISTRIBUTION[@]}"; do echo "Test OBS packages for ${OS_DISTRIBUTION}" run_test "${i}" "${DOCKERFILE_PATH}" remove_image_and_dockerfile "${i}" "${DOCKERFILE_PATH}" done } run_test() { local OS_DISTRIBUTION=${1:-} local DOCKERFILE_PATH=${2:-} generate_dockerfile "${OS_DISTRIBUTION}" "${DOCKERFILE_PATH}" build_dockerfile "${OS_DISTRIBUTION}" "${DOCKERFILE_PATH}" } generate_dockerfile() { local OS_DISTRIBUTION=${1:-} local DOCKERFILE_PATH=${2:-} DISTRIBUTION_NAME=$(echo "${OS_DISTRIBUTION}" | cut -d ':' -f1) case "${DISTRIBUTION_NAME}" in centos) UPDATE="yum -y update" DEPENDENCIES="yum install -y curl git gnupg2 lsb-release sudo" ;; debian|ubuntu) UPDATE="apt-get -y update" DEPENDENCIES="apt-get --no-install-recommends install -y apt-utils ca-certificates curl git gnupg2 lsb-release sudo" ;; fedora) UPDATE="dnf -y update" DEPENDENCIES="dnf install -y curl git gnupg2 sudo" ;; opensuse/leap) UPDATE="zypper -n refresh" DEPENDENCIES="zypper -n install curl git gnupg sudo" esac echo "Building dockerfile for ${OS_DISTRIBUTION}" sed \ -e "s|@OS_DISTRIBUTION@|${OS_DISTRIBUTION}|g" \ -e "s|@UPDATE@|${UPDATE}|g" \ -e "s|@DEPENDENCIES@|${DEPENDENCIES}|g" \ "${DOCKERFILE_PATH}/Dockerfile.in" > "${DOCKERFILE_PATH}"/Dockerfile } build_dockerfile() { local OS_DISTRIBUTION=${1:-} local DOCKERFILE_PATH=${2:-} pushd "${DOCKERFILE_PATH}" sudo docker build \ --build-arg http_proxy="${http_proxy}" \ --build-arg https_proxy="${https_proxy}" \ --tag "obs-kata-test-${OS_DISTRIBUTION}" . popd } remove_image_and_dockerfile() { local OS_DISTRIBUTION=${1:-} local DOCKERFILE_PATH=${2:-} echo "Removing image test-${OS_DISTRIBUTION}" sudo docker rmi "obs-kata-test-${OS_DISTRIBUTION}" echo "Removing dockerfile" sudo rm -f "${DOCKERFILE_PATH}/Dockerfile" } function main() { echo "Run OBS testing" install_packages } main "$@"
#include <iostream> #include <type_traits> // Function overload for lvalue references template <typename T> void print(const T& t) { static_assert(!std::is_rvalue_reference<T>::value, "Invalid overload for rvalue references"); std::cout << "Lvalue reference: " << t << std::endl; } // Function overload for rvalue references void print(int&& t) { std::cout << "Rvalue reference: " << t << std::endl; } int main() { int x = 5; print(x); // Calls the lvalue reference overload print(10); // Calls the rvalue reference overload return 0; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test.transports; /** * An Exception Class used to identify exceptions that occur at the Transport Layer * within a dialog. * * @author TransCore ITS */ public class TransportException extends Exception { public static String PARAMETER_ERROR_TYPE = "MISSING PARAMETER ERROR"; public static String GENERAL_ERROR_TYPE = "GENERAL ERROR"; public static String TIMEOUT_ERROR_TYPE = "TIMEOUT ERROR"; public static String PROTOCOL_ERROR_TYPE = "PROTOCOL ERROR"; public static String LOGIN_ERROR_TYPE = "LOGIN ERROR"; public static String CONNECTION_ERROR_TYPE = "CONNECTION ERROR"; private String errorType=""; public TransportException(){ super(); } public TransportException(String message){ super(message); } public TransportException(String message, String errorType){ super(message); this.errorType = errorType; } public String getExceptionErrorType() { return errorType; } }
/* * File : ThreeIntervalsKE.java * Created : 15-Apr-2010 * By : atrilla * * Emolib - Emotional Library * * Copyright (c) 2010 <NAME> & * 2007-2012 Enginyeria i Arquitectura La Salle (Universitat Ramon Llull) * * This file is part of Emolib. * * You should have received a copy of the rights granted with this * distribution of EmoLib. See COPYING. */ package emolib.classifier.heuristic; import emolib.classifier.Classifier; import emolib.classifier.FeatureBox; /** * The <i>ThreeIntervalsKE</i> is a heuristic rules-based classifier * operating on the circumplex with sentiments. * * <p> * This class works exactly as the Five Intervals heuristic rules classifier, * but displays the sentiment corresponding to the predicted emotion. * </p> * * @see emolib.classifier.heuristic.FiveIntervalsKE FiveIntervalsKE * * @author <NAME> (<EMAIL>) */ public class ThreeIntervalsKE extends Classifier { // A Five intervals heuristic rules classifier private FiveIntervalsKE fiveKE; /** * Main constructor of this neuristic rules classifier. */ public ThreeIntervalsKE() { fiveKE = new FiveIntervalsKE(); } /* (non-Javadoc) * @see emolib.classifier.Classifier#getCategory(emolib.classifier.FeatureBox) */ public String getCategory(FeatureBox inputFeatures) { String category = ""; category = fiveKE.getCategory(inputFeatures); if (category.equals("surprise") || category.equals("happiness")) { category = "P"; } else if (category.equals("sorrow") || category.equals("anger") || category.equals("fear")) { category = "N"; } return category; } /** * Void method to train required by the Classifier class. */ /* (non-Javadoc) * @see emolib.classifier.Classifier#trainingProcedure() */ public void trainingProcedure() { } /* (non-Javadoc) * @see emolib.classifier.Classifier#save(java.lang.String) */ public void save(String path) { } /* (non-Javadoc) * @see emolib.classifier.Classifier#load(java.lang.String) */ public void load(String path) { } }
use crate::crypto_library::{Fq, G1, AffineG1}; fn process_words(words: &[&str]) -> Option<G1> { let x1 = Fq::from_slice(words[2]).ok()?; let y1 = Fq::from_slice(words[3]).ok()?; let p1 = if x1 == Fq::zero() && y1 == Fq::zero() { G1::zero() } else { AffineG1::new(x1, y1).ok()?.into() }; Some(p1) }
def bubble_sort(array): for i in range(len(array)): for j in range(i + 1, len(array)): if array[i] > array[j]: array[i], array[j] = array[j], array[i] return array arr = [5, 3, 1, 4, 7] sorted_arr = bubble_sort(arr) print(sorted_arr)
#!/bin/bash installDirectory=~/Library/Developer/Xcode/UserData mkdir -p "${installDirectory}" cp -R "CodeSnippets" "${installDirectory}"
#!/bin/bash # This script runs all tests in glow, including onnxifi gtests set -euxo pipefail export GLOW_SRC=$PWD export GLOW_BUILD_DIR=${GLOW_SRC}/build export LOADER=${GLOW_BUILD_DIR}/bin/image-classifier export LSAN_OPTIONS="suppressions=$GLOW_SRC/.circleci/suppressions.txt" export ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer export IMAGES_DIR=${GLOW_SRC}/tests/images/ # Pass in which tests to run (one of {test, test_unopt}). run_unit_tests() { CTEST_PARALLEL_LEVEL=4 ninja "${1}" || ( cat Testing/Temporary/LastTest.log && exit 1 ) } run_and_check_lenet_mnist_bundle() { for q in "" "quantized_" do cd "${GLOW_BUILD_DIR}/bundles/${q}lenet_mnist/" rm -f raw_results.txt for f in ${IMAGES_DIR}/mnist/* do # Assume that there is only one file with this format (prepended with Quantized or not) ./*LeNetMnistBundle ${f} | grep "Result: " >> raw_results.txt done diff raw_results.txt "${GLOW_SRC}/.ci/lenet_mnist_expected_output.txt" cd - done } run_and_check_resnet50_bundle() { for q in "" "quantized_" do cd "${GLOW_BUILD_DIR}/bundles/${q}resnet50/" rm -f raw_results.txt for f in ${IMAGES_DIR}/imagenet/* do # Assume that there is only one file with this format (prepended with Quantized or not) ./*ResNet50Bundle ${f} | grep "Result: " >> raw_results.txt done diff raw_results.txt "${GLOW_SRC}/.ci/resnet50_expected_output.txt" cd - done } # Run unit tests and bundle tests. cd "${GLOW_BUILD_DIR}" case ${CIRCLE_JOB} in ASAN) # ASAN is not enabled in onnx, therefore we should skip it for now. # TODO: Enable ASAN test. run_unit_tests check ;; TSAN) # Run only Glow tests. run_unit_tests check ;; DEBUG) run_unit_tests check run_unit_tests test_unopt ;; SHARED) # No tests with shared libs; it's similar to DEBUG. ;; RELEASE_WITH_EXPENSIVE_TESTS) run_unit_tests check_expensive run_and_check_lenet_mnist_bundle run_and_check_resnet50_bundle ;; COVERAGE) cd "${GLOW_SRC}" cd build ../.circleci/run_coverage.sh ;; CHECK_CLANG_FORMAT) cd "${GLOW_SRC}" sudo ln -s /usr/bin/clang-format-7 /usr/bin/clang-format ./utils/format.sh check ;; *) echo "Error, '${CIRCLE_JOB}' not valid mode; Must be one of {ASAN, TSAN, DEBUG, SHARED, RELEASE_WITH_EXPENSIVE_TESTS}." exit 1 ;; esac
#!/usr/bin/env bash cd "$(dirname "${BASH_SOURCE[0]}")" \ || exit 1 # ------------------------------------------------------------------------------ shellcheck \ ../**/*.sh ../*.tmux
#!/bin/sh echo "Execution is being started" echo "**************************" jmeter $@ echo "**************************" echo "Execution has been completed, please check the artifacts to download the results."
<gh_stars>100-1000 interface Props { /** * Component's HTML Element * * @default 'div' */ component?: string; /** * App theme. If set to `'parent'` it will look for `ios` or `md` class on root `<html>` element, useful to use with parent framework like Framework7 or Ionic * * @default 'material' */ theme?: 'ios' | 'material' | 'parent'; /** * Include `dark:` variants (if dark theme is in use) * * @default false * */ dark?: boolean; /** * Enables touch ripple effect in Material theme. Allows to globally disable touch ripple for all components * * @default true */ touchRipple?: boolean; /** * Adds `safe-areas` class to the container. Should be enabled if app container is the full screen element to properly handle screen safe areas * * @default true */ safeAreas?: boolean; }
/* Slider Container */ .testimonial-slider { position: relative; width: 90%; margin: 0 auto; overflow: hidden; } /* Slides */ .testimonials { display: flex; flex-direction: row; width: 100%; padding: 0; white-space: nowrap; height: 100%; } .testimonials li { flex: 0 0 auto; list-style: none; width: 90%; margin: 0 auto; padding-top: 15px; padding-bottom: 15px; border-radius: 10px; background-color: #DCDCDC; } /* Function to adjust widths of slides */ @keyframes moveSlide { 0% {transform:translateX(0%);} 100% {transform:translateX(-100%);} } /* Slider Controls */ .controls { text-align: center; position: absolute; bottom: 10px; width: 80%; z-index: 200; margin: 0 auto; } .next { float: right; cursor: pointer; } .prev { float: left; cursor: pointer; } /* Content Inside Slides */ .testimonial { font-size: 1.2rem; font-style: italic; color: #666; font-family: sans-serif; padding-right: 10px; padding-left: 10px; word-wrap: break-word} /* Testimonials */ .testimonials li { animation-name: moveSlide; animation-duration: 10s; animation-iteration-count: infinite; } .testimonials .author { font-weight: bold; font-size: 1.2rem; } <div class="testimonial-slider"> <ul class="testimonials"> <li> <p class="testimonial"> <span class="author">John Doe: </span>I had a great experience using your service. It was so easy and efficient. </p> </li> <li> <p class="testimonial"> <span class="author">Jane Doe: </span>Your team was really helpful and responsive. I would definitely recommend it to others. </p> </li> </ul> <div class="controls"> <span class="prev">&#8592;</span> <span class="next">&#8594;</span> </div> </div>
<reponame>vsemionov/solar-space /* * Copyright (C) 2003-2011 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. */ #ifndef TEXT_H #define TEXT_H #include <ft2build.h> #include <freetype/freetype.h> #include <freetype/ftglyph.h> #include <freetype/ftoutln.h> #include <freetype/fttrigon.h> #include "Defs.h" #define NUM_CHARS 128 typedef FT_Error (*ptr_FT_Init_FreeType)(FT_Library *); typedef FT_Error (*ptr_FT_Done_FreeType)(FT_Library); typedef FT_Error (*ptr_FT_New_Face)(FT_Library, const char *, FT_Long, FT_Face *); typedef FT_Error (*ptr_FT_Done_Face)(FT_Face); typedef FT_Error (*ptr_FT_Set_Char_Size)(FT_Face, FT_F26Dot6, FT_F26Dot6, FT_UInt, FT_UInt); typedef FT_UInt (*ptr_FT_Get_Char_Index)(FT_Face, FT_ULong); typedef FT_Error (*ptr_FT_Load_Glyph)(FT_Face, FT_UInt, FT_Int32); typedef void (*ptr_FT_Done_Glyph)(FT_Glyph); typedef FT_Error (*ptr_FT_Get_Glyph)(FT_GlyphSlot, FT_Glyph *); typedef FT_Error (*ptr_FT_Glyph_To_Bitmap)(FT_Glyph *, FT_Render_Mode, FT_Vector *, FT_Bool); class CText { public: CText(); virtual ~CText(); bool BuildOutlineFont(const char *name, int size, bool bold, bool italic, bool underline, bool strikeout, float thickness); static bool Init(); static void Shutdown(); void Free(); bool BuildFTFont(const char *name, int size); void Print(const char *fmt, ...); bool GetTextSize(const char *text, float *width, float *height); private: void Construct(); static bool MakeFTChar(FT_Face face, char ch, int list_base, int textures[NUM_CHARS], float charsizes[NUM_CHARS][2], bool mipmaps); static int next_p2 (int a); bool UseFT; bool loaded; int listbase; float charsize[NUM_CHARS][2]; float charheight; int FT_tex[NUM_CHARS]; float sizescale; // FreeType functions: static bool FreeType_loaded; static HMODULE FreeType; static ptr_FT_Init_FreeType pFT_Init_FreeType; static ptr_FT_Done_FreeType pFT_Done_FreeType; static ptr_FT_New_Face pFT_New_Face; static ptr_FT_Done_Face pFT_Done_Face; static ptr_FT_Set_Char_Size pFT_Set_Char_Size; static ptr_FT_Get_Char_Index pFT_Get_Char_Index; static ptr_FT_Load_Glyph pFT_Load_Glyph; static ptr_FT_Done_Glyph pFT_Done_Glyph; static ptr_FT_Get_Glyph pFT_Get_Glyph; static ptr_FT_Glyph_To_Bitmap pFT_Glyph_To_Bitmap; }; #endif
#!/bin/bash # SPDX-License-Identifier: Apache-2.0 # Copyright (C) 2021 The LineageOS Project set -e # Load extract_utils and do some sanity checks MY_DIR="${BASH_SOURCE%/*}" if [[ ! -d "${MY_DIR}" ]]; then MY_DIR="${PWD}"; fi ANDROID_ROOT="${MY_DIR}/../../.." HELPER="${ANDROID_ROOT}/tools/extract-utils/extract_utils.sh" if [ ! -f "${HELPER}" ]; then echo "Unable to find helper script at ${HELPER}" exit 1 fi source "${HELPER}" # Initialize the helper for common setup_vendor "${DEVICE_COMMON}" "${VENDOR}" "${ANDROID_ROOT}" true # Warning headers and guards # Copyright headers and guards write_headers "crownlte star2lte starlte" # The standard common blobs write_makefiles "${MY_DIR}/proprietary-files.txt" true # Finish write_footers if [ -s "${MY_DIR}/../${DEVICE}/proprietary-files.txt" ]; then # Reinitialize the helper for device setup_vendor "${DEVICE}" "${VENDOR}" "${ANDROID_ROOT}" false # Warning headers and guards write_headers # The standard device blobs write_makefiles "${MY_DIR}/../${DEVICE}/proprietary-files.txt" true # Finish write_footers fi
<reponame>yandong2023/The-sword-pointing-to-offer-code<gh_stars>1-10 ''' Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): if not head and n <= 0: return None pNode = ListNode(0) pNode.next = head first, second = pNode, pNode for i in range(n): if first.next: first = first.next else: return None while first.next: first = first.next second = second.next second.next = second.next.next return pNode.next
#!/bin/bash source /opt/intel/compilers_and_libraries/linux/bin/compilervars.sh intel64 #export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/lirui/oneDNN/install/lib sleep 10 #icpc -Ofast -DTOTITER=10 -O3 -axAVX,CORE-AVX2 -mavx2 -qopenmp -march=native --std=c++11 -I/home/lirui/oneDNN/install/include -L/home/lirui/oneDNN/install/lib -L/opt/local/lib ./oneDNN_cnn.cpp -o oneDNNrun -Wl,-rpath=/opt/local/lib -ldnnl #icpc -Ofast -DTOTITER=10 -O3 -axAVX,CORE-AVX2 -mavx2 -qopenmp -march=native --std=c++11 -I/home/lirui/oneDNN/install/include -L/home/lirui/oneDNN/install/lib -L/opt/local/lib ./oneDNN_cnn_wino.cpp -o oneDNNrun_wino -Wl,-rpath=/opt/local/lib -ldnnl input="./sweep_test_cases.txt" while IFS= read -r line do echo "$line" export OMP_NUM_THREADS=1 python main.py $line 16 16 16 > "myresults_16-16-16/ourthreads$OMP_NUM_THREADS.cnn$line.out" done < "$input" # while IFS= read -r line # do # echo "$line" # export OMP_NUM_THREADS=8 # ./oneDNNrun $line > "results/threads$OMP_NUM_THREADS.cnn$line.out" # done < "$input" # while IFS= read -r line # do # echo "$line" # export OMP_NUM_THREADS=1 # ./oneDNNrun_wino $line > "results/wino_threads$OMP_NUM_THREADS.cnn$line.out" # done < "$input" # while IFS= read -r line # do # echo "$line" # export OMP_NUM_THREADS=8 # ./oneDNNrun_wino $line > "results/wino_threads$OMP_NUM_THREADS.cnn$line.out" # done < "$input"
import requests from bs4 import BeautifulSoup def parse_html(url): # Send a get request response = requests.get(url) # Create a BeautifulSoup object soup = BeautifulSoup(response.text, 'lxml') # Find the required data data = soup.find_all('div', class_='content') # Return the data return data
from .component import Component from threading import Thread import logging class ObserverComponent(Component): def __init__(self, **kwargs): super().__init__(**kwargs) self.feature_name = None self.property_name = None self.property_config = None def init_observer(self, feature_name, property_name, property_config): self.feature_name = feature_name self.property_name = property_name self.property_config = property_config def update_property(self, new_value): self.connector.update_property(self.thing_id, self.feature_name, self.property_name, new_value) def start_observe(self, **kwargs): logging.info("Start observer for " + self.feature_name + "/" + self.property_name) thread = Thread(target=self.observe, kwargs=kwargs) thread.daemon = True thread.start() def observe(self, **kwargs): raise NotImplementedError @staticmethod def configure_observer(): raise NotImplementedError
import random class GridGenerator: def __init__(self): self.grid = None self.colors = ['green', 'purple', 'orange'] def generate_grid(self, width, height): self.grid = [['wall' for _ in range(width + 2)] for _ in range(height + 2)] # Initialize grid with walls for i in range(1, height + 1): for j in range(1, width + 1): self.grid[i][j] = random.choice(self.colors) # Assign random color to non-wall cells return self.grid
import { RichUtils, Modifier, EditorState, AtomicBlockUtils } from 'draft-js'; import { INLINE_STYLES } from '../const'; export const { getCurrentBlockType, currentBlockContainsLink, toggleBlockType, toggleLink, } = RichUtils; export const { undo, redo, forceSelection } = EditorState; export function isImageSelected(editorState) { return !!getSelectedImage(editorState).key; } export function addImage(editorState, options) { const { url } = options; const entity = createEntity(editorState, { type: 'IMAGE', mutability: 'IMMUTABLE', src: url, }); const entityKey = entity.getLastCreatedEntityKey(); editorState = AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, ' '); return forceSelection( editorState, editorState.getCurrentContent().getSelectionAfter() ); } export function addLink(editorState, options) { const { selection, url } = options; const entity = createEntity(editorState, { type: 'LINK', mutability: 'MUTABLE', url, }); const entityKey = entity.getLastCreatedEntityKey(); return toggleLink(editorState, selection, entityKey); } export function canUndo(editorState) { return !editorState.getUndoStack().isEmpty(); } export function getSelectedAlignment(editorState) { const { entity } = getSelectedImage(editorState); if (entity) { return entity.getData().alignment || 'default'; } else { const block = getSelectedBlock(editorState); return block.getData().get('alignment') || 'left'; } } export function setAlignment(editorState, alignment) { const selection = editorState.getSelection(); const content = editorState.getCurrentContent(); const { key } = getSelectedImage(editorState); if (key) { content.mergeEntityData(key, { alignment }); return forceSelection(editorState, selection); } else { const aligned = Modifier.mergeBlockData(content, selection, { alignment, }); return EditorState.push(editorState, aligned, 'change-block-data'); } } export function canRedo(editorState) { return !editorState.getRedoStack().isEmpty(); } export function handleKeyCommand(editorState, command) { const style = command.toUpperCase(); if (INLINE_STYLES.includes(style)) { return toggleInlineStyle(editorState, style); } return RichUtils.handleKeyCommand(editorState, command); } export function toggleInlineStyle(editorState, style) { if (!hasOverlappingRanges(editorState, style)) { return RichUtils.toggleInlineStyle(editorState, style); } } // Returns true if the current selection range is entirely // contained by the given style. export function hasCurrentInlineStyle(editorState, style) { return editorState.getCurrentInlineStyle().has(style); } export function canToggleInlineStyle(editorState, style) { return !hasOverlappingRanges(editorState, style); } // Returns true if the current selection range has any style // ranges that are not completely contained by it. function hasOverlappingRanges(editorState, style) { const selection = editorState.getSelection(); if (selection.isCollapsed()) { return false; } else { const edges = getSelectionEdges(editorState, selection); return edges.some((edge) => { const { block, start: edgeStart, end: edgeEnd } = edge; const styledRanges = getBlockStyledRanges(block, (styleMap) => { return styleMap.size > 0 && !styleMap.has(style); }); return styledRanges.some((styledRange) => { const { start, end } = styledRange; const isBefore = start <= edgeStart && end <= edgeStart; const isAfter = start >= edgeEnd && end >= edgeEnd; const isSurrounding = start <= edgeStart && end >= edgeEnd; const isContained = start >= edgeStart && end <= edgeEnd; return !isBefore && !isAfter && !isSurrounding && !isContained; }); }); } } function getBlockStyledRanges(block, fn) { const ranges = []; block.findStyleRanges( (metadata) => { const styleMap = metadata.getStyle(); if (styleMap.size === 0) { return false; } return fn(styleMap); }, (start, end) => { ranges.push({ start, end }); } ); return ranges; } function getSelectionEdges(editorState, selection) { const content = editorState.getCurrentContent(); const startBlock = content.getBlockForKey(selection.getStartKey()); const endBlock = content.getBlockForKey(selection.getEndKey()); const start = selection.getStartOffset(); const end = selection.getEndOffset(); if (startBlock === endBlock) { return [{ block: startBlock, start, end }]; } else { return [ { start, end: startBlock.getLength(), block: startBlock, }, { start: 0, end, block: endBlock, }, ]; } } function createEntity(editorState, options) { const { type, mutability, ...data } = options; return editorState.getCurrentContent().createEntity(type, mutability, data); } function getSelectedImage(editorState) { const key = getSelectedEntityKey(editorState); if (key) { const content = editorState.getCurrentContent(); const entity = content.getEntity(key); if (entity?.getType() === 'IMAGE') { return { entity, key }; } } return {}; } function getSelectedEntityKey(editorState) { const block = getSelectedBlock(editorState); if (block) { return block.getEntityAt(editorState.getSelection().getAnchorOffset()); } } function getSelectedBlock(editorState) { const selection = editorState.getSelection(); const blockKey = selection.getAnchorKey(); if (blockKey) { const content = editorState.getCurrentContent(); return content.getBlockForKey(blockKey); } }
package procs import ( "context" "fmt" tikvKey "github.com/tikv/client-go/key" "github.com/tikv/client-go/txnkv" tikvKv "github.com/tikv/client-go/txnkv/kv" "github.com/vmihailenco/msgpack" "tikv-browser/internal/service" "tikv-browser/pkg/utils" ) func tikvSearchRange(client *txnkv.Client, lowerBound []byte, limit int) ([][]byte, error) { tx, err := client.Begin(context.TODO()) if err != nil { return nil, err } tikvLowerBound := tikvKey.Key(lowerBound) it, err := tx.Iter(context.TODO(), tikvLowerBound, nil) if err != nil { return nil, err } defer it.Close() keys := [][]byte{} for count := 0; it.Valid() && count < limit; { keys = append(keys, it.Key()[:]) count++ it.Next(context.TODO()) } return keys, nil } func tikvSearchPrefix(client *txnkv.Client, prefix []byte, limit int) ([][]byte, error) { tx, err := client.Begin(context.TODO()) if err != nil { return nil, err } tikvPrefix := tikvKey.Key(prefix) it, err := tx.Iter(context.TODO(), tikvPrefix, nil) if err != nil { return nil, err } defer it.Close() keys := [][]byte{} for count := 0; it.Valid() && count < limit; { if !it.Key().HasPrefix(tikvPrefix) { break } keys = append(keys, it.Key()[:]) count++ it.Next(context.TODO()) } return keys, nil } func tikvSearchWhole(client *txnkv.Client, key []byte) (bool, error) { tx, err := client.Begin(context.TODO()) if err != nil { return false, err } _, err = tx.Get(context.TODO(), key) if err != nil { if tikvKv.IsErrNotFound(err) { return false, nil } return false, err } return true, nil } func tikvSearch(inputBytes []byte) ([]byte, error) { type InputMessage struct { Endpoints []string `msgpack:"endpoints"` Mode string `msgpack:"mode"` Encoding string `msgpack:"encoding"` Contents string `msgpack:"contents"` Limit int `msgpack:"limit"` } type OutputMessage = [][]byte var inputMessage InputMessage if err := msgpack.Unmarshal(inputBytes, &inputMessage); err != nil { return nil, err } contents, err := func() ([]byte, error) { switch inputMessage.Encoding { case "utf8": { return []byte(inputMessage.Contents), nil } case "hex": { return utils.HexToBytes(inputMessage.Contents) } case "base64": { return utils.Base64ToBytes(inputMessage.Contents) } } return nil, fmt.Errorf("invalid encoding: %v", inputMessage.Encoding) }() if err != nil { return nil, err } var callbackErr error var outputMessage OutputMessage service.UseTikvClient(inputMessage.Endpoints, func(client *txnkv.Client, err error) { if err != nil { callbackErr = err return } switch inputMessage.Mode { case "scan": { outputMessage, callbackErr = tikvSearchRange(client, contents, inputMessage.Limit) } case "prefix": { outputMessage, callbackErr = tikvSearchPrefix(client, contents, inputMessage.Limit) } case "whole": { found, err := tikvSearchWhole(client, contents) callbackErr = err if found { outputMessage = [][]byte{contents} } } default: { callbackErr = fmt.Errorf("invalid mode: %v", inputMessage.Mode) } } }) if callbackErr != nil { return nil, callbackErr } return msgpack.Marshal(&outputMessage) } func tikvGet(inputBytes []byte) ([]byte, error) { type InputMessage struct { Endpoints []string `msgpack:"endpoints"` Keys [][]byte `msgpack:"keys"` } type Row struct { Key []byte `msgpack:"key"` Value []byte `msgpack:"value"` } type OutputMessge struct { Rows []Row `msgpack:"rows"` } var inputMessage InputMessage if err := msgpack.Unmarshal(inputBytes, &inputMessage); err != nil { return nil, err } var callbackErr error outputMessage := OutputMessge{} service.UseTikvClient(inputMessage.Endpoints, func(client *txnkv.Client, err error) { if err != nil { callbackErr = err return } tx, err := client.Begin(context.TODO()) if err != nil { callbackErr = err return } for _, key := range inputMessage.Keys { value, err := tx.Get(context.TODO(), tikvKey.Key(key)) if err != nil { service.GetLogger().Info(err) continue } row := Row{Key: key, Value: value} outputMessage.Rows = append(outputMessage.Rows, row) } }) if callbackErr != nil { return nil, callbackErr } return msgpack.Marshal(&outputMessage) } func init() { addProc("/tikv/search", tikvSearch) addProc("/tikv/get", tikvGet) }
#!/bin/bash #creates vols.txt file for use with del-vols.sh #separate file to make sure operator is confident they want to delete all these volumes #-could have put in del-vols.txt, but risk is delete wanted volumes # ./desc-vols.sh |awk '{print $1}' > vols.txt
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/dashboard/v1/layouts.proto package com.google.monitoring.dashboard.v1; /** * * * <pre> * A basic layout divides the available space into vertical columns of equal * width and arranges a list of widgets using a row-first strategy. * </pre> * * Protobuf type {@code google.monitoring.dashboard.v1.GridLayout} */ public final class GridLayout extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.monitoring.dashboard.v1.GridLayout) GridLayoutOrBuilder { private static final long serialVersionUID = 0L; // Use GridLayout.newBuilder() to construct. private GridLayout(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GridLayout() { widgets_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GridLayout(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private GridLayout( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { columns_ = input.readInt64(); break; } case 18: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { widgets_ = new java.util.ArrayList<com.google.monitoring.dashboard.v1.Widget>(); mutable_bitField0_ |= 0x00000001; } widgets_.add( input.readMessage( com.google.monitoring.dashboard.v1.Widget.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { widgets_ = java.util.Collections.unmodifiableList(widgets_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.dashboard.v1.LayoutsProto .internal_static_google_monitoring_dashboard_v1_GridLayout_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.dashboard.v1.LayoutsProto .internal_static_google_monitoring_dashboard_v1_GridLayout_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.dashboard.v1.GridLayout.class, com.google.monitoring.dashboard.v1.GridLayout.Builder.class); } public static final int COLUMNS_FIELD_NUMBER = 1; private long columns_; /** * * * <pre> * The number of columns into which the view's width is divided. If omitted * or set to zero, a system default will be used while rendering. * </pre> * * <code>int64 columns = 1;</code> * * @return The columns. */ public long getColumns() { return columns_; } public static final int WIDGETS_FIELD_NUMBER = 2; private java.util.List<com.google.monitoring.dashboard.v1.Widget> widgets_; /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public java.util.List<com.google.monitoring.dashboard.v1.Widget> getWidgetsList() { return widgets_; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public java.util.List<? extends com.google.monitoring.dashboard.v1.WidgetOrBuilder> getWidgetsOrBuilderList() { return widgets_; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public int getWidgetsCount() { return widgets_.size(); } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public com.google.monitoring.dashboard.v1.Widget getWidgets(int index) { return widgets_.get(index); } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public com.google.monitoring.dashboard.v1.WidgetOrBuilder getWidgetsOrBuilder(int index) { return widgets_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (columns_ != 0L) { output.writeInt64(1, columns_); } for (int i = 0; i < widgets_.size(); i++) { output.writeMessage(2, widgets_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (columns_ != 0L) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, columns_); } for (int i = 0; i < widgets_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, widgets_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.monitoring.dashboard.v1.GridLayout)) { return super.equals(obj); } com.google.monitoring.dashboard.v1.GridLayout other = (com.google.monitoring.dashboard.v1.GridLayout) obj; if (getColumns() != other.getColumns()) return false; if (!getWidgetsList().equals(other.getWidgetsList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + COLUMNS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getColumns()); if (getWidgetsCount() > 0) { hash = (37 * hash) + WIDGETS_FIELD_NUMBER; hash = (53 * hash) + getWidgetsList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.monitoring.dashboard.v1.GridLayout parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.monitoring.dashboard.v1.GridLayout parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.monitoring.dashboard.v1.GridLayout parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.monitoring.dashboard.v1.GridLayout prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A basic layout divides the available space into vertical columns of equal * width and arranges a list of widgets using a row-first strategy. * </pre> * * Protobuf type {@code google.monitoring.dashboard.v1.GridLayout} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.monitoring.dashboard.v1.GridLayout) com.google.monitoring.dashboard.v1.GridLayoutOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.monitoring.dashboard.v1.LayoutsProto .internal_static_google_monitoring_dashboard_v1_GridLayout_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.monitoring.dashboard.v1.LayoutsProto .internal_static_google_monitoring_dashboard_v1_GridLayout_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.monitoring.dashboard.v1.GridLayout.class, com.google.monitoring.dashboard.v1.GridLayout.Builder.class); } // Construct using com.google.monitoring.dashboard.v1.GridLayout.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getWidgetsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); columns_ = 0L; if (widgetsBuilder_ == null) { widgets_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { widgetsBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.monitoring.dashboard.v1.LayoutsProto .internal_static_google_monitoring_dashboard_v1_GridLayout_descriptor; } @java.lang.Override public com.google.monitoring.dashboard.v1.GridLayout getDefaultInstanceForType() { return com.google.monitoring.dashboard.v1.GridLayout.getDefaultInstance(); } @java.lang.Override public com.google.monitoring.dashboard.v1.GridLayout build() { com.google.monitoring.dashboard.v1.GridLayout result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.monitoring.dashboard.v1.GridLayout buildPartial() { com.google.monitoring.dashboard.v1.GridLayout result = new com.google.monitoring.dashboard.v1.GridLayout(this); int from_bitField0_ = bitField0_; result.columns_ = columns_; if (widgetsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { widgets_ = java.util.Collections.unmodifiableList(widgets_); bitField0_ = (bitField0_ & ~0x00000001); } result.widgets_ = widgets_; } else { result.widgets_ = widgetsBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.monitoring.dashboard.v1.GridLayout) { return mergeFrom((com.google.monitoring.dashboard.v1.GridLayout) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.monitoring.dashboard.v1.GridLayout other) { if (other == com.google.monitoring.dashboard.v1.GridLayout.getDefaultInstance()) return this; if (other.getColumns() != 0L) { setColumns(other.getColumns()); } if (widgetsBuilder_ == null) { if (!other.widgets_.isEmpty()) { if (widgets_.isEmpty()) { widgets_ = other.widgets_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureWidgetsIsMutable(); widgets_.addAll(other.widgets_); } onChanged(); } } else { if (!other.widgets_.isEmpty()) { if (widgetsBuilder_.isEmpty()) { widgetsBuilder_.dispose(); widgetsBuilder_ = null; widgets_ = other.widgets_; bitField0_ = (bitField0_ & ~0x00000001); widgetsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getWidgetsFieldBuilder() : null; } else { widgetsBuilder_.addAllMessages(other.widgets_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.monitoring.dashboard.v1.GridLayout parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.monitoring.dashboard.v1.GridLayout) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long columns_; /** * * * <pre> * The number of columns into which the view's width is divided. If omitted * or set to zero, a system default will be used while rendering. * </pre> * * <code>int64 columns = 1;</code> * * @return The columns. */ public long getColumns() { return columns_; } /** * * * <pre> * The number of columns into which the view's width is divided. If omitted * or set to zero, a system default will be used while rendering. * </pre> * * <code>int64 columns = 1;</code> * * @param value The columns to set. * @return This builder for chaining. */ public Builder setColumns(long value) { columns_ = value; onChanged(); return this; } /** * * * <pre> * The number of columns into which the view's width is divided. If omitted * or set to zero, a system default will be used while rendering. * </pre> * * <code>int64 columns = 1;</code> * * @return This builder for chaining. */ public Builder clearColumns() { columns_ = 0L; onChanged(); return this; } private java.util.List<com.google.monitoring.dashboard.v1.Widget> widgets_ = java.util.Collections.emptyList(); private void ensureWidgetsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { widgets_ = new java.util.ArrayList<com.google.monitoring.dashboard.v1.Widget>(widgets_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.dashboard.v1.Widget, com.google.monitoring.dashboard.v1.Widget.Builder, com.google.monitoring.dashboard.v1.WidgetOrBuilder> widgetsBuilder_; /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public java.util.List<com.google.monitoring.dashboard.v1.Widget> getWidgetsList() { if (widgetsBuilder_ == null) { return java.util.Collections.unmodifiableList(widgets_); } else { return widgetsBuilder_.getMessageList(); } } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public int getWidgetsCount() { if (widgetsBuilder_ == null) { return widgets_.size(); } else { return widgetsBuilder_.getCount(); } } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public com.google.monitoring.dashboard.v1.Widget getWidgets(int index) { if (widgetsBuilder_ == null) { return widgets_.get(index); } else { return widgetsBuilder_.getMessage(index); } } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder setWidgets(int index, com.google.monitoring.dashboard.v1.Widget value) { if (widgetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWidgetsIsMutable(); widgets_.set(index, value); onChanged(); } else { widgetsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder setWidgets( int index, com.google.monitoring.dashboard.v1.Widget.Builder builderForValue) { if (widgetsBuilder_ == null) { ensureWidgetsIsMutable(); widgets_.set(index, builderForValue.build()); onChanged(); } else { widgetsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder addWidgets(com.google.monitoring.dashboard.v1.Widget value) { if (widgetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWidgetsIsMutable(); widgets_.add(value); onChanged(); } else { widgetsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder addWidgets(int index, com.google.monitoring.dashboard.v1.Widget value) { if (widgetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWidgetsIsMutable(); widgets_.add(index, value); onChanged(); } else { widgetsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder addWidgets(com.google.monitoring.dashboard.v1.Widget.Builder builderForValue) { if (widgetsBuilder_ == null) { ensureWidgetsIsMutable(); widgets_.add(builderForValue.build()); onChanged(); } else { widgetsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder addWidgets( int index, com.google.monitoring.dashboard.v1.Widget.Builder builderForValue) { if (widgetsBuilder_ == null) { ensureWidgetsIsMutable(); widgets_.add(index, builderForValue.build()); onChanged(); } else { widgetsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder addAllWidgets( java.lang.Iterable<? extends com.google.monitoring.dashboard.v1.Widget> values) { if (widgetsBuilder_ == null) { ensureWidgetsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, widgets_); onChanged(); } else { widgetsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder clearWidgets() { if (widgetsBuilder_ == null) { widgets_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { widgetsBuilder_.clear(); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public Builder removeWidgets(int index) { if (widgetsBuilder_ == null) { ensureWidgetsIsMutable(); widgets_.remove(index); onChanged(); } else { widgetsBuilder_.remove(index); } return this; } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public com.google.monitoring.dashboard.v1.Widget.Builder getWidgetsBuilder(int index) { return getWidgetsFieldBuilder().getBuilder(index); } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public com.google.monitoring.dashboard.v1.WidgetOrBuilder getWidgetsOrBuilder(int index) { if (widgetsBuilder_ == null) { return widgets_.get(index); } else { return widgetsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public java.util.List<? extends com.google.monitoring.dashboard.v1.WidgetOrBuilder> getWidgetsOrBuilderList() { if (widgetsBuilder_ != null) { return widgetsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(widgets_); } } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public com.google.monitoring.dashboard.v1.Widget.Builder addWidgetsBuilder() { return getWidgetsFieldBuilder() .addBuilder(com.google.monitoring.dashboard.v1.Widget.getDefaultInstance()); } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public com.google.monitoring.dashboard.v1.Widget.Builder addWidgetsBuilder(int index) { return getWidgetsFieldBuilder() .addBuilder(index, com.google.monitoring.dashboard.v1.Widget.getDefaultInstance()); } /** * * * <pre> * The informational elements that are arranged into the columns row-first. * </pre> * * <code>repeated .google.monitoring.dashboard.v1.Widget widgets = 2;</code> */ public java.util.List<com.google.monitoring.dashboard.v1.Widget.Builder> getWidgetsBuilderList() { return getWidgetsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.dashboard.v1.Widget, com.google.monitoring.dashboard.v1.Widget.Builder, com.google.monitoring.dashboard.v1.WidgetOrBuilder> getWidgetsFieldBuilder() { if (widgetsBuilder_ == null) { widgetsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.monitoring.dashboard.v1.Widget, com.google.monitoring.dashboard.v1.Widget.Builder, com.google.monitoring.dashboard.v1.WidgetOrBuilder>( widgets_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); widgets_ = null; } return widgetsBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.monitoring.dashboard.v1.GridLayout) } // @@protoc_insertion_point(class_scope:google.monitoring.dashboard.v1.GridLayout) private static final com.google.monitoring.dashboard.v1.GridLayout DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.monitoring.dashboard.v1.GridLayout(); } public static com.google.monitoring.dashboard.v1.GridLayout getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GridLayout> PARSER = new com.google.protobuf.AbstractParser<GridLayout>() { @java.lang.Override public GridLayout parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new GridLayout(input, extensionRegistry); } }; public static com.google.protobuf.Parser<GridLayout> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GridLayout> getParserForType() { return PARSER; } @java.lang.Override public com.google.monitoring.dashboard.v1.GridLayout getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
<filename>js/course.js /*global rg2:false */ (function () { function Course(data, isScoreCourse) { this.name = data.name; this.trackcount = 0; this.display = false; this.courseid = data.courseid; this.codes = data.codes; this.x = data.xpos; this.y = data.ypos; this.isScoreCourse = isScoreCourse; this.resultcount = 0; // save angle to next control to simplify later calculations this.angle = []; // save angle to show control code text this.textAngle = []; this.setAngles(); this.length = this.setLength(); } Course.prototype = { Constructor : Course, incrementTracksCount : function () { this.trackcount += 1; }, setLength : function () { var i, length, metresPerPixel; length = 0; metresPerPixel = rg2.events.getMetresPerPixel(); if ((metresPerPixel === undefined) || this.isScoreCourse) { return undefined; } for (i = 1; i < this.x.length; i += 1) { length += rg2.utils.getDistanceBetweenPoints(this.x[i], this.y[i], this.x[i - 1], this.y[i - 1]); } if (length === 0) { return undefined; } else { return (length * metresPerPixel / 1000).toFixed(1); } }, getLegLengths : function () { // used for events with no results to allow pro rata splits var i, distanceSoFar; distanceSoFar = []; if (this.isScoreCourse) { // arbitrary for now... distanceSoFar[1] = 1; return distanceSoFar; } distanceSoFar[0] = 0; for (i = 1; i < this.x.length; i += 1) { distanceSoFar[i] = parseInt(distanceSoFar[i-1] + rg2.utils.getDistanceBetweenPoints(this.x[i], this.y[i], this.x[i - 1], this.y[i - 1]), 0); } return distanceSoFar; }, setAngles : function () { var i, c1x, c1y, c2x, c2y, c3x, c3y; for (i = 0; i < (this.x.length - 1); i += 1) { if (this.isScoreCourse) { // align score event start triangle and controls upwards this.angle[i] = Math.PI * 1.5; this.textAngle[i] = Math.PI * 0.25; } else { // angle of line to next control this.angle[i] = rg2.utils.getAngle(this.x[i], this.y[i], this.x[i + 1], this.y[i + 1]); // create bisector of angle to position number c1x = Math.sin(this.angle[i - 1]); c1y = Math.cos(this.angle[i - 1]); c2x = Math.sin(this.angle[i]) + c1x; c2y = Math.cos(this.angle[i]) + c1y; c3x = c2x / 2; c3y = c2y / 2; this.textAngle[i] = rg2.utils.getAngle(c3x, c3y, c1x, c1y); } } // angle for finish aligns to north this.angle[this.x.length - 1] = Math.PI * 1.5; this.textAngle[this.x.length - 1] = Math.PI * 1.5; }, drawCourse : function (intensity) { var i, opt; if (this.display) { opt = rg2.getOverprintDetails(); rg2.ctx.globalAlpha = intensity; rg2.controls.drawStart(this.x[0], this.y[0], "", this.angle[0], opt); // don't join up controls for score events if (!this.isScoreCourse) { this.drawLinesBetweenControls({x: this.x, y: this.y}, this.angle, opt); } if (this.isScoreCourse) { for (i = 1; i < (this.x.length); i += 1) { if ((this.codes[i].indexOf('F') === 0) || (this.codes[i].indexOf('M') === 0)) { rg2.controls.drawFinish(this.x[i], this.y[i], "", opt); } else { rg2.controls.drawSingleControl(this.x[i], this.y[i], this.codes[i], this.textAngle[i], opt); } } } else { for (i = 1; i < (this.x.length - 1); i += 1) { rg2.controls.drawSingleControl(this.x[i], this.y[i], i, this.textAngle[i], opt); } rg2.controls.drawFinish(this.x[this.x.length - 1], this.y[this.y.length - 1], "", opt); } } }, drawLinesBetweenControls : function (pt, angle, opt) { var c1x, c1y, c2x, c2y, i, dist; for (i = 0; i < (pt.x.length - 1); i += 1) { if (i === 0) { dist = opt.startTriangleLength; } else { dist = opt.controlRadius; } c1x = pt.x[i] + (dist * Math.cos(angle[i])); c1y = pt.y[i] + (dist * Math.sin(angle[i])); //Assume the last control in the array is a finish if (i === this.x.length - 2) { dist = opt.finishOuterRadius; } else { dist = opt.controlRadius; } c2x = pt.x[i + 1] - (dist * Math.cos(angle[i])); c2y = pt.y[i + 1] - (dist * Math.sin(angle[i])); rg2.ctx.beginPath(); rg2.ctx.moveTo(c1x, c1y); rg2.ctx.lineTo(c2x, c2y); rg2.ctx.stroke(); } } }; rg2.Course = Course; }());
#!/usr/bin/env bash set -euf -o pipefail SELF_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" cd "$SELF_DIR/.." source "$SELF_DIR/common.sh" assertPython echo echo "===Settting up venv===" enterVenv echo echo "===Installing poetry===" pip install poetry echo echo "===Installing dependencies===" poetry install echo echo "===Validate with rstcheck===" rstcheck README.rst echo echo "===Sort imports with isort===" ISORT_ARGS="" if [[ "${CI:-}" = "1" ]]; then ISORT_ARGS="--check-only" fi isort $ISORT_ARGS . echo echo "===Format with black===" BLACK_ARGS="" if [[ "${CI:-}" = "1" ]]; then BLACK_ARGS="--check" fi black $BLACK_ARGS . echo echo "===Lint with flake8===" flake8 echo echo "===Lint with pylint===" pylint pywemo echo echo "===Test with pytest===" pytest echo echo "===Building package===" poetry build echo echo "Build complete"
import zope.interface from z3c.form.widget import FieldWidget from z3c.form.browser import button from z3c.form.browser.interfaces import IHTMLImageWidget from z3c.form import interfaces @zope.interface.implementer_only(IHTMLImageWidget) class ImageWidget(button.ButtonWidget): """A image button of a form."""