text
stringlengths
27
775k
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #ifndef _NGX_THREAD_H_INCLUDED_ #define _NGX_THREAD_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> #if (NGX_THREADS) #include <pthread.h> typedef pthread_mutex_t ngx_thread_mutex_t; ngx_int_t ngx_thread_mutex_create(ngx_thread_mutex_t *mtx, ngx_log_t *log); ngx_int_t ngx_thread_mutex_destroy(ngx_thread_mutex_t *mtx, ngx_log_t *log); ngx_int_t ngx_thread_mutex_lock(ngx_thread_mutex_t *mtx, ngx_log_t *log); ngx_int_t ngx_thread_mutex_unlock(ngx_thread_mutex_t *mtx, ngx_log_t *log); typedef pthread_cond_t ngx_thread_cond_t; ngx_int_t ngx_thread_cond_create(ngx_thread_cond_t *cond, ngx_log_t *log); ngx_int_t ngx_thread_cond_destroy(ngx_thread_cond_t *cond, ngx_log_t *log); ngx_int_t ngx_thread_cond_signal(ngx_thread_cond_t *cond, ngx_log_t *log); ngx_int_t ngx_thread_cond_wait(ngx_thread_cond_t *cond, ngx_thread_mutex_t *mtx, ngx_log_t *log); #if (NGX_LINUX) typedef pid_t ngx_tid_t; #define NGX_TID_T_FMT "%P" #elif (NGX_FREEBSD) typedef uint32_t ngx_tid_t; #define NGX_TID_T_FMT "%uD" #elif (NGX_DARWIN) typedef uint64_t ngx_tid_t; #define NGX_TID_T_FMT "%uA" #else typedef uint64_t ngx_tid_t; #define NGX_TID_T_FMT "%uA" #endif ngx_tid_t ngx_thread_tid(void); #define ngx_log_tid ngx_thread_tid() #else #define ngx_log_tid 0 #define NGX_TID_T_FMT "%d" #endif #endif /* _NGX_THREAD_H_INCLUDED_ */
module Tockhead class Settings cattr_accessor :api_key cattr_accessor :secret cattr_accessor :base_url # set api key and secret from file - TEMP # contents = File.open('tmp/creds').read rescue nil contents = contents.split(",") self.api_key = contents[0] self.secret = contents[1] class << self def config(params) params.each { |k,value| send("#{k}=", value) } end end end end
package typingsSlinky.awsSdkServiceModel import typingsSlinky.awsSdkBuildTypes.apiModelMod.ApiModel import typingsSlinky.awsSdkBuildTypes.treeModelMod.TreeModel import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object treeModelMod { @JSImport("@aws-sdk/service-model/build/TreeModel", "fromApiModel") @js.native def fromApiModel(model: ApiModel): TreeModel = js.native @JSImport("@aws-sdk/service-model/build/TreeModel", "fromModelJson") @js.native def fromModelJson(modelJson: String): TreeModel = js.native }
import React from 'react'; import { render } from '@testing-library/react'; import Home from './'; test('renders hero box', () => { const { getByTestId } = render(<Home />); const element = getByTestId('hero-box'); expect(element).toBeInTheDocument(); }); test('renders login box', () => { const { getByTestId } = render(<Home />); const element = getByTestId('login-form'); expect(element).toBeInTheDocument(); }); test('renders features list', () => { const { getByTestId } = render(<Home />); const element = getByTestId('features-1'); expect(element).toBeInTheDocument(); expect(element.children[1].innerHTML.indexOf('unlimited surveys at zero cost')).toBeTruthy(); });
require 'sinatra' class IntegrationTestComponent < Sinatra::Base # Polled by the integration test component runner to determine # when a component is up and ready to receive requests. get '/info' do [200, {}, ''] end end class FakeServiceBroker < Sinatra::Base use IntegrationTestComponent use Rack::Auth::Basic, 'Restricted Area' do |_, password| password == 'opensesame' end # Queried by Cloud Controller to determine if this is a real, # API-compliant service broker. get '/v3' do [200, {}, '["OK"]'] end end
package middleware import ( "net/http" "github.com/rs/zerolog/log" ) func LogMiddlewareFunc(h http.Handler) (http.Handler, error) { var handlerFunc http.HandlerFunc = func( w http.ResponseWriter, r *http.Request) { log.Info(). Int64("ContentLength", r.ContentLength). Str("Method", r.Method). Str("RemoteAddr", r.RemoteAddr). Stringer("URL", r.URL). Msg("Incoming request") h.ServeHTTP(w, r) } return handlerFunc, nil }
require "ruby-cbc" require "sudoku/cbc/version" require "sudoku/cbc/board" require "sudoku/cbc/problem" module Sudoku module Cbc # Your code goes here... end end
import React from 'react'; import { useState } from 'react'; import { useContext } from 'react'; import { useForm } from 'react-hook-form'; import { Button, Form, Grid, Message, Segment, Image } from 'semantic-ui-react'; import { Context } from '../../store/login-context'; import './styles.scss'; import logo from '../../assets/images/logo_basico2.svg'; type FormValues = { email: string; password: string; server: string; }; export const Login: React.FC = () => { const [loginFailed, setLoginFailed] = useState(''); const { handleLogin } = useContext(Context); const { register, formState: { errors }, handleSubmit, } = useForm<FormValues>({ mode: 'onBlur', }); const onSubmit = async (value: FormValues) => { try { await handleLogin(value.email, value.password); } catch (err) { messageSuccessRemove; setLoginFailed('Falha ao tentar realizar o login!'); } }; const messageSuccessRemove = setTimeout(function () { setLoginFailed(''); }, 5000); return ( <Grid className="screen-login" textAlign="center" centered columns={2}> <Grid.Column> <Form className="screen-login-form" onSubmit={handleSubmit(onSubmit)} size="small"> <Segment stacked> <Grid.Row> <Image className="screen-login-logo" src={logo} alt="Advogado Digital" /> </Grid.Row> <Form.Input fluid icon="user" iconPosition="left" placeholder="E-mail address" {...register('email', { required: true, pattern: /^\S+@\S+$/i })} /> {errors.email && errors.email.type === 'required' && ( <Message color="red">E-mail é requerido.</Message> )} {errors.email && errors.email.type === 'pattern' && ( <Message color="red">E-mail com formato inválido.</Message> )} <Form.Input fluid icon="lock" iconPosition="left" placeholder="Password" type="password" {...register('password', { required: true, minLength: 3, maxLength: 12 })} /> {errors.password && errors.password.type === 'required' && ( <Message color="red">Password é requerido.</Message> )} {errors.password && errors.password.type === 'minLength' && ( <Message color="red">Password deve conter no mínímo 3 caracteres.</Message> )} {errors.password && errors.password.type === 'maxLength' && ( <Message color="red">Password deve conter no máximo 12 caracteres.</Message> )} <Button type="submit" color="blue" fluid size="large"> Login </Button> </Segment> </Form> {loginFailed !== '' && <Message color="red">{loginFailed}</Message>} </Grid.Column> </Grid> ); };
# Genyman Core ![Build status](https://ci.appveyor.com/api/projects/status/xf1elh0glbb7as3m?svg=true) ### Work in progress Docs currently here: https://genyman.github.io/docs/ But not production ready, not feature complete, and breaking changes between updates! Check back later, or STAR to follow up.
# TemplateConnector Component Reference A React component that provides access to [Getters](getter.md) and [Actions](action.md) within a [Template](template.md). ## User reference ### Properties Name | Type | Default | Description -----|------|---------|------------ children | (getters: { [getterName: string]: any }, actions: { [actionName: string]: (payload?: any) => void }) => ReactNode | | A function that renders a markup using Getters and Actions passed as arguments.
-- file:select_implicit.sql ln:18 expect:true INSERT INTO test_missing_target VALUES (7, 4, 'cccc', 'h')
function Rename-ItemByPattern() { <# .SYNOPSIS ファイル(ディレクトリ)名等を指定パターン文字列により変更します。 .DESCRIPTION 正規表現文字列によりファイル(ディレクトリ)名を変更します。 .PARAMETER Path 名前変更対象のファイル(ディレクトリ)のパスを指定します。 .PARAMETER Pattern 置換する正規表現文字列を指定します。。 .PARAMETER Replacement 置換後文字列を指定します。 #> param( [Parameter(Mandatory, ValueFromPipeline)][string]$Path, [Parameter(Mandatory)][string]$Pattern, [Parameter(Mandatory)][string]$Replacement ) Process { try { $resolve_path = (Resolve-Path -Path $Path -ErrorAction Stop).Path; $old_name = Split-Path -Path $resolve_path -Leaf; Rename-Item -Path $resolve_path -NewName ($old_name -replace $Pattern, $Replacement); } catch [System.Management.Automation.ItemNotFoundException] { throw Get-ErrorMessage -Code NOT_FOUND -Params @($Path); } } }
package com.twitter.scrooge trait HasThriftStructCodec3[T <: ThriftStruct] { def _codec: ThriftStructCodec3[T] }
from django.db import models from django.contrib.auth.models import User departments = [('Cardiologist', 'Cardiologist'), ('Dermatologists', 'Dermatologists'), ('Emergency Medicine Specialists', 'Emergency Medicine Specialists'), ('Allergists/Immunologists', 'Allergists/Immunologists'), ('Anesthesiologists', 'Anesthesiologists'), ('Colon and Rectal Surgeons', 'Colon and Rectal Surgeons') ] class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField( upload_to='profile_pic/DoctorProfilePic/', null=True, blank=True) address = models.CharField(max_length=40) mobile = models.CharField(max_length=20, null=True) department = models.CharField( max_length=50, choices=departments, default='Cardiologist') status = models.BooleanField(default=False) @property def get_name(self): return self.user.first_name+" "+self.user.last_name @property def get_id(self): return self.user.id def __str__(self): return "{} ({})".format(self.user.first_name, self.department) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField( upload_to='profile_pic/PatientProfilePic/', null=True, blank=True) address = models.CharField(max_length=40) mobile = models.CharField(max_length=20, null=False) symptoms = models.CharField(max_length=100, null=False) assignedDoctorId = models.PositiveIntegerField(null=True) admitDate = models.DateField(auto_now=True) status = models.BooleanField(default=False) @property def get_name(self): return self.user.first_name+" "+self.user.last_name @property def get_id(self): return self.user.id def __str__(self): return self.user.first_name+" ("+self.symptoms+")" class Appointment(models.Model): patientId = models.PositiveIntegerField(null=True) doctorId = models.PositiveIntegerField(null=True) patientName = models.CharField(max_length=40, null=True) doctorName = models.CharField(max_length=40, null=True) appointmentDate = models.DateField(auto_now=True) description = models.TextField(max_length=500) status = models.BooleanField(default=False) class PatientDischargeDetails(models.Model): patientId = models.PositiveIntegerField(null=True) patientName = models.CharField(max_length=40) assignedDoctorName = models.CharField(max_length=40) address = models.CharField(max_length=40) mobile = models.CharField(max_length=20, null=True) symptoms = models.CharField(max_length=100, null=True) admitDate = models.DateField(null=False) releaseDate = models.DateField(null=False) daySpent = models.PositiveIntegerField(null=False) roomCharge = models.PositiveIntegerField(null=False) medicineCost = models.PositiveIntegerField(null=False) doctorFee = models.PositiveIntegerField(null=False) OtherCharge = models.PositiveIntegerField(null=False) total = models.PositiveIntegerField(null=False) # Developed By : Sherida Providence # GitHub: https://github.com/Sherida101 # YouTube : https://www.youtube.com/channel/UCobAZ9eizOU77HaEoLn0jHA
import * as jsonld from 'jsonld'; import { Injectable, OnDestroy, ComponentFactoryResolver, ComponentRef, } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { concat, from, Subject, BehaviorSubject, Observable, of, EMPTY } from 'rxjs'; import { filter, catchError, first } from 'rxjs/operators'; import { ComponentDirective, SimulationContext } from 'app/renpi'; import { ComponentMeta, ComponentsRegistryService, SimulationServiceBase, } from 'app/renpi/services'; import { NewComponentDirective, StaticSessionDirective } from 'app/renpi/directives'; import { assignComponentProperty, assignComponentStyle, componentGraphScan } from 'app/renpi/utils'; import { SimulationOutletComponent } from './simulation-outlet.component'; export interface SceneContext { sceneIRI: string; sceneComponentMeta: ComponentMeta<any>; componentsIRI: { [iri: string]: any }; componentRefsIRI: { [iri: string]: ComponentRef<any> }; } class SceneIRINotAvailableError extends Error { constructor(name?: string) { super(`SceneIRI is not found: [${name}], '@id' is needed for a Scene Definition.`); } } class JsonldNotFoundError extends Error { constructor() { super(`Jsonld is not found.`); } } class UnknownType extends Error { constructor(name: string) { super(`Type [${name}] is not registered.`); } } @Injectable() export class SimulationService implements OnDestroy, SimulationServiceBase { private simulationContext: SimulationContext; private outlet: SimulationOutletComponent; private destroySubject = new Subject<void>(); public readonly initObserve: Observable<SimulationContext>; public readonly leaveObserve: Observable<SimulationContext>; private init$ = new BehaviorSubject<SimulationContext>(null); private leave$ = new BehaviorSubject<SimulationContext>(null); private currentScene: SceneContext; private currentSceneDirective$ = new BehaviorSubject<ComponentDirective & { finished?: boolean }>(null); private currentSceneDirectiveHistory: (ComponentDirective & { finished?: boolean })[] = []; constructor( private http: HttpClient, private componentRegistry: ComponentsRegistryService, private componentFactoryResolver: ComponentFactoryResolver, ) { this.initObserve = this.init$.asObservable().pipe(filter(c => !!c)); this.leaveObserve = this.leave$.asObservable().pipe(filter(s => !!s)); } /** * Completes the active subject, signalling to all other observables to complete. */ ngOnDestroy(): void { this.destroySubject.next(); this.destroySubject.complete(); } leave() { this.leave$.next(this.context); } public get context() { return this.simulationContext; } public observeDirectives() { return concat(from(this.currentSceneDirectiveHistory), this.currentSceneDirective$) .pipe(filter(d => !!d), filter(d => !d.finished)); } setOutlet(outlet: SimulationOutletComponent) { if (this.outlet) { throw new Error('This Outlet has been activated.'); } this.outlet = outlet; this.initObserve.pipe(first()).subscribe(c => { if (!c.entryScene) { throw new Error('http://rengular.js.org/schema/entryScene is not provided.'); } this.sceneFromIRI(c.entryScene, 'initialGekijo'); }); } init(context: object | Observable<object>): void { (function ensureObservable() { if (context instanceof Observable) { return context; } return of(context); })().pipe(first()).toPromise() .then(doc => jsonld.expand(doc)).then(doc => { return jsonld.compact(doc, { ren: 'http://rengular.js.org/schema/', id: '@id', name: 'ren:contextName', title: 'ren:contextTitle', entryScene: 'ren:nextScene', screenAspect: 'ren:screenAspect', width: 'ren:screenAspectWidth', height: 'ren:screenAspectHeight', fontSize: 'ren:screenAspectFontSize', version: 'http://schema.org/version', interfaceVersion: 'http://schema.org/schemaVersion', }); }).then((ctx: SimulationContext) => { this.simulationContext = ctx; this.init$.next(ctx); }); } initFromUrl(contextUrl: string) { return this.init(this.http.get(contextUrl)); } newSceneFromLd(sceneLd: object | Observable<object>): void { if (!this.outlet) { throw new Error('There is still no activated outlet for loading new scene component.'); } const oldDirectiveObservable = this.currentSceneDirective$; this.currentSceneDirective$ = new BehaviorSubject<ComponentDirective>(null); this.currentSceneDirectiveHistory = []; (function ensureObservable() { if (sceneLd instanceof Observable) { return sceneLd; } return of(sceneLd); })().pipe(first(), catchError(e => { console.error(e); // TODO: Throw Error Event as component output return EMPTY; })).toPromise() .then(doc => jsonld.flatten(doc, {})) .then( flattened => jsonld.frame(flattened, { '@context': { '@version': 1.1 }, '@type': 'http://rengular.js.org/schema/StaticSessionAction', }).then(doc => jsonld.expand(doc)) .then(expandedActions => Promise.all( (Array.isArray(expandedActions) ? expandedActions : [expandedActions]) .map( expandedAction => jsonld.compact(expandedAction, { targetType: { '@type': '@id', '@id': 'http://rengular.js.org/schema/targetType' }, property: 'http://schema.org/name', value: 'http://schema.org/value', }).then( (action: { targetType?: string, property: string, value: any, }) => { if (!action.targetType) { console.warn('http://rengular.js.org/schema/targetType is invalid: ' + action); return; } this.castDirective(new StaticSessionDirective( action.targetType, action.property, action.value)); })) )).then(_ => flattened)) .then( flattened => jsonld.frame(flattened, { '@context': { '@version': 1.1 }, '@type': this.componentRegistry.getSceneTypes(), }).then(doc => jsonld.compact(doc, {})) /* Init current Scene with scene component instantiation */ .then((doc: { '@id'?: string, '@type': string[] | string, // `@type`is certain, because this expandedActions is framed by type searching }) => { if (Object.entries(doc).length === 0) { throw new JsonldNotFoundError(); } if (!doc['@id']) { this.currentSceneDirective$ = oldDirectiveObservable; throw new SceneIRINotAvailableError('currentScene'); } oldDirectiveObservable.complete(); const sceneMeta = (Array.isArray(doc['@type']) ? doc['@type'] as string[] : [doc['@type'] as string]) .map(type => this.componentRegistry.getMeta(type))[0]; const sceneHostRef = this.outlet.sceneHost.viewContainerRef; sceneHostRef.clear(); // TODO: check inheritance to make descendant searching more correct if (!sceneMeta) { throw new Error('Root Scene is not defined'); } const componentRefsIRI = {}; componentRefsIRI[doc['@id']] = sceneHostRef.createComponent( this.componentFactoryResolver.resolveComponentFactory(sceneMeta.component), ); const componentsIRI = {}; componentsIRI[doc['@id']] = componentRefsIRI[doc['@id']].instance; this.currentScene = { sceneIRI: doc['@id'], sceneComponentMeta: sceneMeta, componentsIRI, componentRefsIRI, }; }).then(_ => flattened)) .then( flattened => jsonld.frame(flattened, { '@context': { '@version': 1.1 }, '@type': this.componentRegistry.getSceneTypes(), }).then(doc => jsonld.expand(doc)).then(doc => jsonld.compact(doc, {})) /* assign ld into children components */ .then(doc => assignComponentProperty( this.componentRegistry, this.currentScene.sceneComponentMeta, this.currentScene.componentsIRI[this.currentScene.sceneIRI], doc)).then(_ => flattened)) .then( flattened => jsonld.frame(flattened, { '@context': { '@version': 1.1 }, '@type': 'http://rengular.js.org/schema/ComponentAction', }).then(doc => jsonld.expand(doc)).then(doc => Array.isArray(doc) ? doc : [doc]) .then(expandedActions => Promise.all(expandedActions.map( expandedAction => jsonld.compact(expandedAction, {}) /* Execute Children Component Create Action */ .then(action => new Promise<{ meta: ComponentMeta<any>, iri: string, data: object }>(resolve => { const objectDoc = action['http://schema.org/object']; const targetDoc = action['http://schema.org/target']; if (!objectDoc['@id'] || !targetDoc['@id']) { console.warn('"@id" is missing: ' + JSON.stringify(action, null, 2)); return; } const meta = this.componentRegistry.getMeta(objectDoc['@type']); if (!meta) { throw new UnknownType(objectDoc['@id']); } // TODO: dispatch directive to specific target IRI const directive: NewComponentDirective & { finished?: boolean } = { '@type': 'http://rengular.js.org/schema/ComponentAction', meta, componentId: objectDoc['@id'], finish: () => { directive.finished = true; resolve({ meta, iri: objectDoc['@id'], data: objectDoc }); }, }; this.castDirective(directive); })).then(ctx => assignComponentProperty( this.componentRegistry, ctx.meta, this.currentScene.componentsIRI[ctx.iri], ctx.data)) ))).then(_ => flattened)) .then( flattened => jsonld.expand(flattened) /* collect all components indexed by IRI for components styling later */ .then(expanded => componentGraphScan( this.componentRegistry, Array.isArray(expanded) ? expanded : [expanded], this.currentScene.sceneIRI, this.currentScene.componentsIRI)).then(_ => flattened)) .then(flattened => { jsonld.expand(flattened).then(doc => Array.isArray(doc) ? doc : [doc]) .then(nodes => nodes.filter(node => ( node['@type'] && node['@type'] .find(typeIRI => this.componentRegistry.getCssActionTypes().indexOf(typeIRI) > -1) && node['http://schema.org/target'] ))) .then(expandedActions => Promise.all( /* Execute Components Styling Action */ expandedActions.map(expandedAction => jsonld.compact(expandedAction, { '@version': 1.1, version: 'http://schema.org/version', interfaceVersion: 'http://schema.org/schemaVersion', targetComponent: 'http://schema.org/target', matchMedia: 'http://rengular.js.org/schema/matchMedia', '@vocab': 'http://rengular.js.org/schema/CssStyle#', }).then((action: { targetComponent: { '@id': string }, matchMedia?: string | string[], }) => { const targetComponent = this.currentScene.componentRefsIRI[action.targetComponent['@id']]; if (!targetComponent) { return; } const styling: { [property: string]: string, matchMedia: string } = { matchMedia: 'ALL', }; for (const property in action) { if (action.hasOwnProperty(property) && !property.startsWith('@') && ['targetComponent'].indexOf(property) < 0) { styling[property] = action[property]; } } const ele = targetComponent.location.nativeElement; assignComponentStyle([styling], ele); })))); }); } sceneFromIRI(sceneUrl: string, label?: string) { if (!sceneUrl) { throw new SceneIRINotAvailableError(label); } return this.newSceneFromLd(this.http.get(sceneUrl)); } getComponentByIRI(id: string) { if (!this.currentScene) { throw new Error('No Available Scene Loaded!'); } return this.currentScene.componentsIRI[id]; } registerComponentIRI(id: string, component: ComponentRef<any>) { if (!this.currentScene) { throw new Error('No Available Scene Loaded!'); } this.currentScene.componentRefsIRI[id] = component; this.currentScene.componentsIRI[id] = component.instance; } private castDirective(directive: ComponentDirective & { finished?: boolean }) { if (!directive.finish) { directive.finish = () => { directive.finished = true; }; } this.currentSceneDirectiveHistory.push(directive); this.currentSceneDirective$.next(directive); } }
# Chat Create a chat with [socket.io](https://github.com/socketio/socket.io). ## Resources * [Node: De cero a experto](https://www.udemy.com/course/node-de-cero-a-experto/) ## License MIT
/* * This file is part of the librarian application. * * Copyright (c) 2017 Miguel Angel Gabriel <magabriel@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code */ package com.mags.librarian.options import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.util.logging.Level internal class OptionsReaderTest { @Test fun unknownOption() { var called = 0 val optionsReader = OptionsReader(listOf("badoption")) optionsReader.onUnknownOption { option: String -> assertEquals("badoption", option) called++ } optionsReader.process() assertEquals(1, called) } @Test fun optionHelp() { var options: Options options = executeReader(listOf("--help")) assertTrue(options.help) options = executeReader(listOf("-h")) assertTrue(options.help) } @Test fun optionCopy() { val options = executeReader(listOf("--copy")) assertTrue(options.copyOnly) } @Test fun optionCreateConfig() { val options = executeReader(listOf("--create-config")) assertTrue(options.createConfig) } @Test fun optionDryRun() { val options = executeReader(listOf("--dry-run")) assertTrue(options.dryRun) } @Test fun optionVerbosity() { var options: Options options = executeReader(listOf("--quiet")) assertEquals(Options.Verbosity.NONE, options.verbosity) options = executeReader(listOf("-v")) assertEquals(Options.Verbosity.NORMAL, options.verbosity) options = executeReader(listOf("-vv")) assertEquals(Options.Verbosity.HIGH, options.verbosity) } @Test fun optionConfig() { var options: Options options = executeReader(listOf("--config", "my/config/file/name")) assertEquals("my/config/file/name", options.configFileName) options = executeReader(listOf("-c", "my/config/file/name")) assertEquals("my/config/file/name", options.configFileName) } @Test fun optionLog() { var options: Options options = executeReader(listOf("--log", "my/log/file/name")) assertEquals("my/log/file/name", options.logFileName) options = executeReader(listOf("-l", "my/log/file/name")) assertEquals("my/log/file/name", options.logFileName) } @Test fun optionRss() { var options: Options options = executeReader(listOf("--rss", "my/rss/file/name")) assertEquals("my/rss/file/name", options.rssFileName) options = executeReader(listOf("-r", "my/rss/file/name")) assertEquals("my/rss/file/name", options.rssFileName) } @Test fun optionLogLevel() { var options = executeReader(listOf("--loglevel", "all")) assertEquals(Level.ALL, options.logLevel) } @Test fun severalOptions() { val expected = Options(verbosity = Options.Verbosity.NONE, copyOnly = true, configFileName = "/my/config", logLevel = Level.WARNING) var options = executeReader(listOf("--quiet", "--copy", "-c", "/my/config", "--loglevel", "warning")) assertEquals(expected, options) } @Test fun optionLogLevelNotValid() { var called = 0 val optionsReader = OptionsReader(listOf("--loglevel", "notvalid")) optionsReader.onInvalidValue { option: String, value: String -> assertEquals("--loglevel", option) assertEquals("notvalid", value) called++ } optionsReader.process() assertEquals(1, called) } private fun executeReader(arguments: List<String>): Options { val optionsReader = OptionsReader(arguments) optionsReader.onUnknownOption { option: String -> fail<String>("Unknown option \"$option\"") } optionsReader.onMissingValue { option: String -> fail<String>("Missing value for option \"$option\"") } optionsReader.onInvalidValue { option: String, value: String -> fail<String>("Invalid value \"$value\" for option \"$option\"") } return optionsReader.process() } }
import React from 'react'; import ProgressBar from '../commons/ProgressBar'; interface BackupCodesLoaderProps { title: string; } export const BackupCodesLoader = ({title}: BackupCodesLoaderProps) => ( <> <p className="backup-loader-label">{title}</p> <ProgressBar className="backup-loader" /> </> ); export default BackupCodesLoader;
# Install Docker 0.9.0 package "docker" do package_name "lxc-docker-0.9.0" action :install end
package typingsSlinky.bingmaps.Microsoft.Maps.Directions import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native sealed trait TimeType extends StObject @JSGlobal("Microsoft.Maps.Directions.TimeType") @js.native object TimeType extends StObject { /** The dateTime parameter contains the desired arrival time for a transit request. */ @js.native sealed trait arrival extends TimeType /** The dateTime parameter contains the desired departure time for a transit request. */ @js.native sealed trait departure extends TimeType /** The dateTime parameter should be ignored and the first available transit taken. */ @js.native sealed trait firstAvailable extends TimeType /** The dateTime parameter contains the latest departure time available for a transit request. */ @js.native sealed trait lastAvailable extends TimeType }
/** * 700. 二叉搜索树中的搜索 * * https://leetcode-cn.com/problems/search-in-a-binary-search-tree/ * * Easy * * 116ms 90.57% * 42.3mb 15.47% */ const searchBST = (root, val) => { if (!root) { return null } if (root.val === val) { return root } if (root.val > val) { return searchBST(root.left, val) } if (root.val < val) { return searchBST(root.right, val) } }
using System; namespace Realmar.DataBindings { [Serializable] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = true)] public class BindingTargetAttribute : Attribute { public int Id { get; } public BindingTargetAttribute(int id = 0) { Id = id; } } }
# # Sets Prezto options. # # # General # # Theme to use down below in prompt section # Other themes I like: # sorin, steeef, cloud, agnoster, sorin-apj, apjanke-01 _ZPREZTO_THEME="sorin-apj" # Set case-sensitivity for completion, history lookup, etc. zstyle ':prezto:*:*' case-sensitive 'no' # Color output (auto set to 'no' on dumb terminals). zstyle ':prezto:*:*' color 'yes' # Set the Zsh modules to load (man zshmodules). # zstyle ':prezto:load' zmodule 'attr' 'stat' # Set the Zsh functions to load (man zshcontrib). # zstyle ':prezto:load' zfunction 'zargs' 'zmv' # Set the Prezto modules to load (browse modules). # The order matters. () { local pmodules pmodules=( 'environment' 'terminal' 'editor' 'history' 'directory' 'spectrum' 'utility' 'ssh' 'completion' 'git' 'osx' 'rsync' 'history-substring-search' 'belak/contrib/contrib-prompt' 'apjanke/personal/prompt' 'prompt' ) zstyle ':prezto:load' pmodule $pmodules } # # Editor # # Set the key mapping style to 'emacs' or 'vi'. zstyle ':prezto:module:editor' key-bindings 'emacs' # Auto convert .... to ../.. zstyle ':prezto:module:editor' dot-expansion 'no' # # Git # # Ignore submodules when they are 'dirty', 'untracked', 'all', or 'none'. # zstyle ':prezto:module:git:status:ignore' submodules 'all' # # GNU Utility # # Set the command prefix on non-GNU systems. zstyle ':prezto:module:gnu-utility' prefix 'g' # # History Substring Search # # Set the query found color. # zstyle ':prezto:module:history-substring-search:color' found '' # Set the query not found color. # zstyle ':prezto:module:history-substring-search:color' not-found '' # Set the search globbing flags. # zstyle ':prezto:module:history-substring-search' globbing-flags '' # # Prompt # # Set the prompt theme to load. # Setting it to 'random' loads a random theme. # Auto set to 'off' on dumb terminals. zstyle ':prezto:module:prompt' theme "$_ZPREZTO_THEME" # # Ruby # # Auto switch the Ruby version on directory change. # zstyle ':prezto:module:ruby:chruby' auto-switch 'yes' # # Screen # # Auto start a session when Zsh is launched in a local terminal. # zstyle ':prezto:module:screen:auto-start' local 'yes' # Auto start a session when Zsh is launched in a SSH connection. # zstyle ':prezto:module:screen:auto-start' remote 'yes' # # SSH # # Set the SSH identities to load into the agent. # zstyle ':prezto:module:ssh:load' identities 'id_rsa' 'id_rsa2' 'id_github' # # Syntax Highlighting # # Set syntax highlighters. # By default, only the main highlighter is enabled. # zstyle ':prezto:module:syntax-highlighting' highlighters \ # 'main' \ # 'brackets' \ # 'pattern' \ # 'cursor' \ # 'root' # # Set syntax highlighting styles. # zstyle ':prezto:module:syntax-highlighting' styles \ # 'builtin' 'bg=blue' \ # 'command' 'bg=blue' \ # 'function' 'bg=blue' # # Terminal # # Auto set the tab and window titles. zstyle ':prezto:module:terminal' auto-title 'yes' # Set the window title format. # zstyle ':prezto:module:terminal:window-title' format '%n@%m: %s' # Set the tab title format. # zstyle ':prezto:module:terminal:tab-title' format '%m: %s' # # Tmux # # Auto start a session when Zsh is launched in a local terminal. # zstyle ':prezto:module:tmux:auto-start' local 'yes' # Auto start a session when Zsh is launched in a SSH connection. # zstyle ':prezto:module:tmux:auto-start' remote 'yes' # Integrate with iTerm2. # zstyle ':prezto:module:tmux:iterm' integrate 'yes'
package spark_core.rdd.operator.transform import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} object Transform_17_kv_aggregateByKey { def main(args: Array[String]): Unit = { // TODO 创建环境 val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator") val sc = new SparkContext(sparkConf) aggregateByKey() println("-----------------") aggregateByKey_same() println("-----------------") foldByKey() // TODO 关闭资源 sc.stop() // TODO aggregateByKey: def aggregateByKey(): Unit = { val rdd = sc.makeRDD(List( ("a", 1), ("a", 2), ("a", 3), ("a", 4) ),2) // (a,[1,2]), (a, [3,4]) // (a, 2), (a, 4) // (a, 6) // aggregateByKey存在函数柯里化,需要传入两个参数列表 // 第一个参数列表:传递一个参数表示初始值 // 第二个参数列表:需要传递2个参数 // 第一个参数表示分区内的计算规则; // 第一个参数表示分区间的计算规则 rdd.aggregateByKey(0)( (x,y) => math.max(x,y), (x,y) => x+y ).collect().foreach(println) } // TODO aggregateByKey: 如果规则相同也是可以计算比如求和 def aggregateByKey_same(): Unit = { val rdd = sc.makeRDD(List( ("a", 1), ("a", 2), ("a", 3), ("a", 4) ),2) // (a,[1,2]), (a, [3,4]) // (a, 3), (a, 7) // (a, 11) rdd.aggregateByKey(0)( (x,y) => x+y, (x,y) => x+y ).collect().foreach(println) // spark_core.rdd.aggregateByKey(0)(_+_,_+_).collect().foreach(println) } // TODO foldByKey: 如果聚合计算时,分区内和分区间计算规则相同,spark提供了简化的方法 def foldByKey(): Unit = { val rdd = sc.makeRDD(List( ("a", 1), ("a", 2), ("a", 3), ("a", 4) ),2) // (a,[1,2]), (a, [3,4]) // (a, 3), (a, 7) // (a, 11) rdd.foldByKey(0)(_+_).collect().foreach(println) } } }
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^index$', views.index, name='index'), url(r'^projects$', views.projects, name='projects'), url(r'^project/(?P<project_id>\d+)$', views.project, name='project'), url(r'^controller/(?P<controller_id>\d+)$', views.controller, name='controller'), url(r'^controller_image/(?P<controller_id>\d+)/image.svg$', views.controller_image, name='controller_image'), ]
package com.skyinu.hprof.reader.model import okio.BufferedSource class HprofTagHeapSummary(bufferedSource: BufferedSource, parent: HprofTag) { var totalLiveBytes = 0 var totalLiveInstance = 0 var totalByteAllocate = 0L var totalInstanceAllocated = 0L init { totalLiveBytes = bufferedSource.readInt() totalLiveInstance = bufferedSource.readInt() totalByteAllocate = bufferedSource.readLong() totalInstanceAllocated = bufferedSource.readLong() } }
package com.ghstudios.android.features.monsters.list import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.ghstudios.android.data.classes.Monster import com.ghstudios.android.data.classes.MonsterClass import com.ghstudios.android.data.DataManager import com.ghstudios.android.util.loggedThread import com.ghstudios.android.util.toList /** * A viewmodel meant to be used by the MonsterListFragment */ class MonsterListViewModel(app: Application): AndroidViewModel(app) { private val dataManager = DataManager.get() private var initialized = false private var currentClass: MonsterClass? = null val monsterData = MutableLiveData<List<Monster>>() fun loadMonsters(monsterClass: MonsterClass?) { if (initialized && currentClass == monsterClass) { return } initialized = true currentClass = monsterClass loggedThread("Monster List Load") { monsterData.postValue(dataManager.queryMonsters(monsterClass).toList { it.monster }) } } }
<?php namespace Freshcells\Cache\GeneratableKeyCache\KeyGenerator; use Freshcells\Cache\GeneratableKeyCache\Exception\KeyGeneratorException; /** * Class Sha1ShortGenerator * @package Freshcells\Cache\GeneratableKeyCache\KeyGenerator */ class Sha1ShortGenerator implements KeyGeneratorInterface { protected $prefix = ''; /** * Sha1ShortGenerator constructor. * @param string $prefix */ public function __construct(string $prefix = '') { $this->prefix = $prefix; } /** * generates the key as md5 hash for a given var * * @param $keyVar * @return string * @throws KeyGeneratorException */ public function generate($keyVar): string { $var = $keyVar; if (!is_string($keyVar)) { throw new KeyGeneratorException( 'Cannot use anything else than a string for key generation. ' .' You passed '.gettype($keyVar) ); } // SHA1 collision probability is quite low (see https://en.wikipedia.org/wiki/Birthday_problem). // 7 chars give you 28bit with 240 million possibilities (see // http://blog.cuviper.com/2013/11/10/how-short-can-git-abbreviate/). // Concerning the space we save for the keys this is quite a good trade. If you ever come back to this // place and you need a lower chance of collision, raise this number to 12. This would even be enough for the // full linux kernel. return $this->prefix.substr(sha1($var), 0, 7); } }
var space = new CanvasSpace("#pt_canvas").setup({bgcolor: "#f1f3f7", resize: true, retina: true}); var form = space.getForm(); //// Code starts here --- let grid = []; let closest = null; // Find the closest point on the grid function findClosest( p ) { let m = Number.MAX_VALUE; let c = null; for (let i=0; i<grid.length; i++ ){ let mag = p.$subtract( grid[i] ).magnitude(); if (mag < m) { c = grid[i]; m = mag; } } return c.clone(); } space.add( { // On start, use Create.gridPts convenient function to make a 20x20 grid start: () => { grid = Create.gridPts( space.innerBound, 20, 20 ); }, // Draw animate: (time, ftime) => { form.fillOnly("#789").points( grid, 2, "circle" ); if (closest) form.fillOnly("#f90").point( closest, 10, "circle" ); }, // When mouse is moving, find the closest grid point next to mouse point action:( type, px, py ) => { if (type == "move") { closest = findClosest( new Pt(px, py) ); } } }); //// ---- space.bindMouse().bindTouch().play();
# netre Utility to restart network connection on failure. ## TODO * Write better readme and usage information * Address publishing mechanism * Support for other systems ## License [MIT](LICENSE)
TEST_PROJECT = "all-of-us-workbench-test" def make_gae_vars(min_idle_instances = 0, max_instances = 10, instance_class = 'F1') { "GAE_MIN_IDLE_INSTANCES" => min_idle_instances.to_s, "GAE_MAX_INSTANCES" => max_instances.to_s, 'GAE_INSTANCE_CLASS' => instance_class } end def env_with_defaults(env, config) { :env_name => env, :config_json => "config_#{env}.json", :cdr_config_json => "cdr_config_#{env}.json", :featured_workspaces_json => "featured_workspaces_#{env}.json", :gae_vars => make_gae_vars, }.merge(config) end # TODO: Make environment/project flags consistent across commands, consider # using environment keywords as dict keys here, e.g. :test, :staging, etc. ENVIRONMENTS = { "local" => env_with_defaults("local", { :api_endpoint_host => "localhost:8081", :cdr_sql_instance => "workbench", :source_cdr_project => "all-of-us-ehr-dev" }), "all-of-us-workbench-test" => env_with_defaults("test", { :api_endpoint_host => "api-dot-#{TEST_PROJECT}.appspot.com", :cdr_sql_instance => "#{TEST_PROJECT}:us-central1:workbenchmaindb", :gae_vars => make_gae_vars(0, 10, 'F4'), :publisher_account => "circle-deploy-account@all-of-us-workbench-test.iam.gserviceaccount.com", :source_cdr_project => "all-of-us-ehr-dev", :source_cdr_wgs_project => "all-of-us-workbench-test", :accessTiers => { "registered" => { :ingest_cdr_project => "fc-aou-vpc-ingest-test", :dest_cdr_project => "fc-aou-cdr-synth-test", :auth_domain_group_email => "GROUP_all-of-us-registered-test@dev.test.firecloud.org", }, "controlled" => { :ingest_cdr_project => "fc-aou-cdr-ingest-test-2", :dest_cdr_project => "fc-aou-cdr-synth-test-2", :auth_domain_group_email => "all-of-us-test-prototype-3@dev.test.firecloud.org", } } }), "all-of-us-rw-staging" => env_with_defaults("staging", { :api_endpoint_host => "api-dot-all-of-us-rw-staging.appspot.com", :cdr_sql_instance => "#{TEST_PROJECT}:us-central1:workbenchmaindb", :gae_vars => make_gae_vars(0, 10, 'F2'), :source_cdr_project => "all-of-us-ehr-dev", :source_cdr_wgs_project => "all-of-us-workbench-test", :publisher_account => "circle-deploy-account@all-of-us-workbench-test.iam.gserviceaccount.com", :accessTiers => { "registered" => { :ingest_cdr_project => "fc-aou-vpc-ingest-staging", :dest_cdr_project => "fc-aou-cdr-synth-staging", :auth_domain_group_email => "GROUP_all-of-us-registered-staging@firecloud.org", }, "controlled" => { :ingest_cdr_project => "fc-aou-vpc-ingest-staging-ct", :dest_cdr_project => "fc-aou-cdr-staging-ct", :auth_domain_group_email => "all-of-us-controlled-staging@firecloud.org", } } }), "all-of-us-rw-perf" => env_with_defaults("perf", { :api_endpoint_host => "api-dot-all-of-us-rw-perf.appspot.com", :cdr_sql_instance => "#{TEST_PROJECT}:us-central1:workbenchmaindb", :gae_vars => make_gae_vars(5, 20), :source_cdr_project => "all-of-us-ehr-dev", :source_cdr_wgs_project => "all-of-us-workbench-test", :publisher_account => "circle-deploy-account@all-of-us-workbench-test.iam.gserviceaccount.com", :accessTiers => { "registered" => { :ingest_cdr_project => "fc-aou-vpc-ingest-perf", :dest_cdr_project => "fc-aou-cdr-perf", :auth_domain_group_email => "all-of-us-registered-perf@perf.test.firecloud.org", }, "controlled" => { :ingest_cdr_project => "fc-aou-vpc-ingest-perf-ct", :dest_cdr_project => "fc-aou-cdr-perf-ct", :auth_domain_group_email => "all-of-us-controlled-perf@perf.test.firecloud.org", } } }), "all-of-us-rw-stable" => env_with_defaults("stable", { :api_endpoint_host => "api-dot-all-of-us-rw-stable.appspot.com", :cdr_sql_instance => "#{TEST_PROJECT}:us-central1:workbenchmaindb", :source_cdr_project => "all-of-us-ehr-dev", :source_cdr_wgs_project => "all-of-us-workbench-test", :publisher_account => "deploy@all-of-us-rw-stable.iam.gserviceaccount.com", :accessTiers => { "registered" => { :ingest_cdr_project => "fc-aou-vpc-ingest-stable", :dest_cdr_project => "fc-aou-cdr-synth-stable", :auth_domain_group_email => "GROUP_all-of-us-registered-stable@firecloud.org", }, } }), "all-of-us-rw-preprod" => env_with_defaults("preprod", { :api_endpoint_host => "api.preprod-workbench.researchallofus.org", :cdr_sql_instance => "all-of-us-rw-preprod:us-central1:workbenchmaindb", :source_cdr_project => "aou-res-curation-output-prod", :source_cdr_wgs_project => "aou-genomics-curation-prod", :publisher_account => "deploy@all-of-us-rw-preprod.iam.gserviceaccount.com", :accessTiers => { "registered" => { :ingest_cdr_project => "fc-aou-vpc-ingest-preprod", :dest_cdr_project => "fc-aou-cdr-preprod", :auth_domain_group_email => "all-of-us-registered-preprod@firecloud.org", }, "controlled" => { :ingest_cdr_project => "fc-aou-vpc-ingest-preprod-ct", :dest_cdr_project => "fc-aou-cdr-preprod-ct", :auth_domain_group_email => "all-of-us-controlled-preprod@firecloud.org", } } }), "all-of-us-rw-prod" => env_with_defaults("prod", { :api_endpoint_host => "api.workbench.researchallofus.org", :cdr_sql_instance => "all-of-us-rw-prod:us-central1:workbenchmaindb", :gae_vars => make_gae_vars(8, 64, 'F4'), :source_cdr_project => "aou-res-curation-output-prod", :publisher_account => "deploy@all-of-us-rw-prod.iam.gserviceaccount.com", :accessTiers => { "registered" => { :ingest_cdr_project => "fc-aou-vpc-ingest-prod", :dest_cdr_project => "fc-aou-cdr-prod", :auth_domain_group_email => "all-of-us-registered-prod@firecloud.org", }, "controlled" => { :ingest_cdr_project => "fc-aou-vpc-ingest-prod-ct", :dest_cdr_project => "fc-aou-cdr-prod-ct", :auth_domain_group_email => "all-of-us-controlled-prod@firecloud.org", } } }) } def must_get_env_value(env, key) unless ENVIRONMENTS.fetch(env, {}).has_key?(key) raise ArgumentError.new("env '#{env}' lacks key #{key}") end return ENVIRONMENTS[env][key] end def get_config(project) config_json = must_get_env_value(project, :config_json) path = File.join(File.dirname(__FILE__), "../config/#{config_json}") return JSON.parse(File.read(path)) end def get_cdr_config(project) cdr_config_json = must_get_env_value(project, :cdr_config_json) path = File.join(File.dirname(__FILE__), "../config/#{cdr_config_json}") return JSON.parse(File.read(path)) end
package de.wias.nonparregboot.classifier import breeze.linalg.{DenseVector, softmax, sum} import breeze.numerics.exp import org.platanios.tensorflow.api.core.Shape import org.platanios.tensorflow.api.tensors.Tensor import scalapurerandom.DV case class ClassificationResults(scores: TFloat // nstar * m ) { def predictedClasses: Classes = scores.argmax(axes = Tensor.ones[Int](Shape())).toInt def probabilities: OFloat = scores.softmax(axis = 1) }
<?php namespace App\Http\Controllers; use App\Models\AppliedJobs; use App\Models\Jobs; use App\Models\Profile; use App\Services\UserService; use Illuminate\Http\Request; use Auth; use DB; class DashboardController extends Controller { public function dashboard() { if (Auth::user()->role === 'Employee') { $jobs = DB::table('jobs as j') ->leftjoin('companies as c', 'j.companyId', 'c.id') ->select('j.id', 'j.title', 'c.businessName') ->paginate(15); $isApply = AppliedJobs::where('profileId', UserService::getUserId()) ->pluck('jobId') ->all(); $data = array( 'jobs' => $jobs, 'isApply' => $isApply, ); } else { $userId = UserService::getUserId(); /* $appliedJobEmp = DB::table('jobs as j') ->where('j.companyId', $userId) ->leftjoin('appliedjob as aj', 'j.id', 'aj.jobId') ->leftjoin('profiles as p', 'aj.profileId', 'p.id') ->select('p.*') ->paginate(15); */ $appliedJobEmp = DB::table('appliedjob as aj') ->leftjoin('profiles as p', 'aj.profileId', 'p.id') ->leftjoin('jobs as j', function($query) use ($userId){ $query->on('aj.jobId', 'j.id') ->where('j.companyId', $userId); }) ->select('p.*') ->paginate(15); $data = array( 'appliedEmp' => $appliedJobEmp, ); } return view('dashboard', $data); } public function profileView(Request $request) { $profileData = Profile::find(decrypt($request->id)); $data = array( 'fName' => $profileData->firstName, 'lName' => $profileData->lastName, 'email' => $profileData->email, 'picture' => $profileData->picture, 'resume' => $profileData->resume, 'skills' => $profileData->skills, ); return view('profile.profile', $data); } }
package framian.benchmark import scala.util.Random import org.openjdk.jmh.annotations.{ Benchmark, Scope, State } import framian.Column import framian.column.Mask class ColumnFilterBenchmark { import Data.work @Benchmark def dense(data: FilterData): Int = work(data.denseColumn.filter(data.p), data.size) @Benchmark def eval(data: FilterData): Int = work(data.evalColumn.filter(data.p), data.size) @Benchmark def optimisticMemoized(data: FilterData): Int = work(data.optMemoColumn.filter(data.p), data.size) @Benchmark def pessimisticMemoized(data: FilterData): Int = work(data.pesMemoColumn.filter(data.p), data.size) } @State(Scope.Benchmark) class FilterData extends Data { val p: Int => Boolean = { x => x % 2 == 0 } val denseColumn: Column[Int] = Column.dense(Array.range(0, size)) val evalColumn: Column[Int] = Column.eval(row => framian.Value(row)) val optMemoColumn: Column[Int] = evalColumn.memoize(true) val pesMemoColumn: Column[Int] = evalColumn.memoize(false) }
<!--- # This file is part of the pl.wrzasq.commons. # # @license http://mit-license.org/ The MIT license # @copyright 2022 © by Rafał Wrzeszcz - Wrzasq.pl. --> # Ktor feature `XRayFeature` integrates [**AWS X-Ray**](https://aws.amazon.com/xray/) tracing for HTTP clients. ```kotlin val httpClient = HttpClient(engine) { install(XRayFeature) } ``` It resembles behavior of `aws-xray-recorder-sdk-apache-http`. ![img.png](console.png)
package io.github.gravetii.scene.start import io.github.gravetii.scene.FxDimensions import io.github.gravetii.scene.FxScene import io.github.gravetii.scene.menu.MenuBarComponent import javafx.geometry.Dimension2D import javafx.stage.Stage class StartScene(stage: Stage) : FxScene(stage) { private val menuBarComponent = MenuBarComponent(stage, root) private val startImageComponent = StartImageComponent(root) private val startControlsComponent = StartControlsComponent(menuBarComponent) override fun build() { showTop(menuBarComponent) showCenter(startImageComponent) showRight(startControlsComponent) } override fun title() = "-WORDAGAM-" override fun preferredDimensions(): FxDimensions { val def = Dimension2D(960.0, 630.0) val min = Dimension2D(960.0, 630.0) val max = Dimension2D(1100.0, 732.0) return FxDimensions(def, min, max) } }
# -*- encoding : utf-8 -*- # # $Id: depreciation_param.rb 2474 2011-03-23 15:28:08Z ichy $ # Product: hyacc # Copyright 2009 by Hybitz.co.ltd # ALL Rights Reserved. # module Auto::Journal class DepreciationParam < Auto::AutoJournalParam attr_reader :depreciation attr_reader :user def initialize( depreciation, user ) super( HyaccConstants::AUTO_JOURNAL_TYPE_DEPRECIATION, user ) @depreciation = depreciation end end end
#!/bin/bash export PATH="/opt/homebrew/bin:/usr/local/bin:${PATH}" caffeinate & # Prevent computer from going to sleep tmp_dir="$(mktemp -d)" curl --location 'https://github.com/vitorgalvao/dotfiles/archive/master.zip' | ditto -xk - "${tmp_dir}" for shell_script in "${tmp_dir}/dotfiles-master/scripts/"*.sh; do source "${shell_script}" done function show_options { clear echo " What do you want to do next? [1] Update the system. [2] Configure macOS. [3] Setup language environments. [4] Install apps. [5] Configure tools. [0] Quit. " | sed -E 's/ {4}//' read -n1 -rp 'Pick a number: ' option clear if [[ "${option}" -eq 1 ]]; then sync_icloud mas_login update_system elif [[ "${option}" -eq 2 ]]; then configure_macos_auto configure_macos_manual set_lock_screen_message lower_startup_chime install_commercial_fonts install_launch_agents "${tmp_dir}/dotfiles-master/files/launchd_plists" elif [[ "${option}" -eq 3 ]]; then install_brew install_python install_ruby install_node elif [[ "${option}" -eq 4 ]]; then install_brew_apps install_cask_apps install_mas_apps elif [[ "${option}" -eq 5 ]]; then restore_settings set_keyboard_shortcuts set_default_apps install_editor_packages configure_pinboard_scripts install_chromium_extensions install_alfred_workflow_launch_agents elif [[ "${option}" -eq 0 ]]; then # Let computer go to sleep again killall 'caffeinate' sudo --remove-timestamp return 0 else echo 'Not a valid option. Try again.' >&2 fi show_options } renew_sudo show_options
class BaseMailer < ActionMailer::Base default :from => Setting.mailer.sender default :charset => "utf-8" default :content_type => "text/html" default_url_options[:host] = Setting.domain layout 'mailer' end
package com.skai.snapboard; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import java.io.File; /** * Created by SKai on 2016/11/30. */ public class BoardCustomAdapter extends CursorAdapter { private LayoutInflater cursorInflater; // Default constructor public BoardCustomAdapter(Context context, Cursor cursor, int flags) { super(context, cursor, flags); cursorInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); } public void bindView(View view, Context context, Cursor cursor) { File image = new File(cursor.getString(cursor.getColumnIndex(BoardDBHelper.KEY_FILEPATH))); Bitmap mBitmapInsurance; BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 16; mBitmapInsurance = BitmapFactory.decodeFile(image.getAbsolutePath(),options); ImageView imageView = (ImageView) view.findViewById(R.id.board); imageView.setImageBitmap(mBitmapInsurance); TextView subjectTextView = (TextView) view.findViewById(R.id.subject); String subject = cursor.getString( cursor.getColumnIndex(BoardDBHelper.KEY_SUBJECT )); subjectTextView.setText(subject); TextView tagTextView = (TextView) view.findViewById(R.id.tag); String tag = cursor.getString( cursor.getColumnIndex(BoardDBHelper.KEY_TAG )); tagTextView.setText(tag); TextView dateTextView = (TextView) view.findViewById(R.id.date); String date = cursor.getString( cursor.getColumnIndex(BoardDBHelper.KEY_DATE )); dateTextView.setText(date); } public View newView(Context context, Cursor cursor, ViewGroup parent) { // R.layout.list_row is your xml layout for each row return cursorInflater.inflate(R.layout.board_item, parent, false); } }
package com.jiangjg.lib.JavaAndPattern.TH12; public class BadFruitException extends Exception{ public BadFruitException(String msg){ super(msg); } }
// Copyright (c) 2019 Doyub Kim // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include <pch.h> #include <jet/parallel.h> #include <jet/particle_emitter3.h> #include <limits> namespace jet { ParticleEmitter3::ParticleEmitter3() {} ParticleEmitter3::~ParticleEmitter3() {} const ParticleSystemData3Ptr& ParticleEmitter3::target() const { return _particles; } void ParticleEmitter3::setTarget(const ParticleSystemData3Ptr& particles) { _particles = particles; onSetTarget(particles); } bool ParticleEmitter3::isEnabled() const { return _isEnabled; } void ParticleEmitter3::setIsEnabled(bool enabled) { _isEnabled = enabled; } void ParticleEmitter3::update(double currentTimeInSeconds, double timeIntervalInSeconds) { if (_onBeginUpdateCallback) { _onBeginUpdateCallback(this, currentTimeInSeconds, timeIntervalInSeconds); } onUpdate(currentTimeInSeconds, timeIntervalInSeconds); } void ParticleEmitter3::onSetTarget(const ParticleSystemData3Ptr& particles) { UNUSED_VARIABLE(particles); } void ParticleEmitter3::setOnBeginUpdateCallback( const OnBeginUpdateCallback& callback) { _onBeginUpdateCallback = callback; } } // namespace jet
<?php namespace App\Library\EmailDirect; /** * Description of Orders * * @author mlapko */ class EmailDirect_Orders extends EmailDirect_Resource { /** * @link http://docs.emaildirect.com/#OrderList * @param array $options * @return EmailDirect_Response */ public function all($options = array()) { return $this->_adapter->get('/Orders', $options); } /** * @link http://docs.emaildirect.com/#OrderDetails * @return EmailDirect_Response */ public function details() { return $this->_adapter->get('/Orders/' . $this->_id); } /** * @link http://docs.emaildirect.com/#OrderAdd * @param string $email * @param array $options * @return EmailDirect_Response */ public function create($email, $options = array()) { $data = array_merge($options, array( 'EmailAddress' => $email, )); return $this->_adapter->post('/Orders', $data); } /** * @link http://docs.emaildirect.com/#OrderImport * @param array $orders * @return EmailDirect_Response */ public function import($orders) { return $this->_adapter->post('/Orders/Import', array('Orders' => (array) $orders)); } /** * @link http://docs.emaildirect.com/#OrderUpdate * @param string $email * @param array $options * @return EmailDirect_Response */ public function update($email, $options = array()) { $options = array_merge($options, array('EmailAddress' => $email)); return $this->_adapter->put('/Orders/' . $this->_id, $options); } /** * @link http://docs.emaildirect.com/#OrderDelete * @return EmailDirect_Response */ public function delete() { return $this->_adapter->delete('/Orders/' . $this->_id); } }
package dataprotocol.buffered import dataprotocol.DataProtocol import dataprotocol.Protocol import java.lang.IllegalStateException import java.nio.ByteBuffer import java.nio.ByteOrder class ProtocolBuffer( private val byteBuffer: ByteBuffer, private val protocol: Protocol ): Iterator<Any> { private lateinit var componentBuffer: ByteBuffer init { rewind() allocComponentBuffer() } fun rewind() { byteBuffer.rewind() protocol.headTo(0) } override fun hasNext(): Boolean { return (currentComponentRemaining() > 0) || ((currentComponentRemaining() <= 0) && (hasValidNextComponent())) } private fun hasValidNextComponent(): Boolean { val nextComponent = protocol.getNextComponent() return (nextComponent.size <= byteBuffer.remaining()) } override fun next(): Any { if (currentComponentRemaining() <= 0) { headToNextComponent() allocComponentBuffer() } val value = protocol.getCurrentComponent().fetch(componentBuffer)!! byteBuffer.position(byteBuffer.position() + currentComponentPrimitiveSize()) return value } private fun headToNextComponent() { protocol.headToNextComponent() if (currentComponentDataCount() == DataProtocol.DECLARE_LAZY_COUNT) throw IllegalStateException("Component's data count has not been lazily initialized.") } private fun allocComponentBuffer() { componentBuffer = byteBuffer.slice().limit(currentComponentSize()) as ByteBuffer } fun currentComponentRemaining(): Int { return componentBuffer.remaining() } fun currentComponentDataCount(): Int { return protocol.getCurrentComponent().count } fun currentComponentIndex(): Int { return protocol.getCurrentComponentIndex() } fun currentComponentPrimitiveSize(): Int { return protocol.getCurrentComponent().primitiveSize } fun currentComponentOrder(): ByteOrder { return protocol.getCurrentComponent().order } fun currentComponentSize(): Int { return protocol.getCurrentComponent().size } fun changeComponentDataCount(componentIndex: Int, count: Int) { protocol.changeComponentNumber(componentIndex, count) } }
import { Injectable } from '@angular/core'; import { File } from '@ionic-native/file/ngx'; //eclare var cordova: any; // const fs:string = cordova.file.dataDirectory; //const fs: string = cordova.file.externalDataDirectory; import * as XLSX from 'ts-xlsx'; @Injectable({ providedIn: 'root' }) export class ExcelServiceService { sheetNames: string[] = [] sheets: any; constructor(private file: File) { } createXSLX(data:any): Promise<any> { return new Promise((resolve) => { let ws_name = "OrderDetails"; let wb: XLSX.IWorkBook = { SheetNames: [], Sheets: {}, Props: {} }; let ws = this.sheet_from_array_of_arrays(data, {}); /* add worksheet to workbook */ wb.SheetNames.push(ws_name); wb.Sheets[ws_name] = ws; let wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' }); let xslxBlob = new Blob([this.s2ab(wbout)],{type:"application/octet-stream"}); resolve(xslxBlob); }); } datenum(v, date1904): any { if (date1904) v += 1462; let epoch: any = Date.parse(v); return (epoch - new Date(Date.UTC(1899, 11, 30)).getTime()) / (24 * 60 * 60 * 1000); } sheet_from_array_of_arrays(data, opts) { let ws = {}; let range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } }; for (let R = 0; R != data.length; ++R) { for (let C = 0; C != data[R].length; ++C) { if (range.s.r > R) range.s.r = R; if (range.s.c > C) range.s.c = C; if (range.e.r < R) range.e.r = R; if (range.e.c < C) range.e.c = C; let cell: any = { v: data[R][C] }; if (cell.v == null) continue; let cell_ref = XLSX.utils.encode_cell({ c: C, r: R }); if (typeof cell.v === 'number') cell.t = 'n'; else if (typeof cell.v === 'boolean') cell.t = 'b'; else if (cell.v instanceof Date) { cell.t = 'n'; //cell.z = XLSX.SSF._table[14]; cell.v = this.datenum(cell.v, null); } else cell.t = 's'; ws[cell_ref] = cell; } } if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range.s, range.e); return ws; } s2ab(s) { let buf = new ArrayBuffer(s.length); let view = new Uint8Array(buf); for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } }
#!/usr/bin/env bash dt=$(date '+%d/%m/%Y %H:%M:%S') # http://docs.openlinksw.com/virtuoso/rdfperfdumpandreloadgraphs/ # Definition of the isql connection to Virtuoso bin="isql-vt" host="virtuoso" port=1111 user="dba" password=${DBA_PASSWORD} export_dir="${VIRTUOSO_DATA_DIR}" # Wrap the execution of isql commands to receive the return code and output run_virtuoso_cmd () { VIRT_OUTPUT=`echo "$1" | "$bin" -H "$host" -S "$port" -U "$user" -P "$password" 2>&1` VIRT_RETCODE=$? if [[ $VIRT_RETCODE -eq 0 ]]; then echo "$VIRT_OUTPUT" | tail -n+5 | perl -pe 's|^SQL> ||g' return 0 else echo -e "[ERROR] running the these commands in virtuoso:\n$1\nerror code: $VIRT_RETCODE\noutput:" echo "$VIRT_OUTPUT" let 'ret = VIRT_RETCODE + 128' return $ret fi } # Check if the virtuoso is up and running # This is needed during the bootstrapping process in a docker setup test_connection () { if [[ -z $1 ]]; then echo "[ERROR] missing argument: retry attempts" exit 1 fi t=$1 run_virtuoso_cmd 'status();' while [[ $? -ne 0 ]] ; do echo -n "." sleep 2 echo $t let "t=$t-1" if [ $t -eq 0 ] then echo "timeout" return 2 fi run_virtuoso_cmd 'status();' done } cd "$export_dir" echo "[INFO] waiting for store to come online" : ${CONNECTION_ATTEMPTS:=60} test_connection "${CONNECTION_ATTEMPTS}" if [ $? -eq 2 ]; then echo "[ERROR] store not reachable" exit 1 fi # Give some more seconds to the virtuoso to really accept updates sleep 3 # First define the procedure command=`cat /virtuoso/dump_one_graph.virtuoso>&1` run_virtuoso_cmd "$command" echo "[INFO] $dt Starting dump process..."; echo "[INFO] initializing named graphs from *.graph files" declare -A serializer=( ["nt"]="ntriples" ["rdf"]="rdfxml" ["xml"]="rdfxml" ["ttl"]="turtle") for ext in nt rdf ttl xml; do for graph_file in *.${ext}.graph; do if [ ! -f ${graph_file} ]; then # skip when the loop iterates varbatom "*.xml.graph" files continue fi graph=`head -n1 ${graph_file}` echo "[INFO] dump graph $graph to ${graph_file%.graph}" # Now use it to dump run_virtuoso_cmd "dump_one_graph('${graph}', '${export_dir}/tmp_data_', 1000000000);" exportfile="tmp_data_000001.ttl" # Check if the repository contains a custom normalize script if [ -f ./normalize.sh ]; then mv $exportfile ${graph_file%.graph} ./normalize.sh ${graph_file%.graph} else if [ $ext -eq "nt" ]; then rapper -q -i turtle -o ${serializer[$ext]} $exportfile | LC_ALL=C sort -u > ${graph_file%.graph} else rapper -q -i turtle -o ${serializer[$ext]} $exportfile > ${graph_file%.graph} fi rm "$exportfile" fi rm "$exportfile.graph" done done echo "[INFO] dump done;"
# Sorted-Square-List-2 Sorted square list data structure using merged linked lists to store the data See project description pdf for more information
#!/bin/sh { echo "mcr.microsoft.com/mssql/server:2017-CU12" echo "ibmcom/db2:11.5.0.0a" } > spring-data-jdbc/src/test/resources/container-license-acceptance.txt
<?php declare(strict_types=1); namespace Torr\Rad\Entity\Interfaces; /** * Interface for automatic integration in the sortable helpers. */ interface SortableEntityInterface extends EntityInterface { /** */ public function getSortOrder () : ?int; /** */ public function setSortOrder (int $sortOrder) : void; }
package me.pisal.compass_sensor import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.util.Log import android.view.animation.Animation import android.view.animation.RotateAnimation import android.widget.ImageView class Orientation(context: Context){ private var mContext: Context private var mSensorManager: SensorManager? = null private var mAccelerometer: Sensor? = null private var mMagnetometer: Sensor? = null private val mLastAccelerometer = FloatArray(3) private val mLastMagnetometer = FloatArray(3) private var mLastAccelerometerSet = false private var mLastMagnetometerSet = false private val mR = FloatArray(9) private val mOrientation = FloatArray(3) private var mCurrentDegree = 0f init { this.mContext = context initSensor() } private fun initSensor(){ mSensorManager = mContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager mAccelerometer = mSensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) mMagnetometer = mSensorManager!!.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) } private var sensorEventListener: SensorEventListener = object: SensorEventListener { override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { } override fun onSensorChanged(event: SensorEvent) { if (event.sensor == mAccelerometer) { System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.size) mLastAccelerometerSet = true } else if (event.sensor == mMagnetometer) { System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.size) mLastMagnetometerSet = true } if (mLastAccelerometerSet && mLastMagnetometerSet) { SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer) SensorManager.getOrientation(mR, mOrientation) val azimuthInRadians = mOrientation[0] val azimuthInDegress = (Math.toDegrees(azimuthInRadians.toDouble()) + 360).toFloat() % 360 Log.d("Debug", "Bearing: ${azimuthInDegress}") orientationListener?.invoke(azimuthInDegress) val ra = RotateAnimation( mCurrentDegree, -azimuthInDegress, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f ) ra.duration = 250 ra.fillAfter = true pointer?.startAnimation(ra) mCurrentDegree = -azimuthInDegress } } } //region public members var orientationListener: OrientationListener? = null /** * (Optional)The image view that indicates the current orientation */ var pointer: ImageView? = null fun pause(){ mSensorManager!!.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_GAME) mSensorManager!!.registerListener(sensorEventListener, mMagnetometer, SensorManager.SENSOR_DELAY_GAME) } fun resume(){ mSensorManager!!.registerListener(sensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_GAME) mSensorManager!!.registerListener(sensorEventListener, mMagnetometer, SensorManager.SENSOR_DELAY_GAME) } //endregion } typealias OrientationListener = (Float) -> Unit fun ImageView.rotate(from: Float, to: Float) { val ra = RotateAnimation( from, -to, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f ) ra.duration = 250 ra.fillAfter = true this.startAnimation(ra) }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Tensorflow.UnitTest { public class TestHelper { public static string GetFullPathFromDataDir(string fileName) { var dir = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "..", "..", "..", "data"); return Path.GetFullPath(Path.Combine(dir, fileName)); } } }
EnabledLanguagesLogger = ActiveSupport::Logger.new(Rails.root.join('log/enabled_languages.log')) EnabledLanguagesLogger.formatter = Logger::Formatter.new
using System; namespace OrigoDB.Core { public class LocalEngineClient<TModel> : IEngine<TModel> where TModel : Model { public readonly Engine<TModel> Engine; public LocalEngineClient(Engine<TModel> engine) { Engine = engine; } public TResult Execute<TResult>(Query<TModel, TResult> query) { return Engine.Execute(query); } public void Execute(Command<TModel> command) { Engine.Execute(command); } public TResult Execute<TResult>(Command<TModel, TResult> command) { return Engine.Execute(command); } public object Execute(Command command) { return Engine.Execute(command); } public object Execute(Query query) { return Engine.Execute(query); } public TResult Execute<TResult>(Func<TModel, TResult> query) { return Engine.Execute(query); } } }
#!/bin/sh # Adapted from http://blog.pkh.me/p/21-high-quality-gif-with-ffmpeg.html # Converts a series of png files (named 1.png 2.png ... n.png) in a folder $1 # to a movie $2, which is then converted to a gif $3. palette="/tmp/palette.png" filters="fps=1" find $1 -name "[0-9]*.png" -print0 | while read -d $'\0' file do echo "Converting $file to remove transparent background..." convert $file -background white -alpha remove $file done ffmpeg -framerate 1 -i $1/%d.png -c:v libx264 -r 30 -pix_fmt yuv420p $2 ffmpeg -v warning -i $2 -vf "$filters,palettegen" -y $palette ffmpeg -v warning -i $2 -i $palette -lavfi "$filters [x]; [x][1:v] paletteuse" -y $3
require 'helper' require 'striped/proxy/discount' describe Striped::Proxy::Discount do let(:client) { double('client') } let(:arguments) { double('arguments') } let(:api_response) { double('api_response') } let(:resource_id) { 'customer_id' } subject(:proxy) { Striped::Proxy::Discount.new(client, resource_id) } before do client.stub(:delete).and_return(api_response) end describe "#delete" do before { @response = proxy.delete } it "sends a request to delete a customer's discount" do expect(client).to( have_received(:delete).with("/customers/#{resource_id}/discount") ) end it "returns the API response" do expect(@response).to eq api_response end end end
import React, { Component } from "react"; import MouseMonitor from "./MouseMonitor"; interface Props { onMouseOver: (content: JSX.Element) => void; popupContent: JSX.Element; onMouseOut: () => void; children: JSX.Element; } interface State { mouseIn: boolean; } export class Popup extends Component<Props, State> { state: State = { mouseIn: false, }; render() { const { onMouseOver, popupContent, onMouseOut } = this.props; return ( <div onMouseOver={() => { this.setState({ mouseIn: true }); onMouseOver( <MouseMonitor onMoveAway={() => { if (this.state.mouseIn) { return; } onMouseOut(); }} paddingX={60} paddingY={30} children={popupContent} /> ); }} onMouseOut={() => { this.setState({ mouseIn: false }); }} > {this.props.children} </div> ); } } export default Popup;
// @flow import cx from 'classnames'; import { createField } from './Field'; import Textarea from 'react-textarea-autosize'; import styles from './TextInput.css'; type Props = { type?: string, className?: string, inputRef?: any, readOnly?: boolean, }; function TextArea({ type = 'text', className, inputRef, readOnly, ...props }: Props) { return ( <Textarea ref={inputRef} type={type} className={cx(styles.input, readOnly && styles.disabled, className)} {...(props: Object)} /> ); } TextArea.Field = createField(TextArea); export default TextArea;
<?php ini_set("memory_limit", "1024m"); function reconn() { echo "Reconnect\n"; $cli = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $cli->on("connect", function(swoole_client $cli) { // client 发送 大包数据 $cli->send(str_repeat("\0", 1024 * 1024 * 1.9)); }); $cli->on("receive", function(swoole_client $cli, $data) { $cli->send($data); }); $cli->on("error", function(swoole_client $cli) { echo "error\n"; }); $cli->on("close", function(swoole_client $cli) { echo "close\n"; reconn(); }); $cli->connect("127.0.0.1", 9001); } reconn();
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Syndication { using System.Xml; using System.Runtime.CompilerServices; // NOTE: This class implements Clone so if you add any members, please update the copy ctor [TypeForwardedFrom("System.ServiceModel.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] public class UrlSyndicationContent : SyndicationContent { string mediaType; Uri url; public UrlSyndicationContent(Uri url, string mediaType) : base() { if (url == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("url"); } this.url = url; this.mediaType = mediaType; } protected UrlSyndicationContent(UrlSyndicationContent source) : base(source) { if (source == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("source"); } this.url = source.url; this.mediaType = source.mediaType; } public override string Type { get { return this.mediaType; } } public Uri Url { get { return this.url; } } public override SyndicationContent Clone() { return new UrlSyndicationContent(this); } protected override void WriteContentsTo(XmlWriter writer) { writer.WriteAttributeString(Atom10Constants.SourceTag, string.Empty, FeedUtils.GetUriString(this.url)); } } }
<h1>Thêm lớp</h1> <form action="{{ route('grade.store')}}" method="post"> @csrf Tên <input type="text" name="name" required><br> <button>them</button> </form>
<?php use App\Unidad; use Illuminate\Database\Seeder; class UnidadSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(Unidad::class)->create([ 'nombre' => 'Litros', 'simbolo' => 'L', ]); factory(Unidad::class)->create([ 'nombre' => 'Unidades', 'simbolo' => 'U', ]); factory(Unidad::class)->create([ 'nombre' => 'Kilogramos', 'simbolo' => 'Kg', ]); } }
const gulp = require("gulp"); const sourcemaps = require("gulp-sourcemaps"); const ts = require("gulp-typescript"); const tslint = require("gulp-tslint"); const tsProject = ts.createProject("tsconfig.json"); let node = null; gulp.task("build", function() { return tsProject .src() .pipe(sourcemaps.init({ loadMaps: true })) .pipe(tsProject()) .js.pipe(sourcemaps.write()) .pipe(gulp.dest("build")); }); gulp.task("lint", function() { return tsProject .src() .pipe(tslint({ formatter: "stylish" })) .pipe(tslint.report({ summarizeFailureOutput: true })); }); gulp.task("default", gulp.series("build", "lint")); gulp.task("dev", gulp.series("build")); process.on("exit", function() { if (!!node) { node.kill(); } });
require 'spec_helper' describe "indent-based languages, not using matchit" do let(:filename) { 'test.py' } specify "Removes a wrapping if-clause" do set_file_contents <<~EOF if one: if two: if three: pass EOF vim.search 'two' vim.command 'Deleft' vim.write expect_file_contents <<~EOF if one: if three: pass EOF end specify "Removes a wrapping if-clause with a following unindent" do set_file_contents <<~EOF if wrapping: if one: two if another: three EOF vim.search 'one' vim.command 'Deleft' vim.write expect_file_contents <<~EOF if wrapping: two if another: three EOF end end
/* eslint-disable @typescript-eslint/ban-ts-comment */ /* eslint-disable unused-imports/no-unused-vars-ts */ import { Body, Controller, Get, Global, INestApplication, Module, Patch, Post, Put, Query, } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import * as Joi from 'joi'; import { JoiSchema } from 'joi-class-decorators'; import { JoiPipe, JOIPIPE_OPTIONS, JoiPipeModule, JoiValidationGroups } from 'nestjs-joi'; import * as request from 'supertest'; describe('NestJS integration', () => { class metatype { @JoiSchema(Joi.string().required()) @JoiSchema([JoiValidationGroups.CREATE], Joi.number().required()) @JoiSchema([JoiValidationGroups.UPDATE], Joi.array().required()) prop!: unknown; } let controller; let module: TestingModule; let app: INestApplication; let request_: request.Test; // Note: we will test one case (@Query or @Body) each, since the other cases // are considered to be equivalent describe('app module', () => { describe('without options', () => { const CASES = [JoiPipeModule, JoiPipeModule.forRoot()]; for (const pipeModule of CASES) { beforeEach(async () => { @Controller() class ctrl { @Get('/') get(@Query() query: metatype): unknown { return { status: 'OK' }; } @Post('/') post(@Body() body: metatype): unknown { return { status: 'OK' }; } @Put('/') put(@Body() body: metatype): unknown { return { status: 'OK' }; } @Patch('/') patch(@Body() body: metatype): unknown { return { status: 'OK' }; } } controller = ctrl; module = await Test.createTestingModule({ controllers: [controller], imports: [pipeModule], }).compile(); app = module.createNestApplication(); await app.init(); }); afterEach(async () => { await app.close(); }); describe('GET', () => { it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .get('/?prop=foo') .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .get('/') .expect(res => expect(res.body).toMatchObject({ statusCode: 400, message: expect.stringContaining('"prop" is required'), }), ); }); }); describe('POST', () => { it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .post('/') .send({ prop: 1 }) .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .post('/') .send({ prop: 'a' }) .expect(res => expect(res.body).toMatchObject({ statusCode: 400, message: expect.stringContaining('"prop" must be a number'), }), ); }); }); describe('PUT', () => { it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .put('/') .send({ prop: [] }) .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .put('/') .send({ prop: 'a' }) .expect(res => expect(res.body).toMatchObject({ statusCode: 400, message: expect.stringContaining('"prop" must be an array'), }), ); }); }); describe('PATCH', () => { it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .patch('/') .send({ prop: [] }) .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .patch('/') .send({ prop: 'a' }) .expect(res => expect(res.body).toMatchObject({ statusCode: 400, message: expect.stringContaining('"prop" must be an array'), }), ); }); }); } }); describe('with options in .forRoot()', () => { beforeEach(async () => { @Controller() class ctrl { @Get('/') get(@Query() query: metatype): unknown { return { status: 'OK' }; } } controller = ctrl; module = await Test.createTestingModule({ controllers: [controller], imports: [ JoiPipeModule.forRoot({ pipeOpts: { usePipeValidationException: true, }, }), ], }).compile(); app = module.createNestApplication(); // Silence the ExceptionHandler output on 500 app.useLogger(false); await app.init(); }); afterEach(async () => { await app.close(); }); it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .get('/?prop=foo') .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .get('/') .expect(res => expect(res.body).toMatchObject({ statusCode: 500, message: expect.stringContaining('Internal server error'), }), ); }); }); describe('options injection', () => { beforeEach(async () => { @Controller() class ctrl { @Get('/') get(@Query() query: metatype): unknown { return { status: 'OK' }; } } controller = ctrl; @Global() @Module({ providers: [ { provide: JOIPIPE_OPTIONS, useValue: { usePipeValidationException: true, }, }, ], exports: [JOIPIPE_OPTIONS], }) class OptionsModule {} module = await Test.createTestingModule({ controllers: [controller], imports: [OptionsModule, JoiPipeModule], }).compile(); app = module.createNestApplication(); // Silence the ExceptionHandler output on 500 app.useLogger(false); await app.init(); }); afterEach(async () => { await app.close(); }); it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .get('/?prop=foo') .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .get('/') .expect(res => expect(res.body).toMatchObject({ statusCode: 500, message: expect.stringContaining('Internal server error'), }), ); }); }); }); describe('method parameter pipe', () => { describe('without options', () => { beforeEach(async () => { @Controller() class ctrl { @Get('/') get(@Query(JoiPipe) query: metatype): unknown { return { status: 'OK' }; } } controller = ctrl; module = await Test.createTestingModule({ controllers: [controller], }).compile(); app = module.createNestApplication(); await app.init(); }); afterEach(async () => { await app.close(); }); it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .get('/?prop=foo') .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .get('/?prop=') .expect(res => expect(res.body).toMatchObject({ statusCode: 400, message: expect.stringContaining('"prop" is not allowed to be empty'), }), ); }); }); }); describe('options injection', () => { beforeEach(async () => { @Controller() class ctrl { @Get('/') get(@Query(JoiPipe) query: metatype): unknown { return { status: 'OK' }; } } controller = ctrl; module = await Test.createTestingModule({ controllers: [controller], providers: [ { provide: JOIPIPE_OPTIONS, useValue: { usePipeValidationException: true, }, }, ], }).compile(); app = module.createNestApplication(); // Silence the ExceptionHandler output on 500 app.useLogger(false); await app.init(); }); afterEach(async () => { await app.close(); }); it('should use the pipe correctly (positive test)', async () => { return request(app.getHttpServer()) .get('/?prop=foo') .expect(res => expect(res.body).toEqual({ status: 'OK', }), ); }); it('should use the pipe correctly (negative test)', async () => { return request(app.getHttpServer()) .get('/?prop=') .expect(res => expect(res.body).toMatchObject({ statusCode: 500, message: expect.stringContaining('Internal server error'), }), ); }); }); });
using UnityEngine; using System.Collections.Generic; public class InputProxy : MonoBehaviour { public static InputProxy Instance { get; private set; } public List<KeyCode> disabledKeys = new List<KeyCode>(); void Start() { Instance = this; } void OnDestroy() { Instance = null; } public bool GetKey(KeyCode key) { return !disabledKeys.Contains(key) && Input.GetKey(key); } }
package ru.ir.steam.dto; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.io.Serializable; @Data public class AcceptSellResponse implements Serializable { @JsonProperty("success") private boolean success; @JsonProperty("requires_confirmation") private int requiresConfirmation; @JsonProperty("needs_mobile_confirmation") private Boolean needsMobileConfirmation; @JsonProperty("needs_email_confirmation") private Boolean needsEmailConfirmation; @JsonProperty("email_domain") private String emailDomain; @JsonProperty("strError") private String strError; }
<?php session_start(); if(isset($_SESSION['userid'])){ header('location:home.php'); } $conn = new mysqli("localhost","root","","movie"); if(isset($_POST['btn'])) { //Get values passed from form in login.php file $username = $_POST['user']; $password = $_POST['pass']; //To prevent MySql injection $username = mysqli_real_escape_string($conn, $username); $password = mysqli_real_escape_string($conn, $password); // ?? $password = md5($password); // Check connection if ($conn->connect_error) { die("Connection failed: \n" . $conn->connect_error); } //Query the database for user $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password' "; $result = $conn->query($sql); $row = mysqli_fetch_array($result); if($row['username'] == $username && $row['password'] == $password){ $_SESSION['userid'] = $row['userid']; $_SESSION['username'] = $username; //included home as header header("location:home.php"); } else{ $_SESSION['message']="Username and Password do not match"; } $conn->close(); } ?> <!DOCTYPE html> <html> <head> <title> login page </title> <link rel="stylesheet" type="text/css" href="login_style.css"> </head> <body> <?php if(isset($_SESSION['message'])) { echo "<div id='error_msg'>".$_SESSION['message']."</div>"; unset($_SESSION['message']); } ?> <div id="frm"> <form action="login.php" method="POST"> <p> <label>Username: </label> <input type="text" id="user" name="user" /> </p> <p> <label>Password: </label> <input type="password" id="pass" name="pass" /> </p> <br> <div> <a href="register.php" class="button">New User? Sign up!</a> <input type="submit" id="btn" name = "btn" value="Login" /> </div> </form> </div> </body> </html>
<?php class org_glizy_middleware_DynamicPage extends org_glizy_middleware_AbstractHttpCache { public function beforeProcess($pageId, $pageType) { } public function afterRender($content) { $this->etag = md5($content.var_export(__Request::getAllAsArray(), true)); $this->checkIfIsChanged(); } }
env :PATH, ENV['PATH'] every 5.minutes do runner 'Schedule.schedule; Run.schedule' end every 1.minutes do check = '(ps aux | grep sidekiq | grep -v grep) > /dev/null' restart = "(cd #{path} && bundle exec cap localhost sidekiq:restart)" command "#{check} || #{restart}" end every 1.day do rake 'sessions:clear' end
-- @testpoint:opengauss关键字procedural非保留),作为序列名 --关键字不带引号-成功 drop sequence if exists procedural; create sequence procedural start 100 cache 50; drop sequence procedural; --关键字带双引号-成功 drop sequence if exists "procedural"; create sequence "procedural" start 100 cache 50; drop sequence "procedural"; --关键字带单引号-合理报错 drop sequence if exists 'procedural'; --关键字带反引号-合理报错 drop sequence if exists `procedural`;
package util import ( "path" "path/filepath" "strings" ) func ChangeExtension(filename, newExt string) string { file := filepath.Base(filename) return strings.TrimSuffix(file, path.Ext(file)) + newExt }
export class ForwardRef<T = any> { constructor(private forwardRefFn: () => T) { } getRef() { return this.forwardRefFn(); } } /** * 引用后声明的类的工具函数 * @param fn */ export function forwardRef<T>(fn: () => T) { return new ForwardRef<T>(fn); }
import React, { useCallback, useContext, useEffect } from 'react'; import { useSelector } from 'react-redux'; import { gameSelector } from '../../../../features/game'; import { gameSocketMsg, SocketSendTag } from '../../../../socket'; import { SecondaryAction } from '../../_shared_/SecondaryAction'; import { RaiseContext } from '../../RaiseContext'; import { AutoAction } from '../../constants'; type Props = {}; export const QuitAction: React.FC<Props> = () => { const tableName = useSelector(gameSelector.get('name')); const street = useSelector(gameSelector.get('_street')); const { autoAction, toggleAutoAction } = useContext(RaiseContext); const isActive = autoAction === AutoAction.Leave; useEffect(() => { if (isActive) { gameSocketMsg({ tag: SocketSendTag.LeaveSeat, contents: tableName, }); } }, [isActive, tableName, street]); return ( <SecondaryAction active={isActive} onClick={() => toggleAutoAction(AutoAction.Leave)} > Quit </SecondaryAction> ); };
from yggdrasil.metaschema.encoder import encode_yaml, decode_yaml from yggdrasil.serialize.JSONSerialize import JSONSerialize class YAMLSerialize(JSONSerialize): r"""Class for serializing a python object into a bytes message using YAML. Args: indent (str, int, optional): String or number of spaces that should be used to indent each level within the seiralized structure. Defaults to '\t'. encoding (str, optional): Encoding that should be used to serialize the object. Defaults to 'utf-8'. default_flow_style (bool, optional): If True, nested collections will be serialized in the block style. If False, they will always be serialized in the flow style. See `PyYAML Documentation <https://pyyaml.org/wiki/PyYAMLDocumentation>`_. """ _seritype = 'yaml' _schema_subtype_description = ('Serializes Python objects using the YAML ' 'standard.') _schema_properties = { 'indent': {'type': ['string', 'int'], 'default': '\t'}, 'encoding': {'type': 'string', 'default': 'utf-8'}, 'default_flow_style': {'type': 'boolean', 'default': False}} _schema_excluded_from_inherit = ['sort_keys'] def func_serialize(self, args): r"""Serialize a message. Args: args (obj): Python object to be serialized. Returns: bytes, str: Serialized message. """ return encode_yaml(args, indent=self.indent, encoding=self.encoding, default_flow_style=self.default_flow_style) def func_deserialize(self, msg): r"""Deserialize a message. Args: msg (str, bytes): Message to be deserialized. Returns: obj: Deserialized Python object. """ return decode_yaml(msg) @classmethod def get_testing_options(cls, **kwargs): r"""Method to return a dictionary of testing options for this class. Returns: dict: Dictionary of variables to use for testing. """ # iobj = {'a': ['b', int(1), float(1.0)], 'c': {'z': 'hello'}} iobj1 = {'a': ['b', int(1), float(1.0)], 'c': {'z': 'hello'}} iobj2 = {'d': 'new field'} # iobj3 = int(2) # iobj4 = [float(2.0)] out = {'kwargs': {}, 'empty': {}, 'dtype': None, 'extra_kwargs': {}, 'objects': [iobj1, iobj2], # , iobj3, iobj4], 'typedef': {'type': 'object'}} out['contents'] = (b'a:\n- b\n- 1\n- 1.0\n' b'c:\n z: hello\n' b'd: new field\n') # out['contents'] = (b'- a:\n - b\n - 1\n - 1.0\n' # b' c:\n z: hello\n' # b' d: new field\n' # b'- 2\n- 2.0\n') return out
(ns simple-symbolic-regression-clojure.interpreter (:use [clojure.math.numeric-tower]) ) ;;; Interpreter (defn translate-op [op] "Translate operators from the symbolic regression language to the appropriate Clojure operator for evaluation. A key goal here is replacing +, -, and * with +', -', and *' so we don't have unexpected overflow exceptions." (condp = op :+ +' :- -' :* *' :÷ / op)) (defn legal-division-stack? [stack] (not (zero? (peek stack)))) (defn legal-binary-op-stack? [op stack] (and (>= (count stack) 2) (or (not (= op :÷)) (legal-division-stack? stack)))) (defn process-binary-operator [op stack] "Apply a binary operator to the given stack, returning the updated stack" (if (legal-binary-op-stack? op stack) (let [arg2 (peek stack) arg1 (peek (pop stack)) new-stack (pop (pop stack))] (conj new-stack ((translate-op op) arg1 arg2))) stack)) (defn binary-operator? [token] (contains? #{:+ :- :* :÷} token)) ; We might consider throwing an exception in the :else ; case instead of returning to help alert (human) programmers ; of errors in things like bindings and undefined tokens. (defn process-token "Process given token returning the updated stack" ([stack token] (process-token {} stack token)) ([bindings stack token] (cond (contains? bindings token) (conj stack (bindings token)) (number? token) (conj stack token) (binary-operator? token) (process-binary-operator token stack) :else stack) )) (defn run-script [script bindings] "loop over every item in the script and modify the stack accordingly" (reduce (partial process-token bindings) [] script) ) (defn interpret [script bindings] (let [stack (run-script script bindings) answer (peek stack)] {:result answer, :stack stack})) ;;; Rubrics (defrecord Rubric [input output]) (def score-penalty 100000000000000000000N) (defn score-on [script rubric] (if-let [result (:result (interpret script (:input rubric)))] (abs (- (:output rubric) result)) score-penalty)) ;; Using pmap here leads to thrashing and poor performance. (defn total-score-on [_ script rubrics] (reduce + (map (partial score-on script) rubrics))) (defn thingy-for-the-agent [script rubrics scoreBox] (swap! scoreBox (total-score-on script rubrics)))
// WITH_RUNTIME // NO_INTERCEPT_RESUME_TESTS class Controller { var result = "" suspend fun <T> suspendAndLog(value: T): T = suspendWithCurrentContinuation { c -> result += "suspend($value);" c.resume(value) Suspend } // Tail calls are not allowed to be Nothing typed. See KT-15051 suspend fun suspendLogAndThrow(exception: Throwable): Any? = suspendWithCurrentContinuation { c -> result += "throw(${exception.message});" c.resumeWithException(exception) Suspend } operator fun handleException(exception: Throwable, c: Continuation<Nothing>) { result += "caught(${exception.message});" } } fun builder(coroutine c: Controller.() -> Continuation<Unit>): String { val controller = Controller() c(controller).resume(Unit) return controller.result } fun box(): String { val value = builder { try { try { suspendAndLog("1") suspendLogAndThrow(RuntimeException("exception")) } catch (e: RuntimeException) { suspendAndLog("caught") suspendLogAndThrow(RuntimeException("fromCatch")) } } finally { suspendAndLog("finally") } suspendAndLog("ignore") } if (value != "suspend(1);throw(exception);suspend(caught);throw(fromCatch);suspend(finally);caught(fromCatch);") { return "fail: $value" } return "OK" }
from collections import namedtuple from games import (Game) class GameState: def __init__(self, to_move, board, label=None): self.to_move = to_move self.board = board self.label = label def __str__(self): if self.label == None: return super(GameState, self).__str__() return self.label class Hex(Game): """ """ def __init__(self, h=5, v=5): self.h = h self.v = v # self.blueWin = ((1, 1), (1, 2), (1, 3)) # self.redWin = ((1, 3), (2, 3), (3, 3)) self.initial = GameState(to_move='B', board={}) def actions(self, state): try: return state.moves except: pass "Legal moves are any square not yet taken." moves = [] for x in range(1, self.h + 1): for y in range(1, self.v + 1): if (x, y) not in state.board.keys(): moves.append((x, y)) state.moves = moves return moves # defines the order of play def opponent(self, player): if player == 'B': return 'R' if player == 'R': return 'B' return None def result(self, state, move): if move not in self.actions(state): return state # Illegal move has no effect board = state.board.copy() player = state.to_move board[move] = player next_mover = self.opponent(player) return GameState(to_move=next_mover, board=board) def utility(self, state, player): "Return the value to player; 1 for win, -1 for loss, 0 otherwise." try: return state.utility if player == 'B' else -state.utility except: pass board = state.board util = self.check_win(board, 'B') if util == 0: util = -self.check_win(board, 'R') state.utility = util return util if player == 'B' else -util # Did I win? def check_win(self, board, player): if player == 'B': for y in range(1, self.v + 1): if board.get((1, y)) == player and self.check_blue(board, (1, y), player, (1, 0)) == 1: return 1 return 0 if player == 'R': for x in range(1, self.h + 1): if board.get((x, 1)) == player and self.check_red(board, (x, 1), player, (0, 1)) == 1: return 1 return 0 else: return 0 def check_blue(self, board, start, player, direction): (delta_x, delta_y) = direction (start_x, start_y) = start x, y = start_x + delta_x, start_y + delta_y # check if board.get((x, y)) == player: if x == self.h: return 1 else: return self.check_blue(board, (x, y), player, (1, 0)) else: if direction == (1, 0): # if down direction = (1, -1) # down and left elif direction == (1, -1): # if down and left direction = (1, 1) # down and right else: return 0 return self.check_blue(board, start, player, direction) def check_red(self, board, start, player, direction): (delta_x, delta_y) = direction (start_x, start_y) = start x, y = start_x + delta_x, start_y + delta_y # check if board.get((x, y)) == player: if y == self.v: return 1 else: return self.check_red(board, (x, y), player, (0, 1)) else: if direction == (0, 1): # if right direction = (-1, 1) # right and up elif direction == (-1, 1): # if right and up direction = (1, 1) # right and down else: return 0 return self.check_red(board, start, player, direction) def terminal_test(self, state): "A state is terminal if it is won or there are no empty squares." return self.utility(state, 'B') != 0 or len(self.actions(state)) == 0 def display(self, state): board = state.board for x in range(1, self.h + 1): for y in range(1, self.v + 1): print(board.get((x, y), '.'), end=' ') print() myGame = Hex() myGames = { myGame: [ ] }
require "rails_helper" RSpec.shared_examples_for "paginable" do let(:model) { described_class } let!(:bucketlists) { create_list(:bucketlist, 10) } context "when page 1" do it "returns paginated records" do results = model.paginate(page: 1, limit: 5) expect(results.size).to eq(5) expect(results.first).to eq(Bucketlist.first) end end context "when page 2" do it "returns paginated records" do results = model.paginate(page: 2, limit: 5) expect(results.size).to eq(5) expect(results.first).to eq(Bucketlist.all[5]) end end end
# frozen_string_literal: true # 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. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Api # Configuration controlling usage of a service. # @!attribute [rw] requirements # @return [::Array<::String>] # Requirements that must be satisfied before a consumer project can use the # service. Each requirement is of the form <service.name>/<requirement-id>; # for example 'serviceusage.googleapis.com/billing-enabled'. # @!attribute [rw] rules # @return [::Array<::Google::Api::UsageRule>] # A list of usage rules that apply to individual API methods. # # **NOTE:** All service configuration rules follow "last one wins" order. # @!attribute [rw] producer_notification_channel # @return [::String] # The full resource name of a channel used for sending notifications to the # service producer. # # Google Service Management currently only supports # [Google Cloud Pub/Sub](https://cloud.google.com/pubsub) as a notification # channel. To use Google Cloud Pub/Sub as the channel, this must be the name # of a Cloud Pub/Sub topic that uses the Cloud Pub/Sub topic name format # documented in https://cloud.google.com/pubsub/docs/overview. class Usage include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Usage configuration rules for the service. # # NOTE: Under development. # # # Use this rule to configure unregistered calls for the service. Unregistered # calls are calls that do not contain consumer project identity. # (Example: calls that do not contain an API key). # By default, API methods do not allow unregistered calls, and each method call # must be identified by a consumer project identity. Use this rule to # allow/disallow unregistered calls. # # Example of an API that wants to allow unregistered calls for entire service. # # usage: # rules: # - selector: "*" # allow_unregistered_calls: true # # Example of a method that wants to allow unregistered calls. # # usage: # rules: # - selector: "google.example.library.v1.LibraryService.CreateBook" # allow_unregistered_calls: true # @!attribute [rw] selector # @return [::String] # Selects the methods to which this rule applies. Use '*' to indicate all # methods in all APIs. # # Refer to {::Google::Api::DocumentationRule#selector selector} for syntax details. # @!attribute [rw] allow_unregistered_calls # @return [::Boolean] # If true, the selected method allows unregistered calls, e.g. calls # that don't identify any user or application. # @!attribute [rw] skip_service_control # @return [::Boolean] # If true, the selected method should skip service control and the control # plane features, such as quota and billing, will not be available. # This flag is used by Google Cloud Endpoints to bypass checks for internal # methods, such as service health check methods. class UsageRule include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end end
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using NWebsec.Core.Common.HttpHeaders; using NWebsec.Core.Common.HttpHeaders.Configuration; using NWebsec.Core.Common.Middleware.Options; using NWebsec.Owin.Core; using NWebsec.Owin.Helpers; namespace NWebsec.Owin.Middleware { using AppFunc = Func<IDictionary<string, object>, Task>; public class HstsMiddleware : MiddlewareBase { private readonly IHstsConfiguration _config; private readonly HeaderResult _headerResult; private const string Https = "https"; public HstsMiddleware(AppFunc next, HstsOptions options) : base(next) { _config = options; var headerGenerator = new HeaderGenerator(); _headerResult = headerGenerator.CreateHstsResult(_config); } internal override void PreInvokeNext(OwinEnvironment owinEnvironment) { if (_config.HttpsOnly && !Https.Equals(owinEnvironment.RequestScheme, StringComparison.OrdinalIgnoreCase)) { return; } if (_config.UpgradeInsecureRequests && !CspUpgradeHelper.UaSupportsUpgradeInsecureRequests(owinEnvironment)) { return; } if (_headerResult.Action == HeaderResult.ResponseAction.Set) { owinEnvironment.ResponseHeaders.SetHeader(_headerResult.Name, _headerResult.Value); } } } }
{-# LANGUAGE FlexibleInstances #-} module SimpleJSON ( JValue(..), renderJValue, pretty, compact ) where import Numeric (showHex) import Data.Bits (shiftR, (.&.)) import Data.Char (ord) import Control.Arrow (second) data JValue = JString String | JNumber Double | JBool Bool | JNull | JObject (JObj JValue) | JArray (JAry JValue) deriving (Eq, Ord, Show) data Doc = Empty | Char Char | Text String | Line | Concat Doc Doc | Union Doc Doc deriving (Show) type JError = String -- avoid OverlappingInstances newtype JAry a = JAry { fromJAry :: [a] } deriving (Eq, Ord, Show) newtype JObj a = JObj { fromJObj :: [(String, a)] } deriving (Eq, Ord, Show) class JSON a where toJValue :: a -> JValue fromJValue :: JValue -> Either JError a instance JSON JValue where toJValue = id fromJValue = Right instance JSON Bool where toJValue = JBool fromJValue (JBool b) = Right b fromJValue _ = Left "Not a JSON Boolean" -- in Haskell 98, need LANGUAGE TypeSynonymInstances -- instance cannot use [Char] instead of [] Char instance JSON String where toJValue = JString fromJValue (JString s) = Right s fromJValue _ = Left "Not a JSON String" doubleToJValue :: (Double -> a) -> JValue -> Either JError a doubleToJValue f (JNumber v) = Right (f v) doubleToJValue _ _ = Left "Not a JSON Number" instance JSON Int where toJValue = JNumber . realToFrac fromJValue = doubleToJValue round instance JSON Integer where toJValue = JNumber . realToFrac fromJValue = doubleToJValue round instance JSON Double where toJValue = JNumber fromJValue = doubleToJValue id {- Overlappable instance (JSON a) => JSON [a] where toJValue = undefined fromJValue = undefined instance (JSON a) => JSON [(String, a)] where toJValue = undefined fromJValue = undefined -} jAryFromJValue :: (JSON a) => JValue -> Either JError (JAry a) jAryFromJValue (JArray (JAry a)) = whenRight JAry (mapEithers fromJValue a) jAryFromJValue _ = Left "Not a JSON Array" whenRight :: (b -> c) -> Either a b -> Either a c whenRight _ (Left err) = Left err whenRight f (Right a) = Right (f a) mapEithers :: (a -> Either b c) -> [a] -> Either b [c] mapEithers f (x:xs) = case mapEithers f xs of Left err -> Left err Right ys -> case f x of Left err -> Left err Right y -> Right (y:ys) mapEithers _ _ = Right [] jAryToJValue :: (JSON a) => JAry a -> JValue jAryToJValue = JArray . JAry . map toJValue . fromJAry instance (JSON a) => JSON (JAry a) where toJValue = jAryToJValue fromJValue = jAryFromJValue instance (JSON a) => JSON (JObj a) where toJValue = JObject . JObj . map (second toJValue) . fromJObj fromJValue (JObject (JObj o)) = whenRight JObj (mapEithers unwrap o) where unwrap (k,v) = whenRight ((,) k) (fromJValue v) fromJValue _ = Left "not a JSON object" empty :: Doc empty = Empty char :: Char -> Doc char c = Char c text :: String -> Doc text "" = Empty text s = Text s double :: Double -> Doc double d = text (show d) line :: Doc line = Line string :: String -> Doc string = enclose '"' '"' . hcat . map oneChar enclose :: Char -> Char -> Doc -> Doc enclose l r x = char l <> x <> char r (<>) :: Doc -> Doc -> Doc Empty <> y = y x <> Empty = x x <> y = x `Concat` y hcat :: [Doc] -> Doc hcat xs = fold (<>) xs fold :: (Doc -> Doc -> Doc) -> [Doc] -> Doc fold f = foldr f empty oneChar :: Char -> Doc oneChar c = case lookup c simpleEscapes of Just r -> text r Nothing | mustEscape c -> hexEscape c | otherwise -> char c where mustEscape c = c < ' ' || c == '\x7f' || c > '\xff' simpleEscapes :: [(Char, String)] simpleEscapes = zipWith ch "\b\n\f\r\t\\\"/" "bnfrt\\\"/" where ch a b = (a, ['\\', b]) hexEscape :: Char -> Doc hexEscape c | d < 0x10000 = smallHex d | otherwise = astral (d - 0x10000) where d = ord c -- smallHex only support 0000-FFFF smallHex :: Int -> Doc smallHex x = text "\\u" <> text (replicate (4 - length h) '0') <> text h where h = showHex x "" -- fix 0000-10FFFF astral :: Int -> Doc astral n = smallHex (a + 0xd800) <> smallHex (b + 0xdc00) where a = (n `shiftR` 10) .&. 0x3ff b = n .&. 0x3ff series :: Char -> Char -> (a -> Doc) -> [a] -> Doc series open close f = enclose open close . fsep . punctuate (char ',') . map f fsep :: [Doc] -> Doc fsep = fold (</>) (</>) :: Doc -> Doc -> Doc x </> y = x <> softline <> y softline :: Doc softline = group line group :: Doc -> Doc group x = flatten x `Union` x flatten :: Doc -> Doc flatten (x `Concat` y) = flatten x `Concat` flatten y flatten Line = Char ' ' flatten (x `Union` _) = flatten x flatten other = other punctuate :: Doc -> [Doc] -> [Doc] punctuate p [] = [] punctuate p [d] = [d] punctuate p (d:ds) = (d <> p) : punctuate p ds compact :: Doc -> String compact x = transform [x] where transform [] = "" transform (d:ds) = case d of Empty -> transform ds Char c -> c : transform ds Text s -> s ++ transform ds Line -> '\n' : transform ds a `Concat` b -> transform (a:b:ds) _ `Union` b -> transform (b:ds) pretty :: Int -> Doc -> String pretty width x = best 0 [x] where best col (d:ds) = case d of Empty -> best col ds Char c -> c : best (col+1) ds Text s -> s ++ best (col + length s) ds Line -> '\n' : best 0 ds a `Concat` b -> best col (a:b:ds) a `Union` b -> nicest col (best col (a:ds)) (best col (b:ds)) best _ _ = "" nicest col a b | (width - least) `fits` a = a | otherwise = b where least = min width col fits :: Int -> String -> Bool w `fits` _ | w < 0 = False w `fits` "" = True w `fits` ('\n':_) = True w `fits` (c:cs) = (w - 1) `fits` cs getString :: JValue -> Maybe String getString (JString s) = Just s getString _ = Nothing getInt (JNumber n) = Just (truncate n) getInt _ = Nothing getDouble (JNumber n) = Just n getDouble _ = Nothing getBool (JBool b) = Just b getBool _ = Nothing getObject (JObject o) = Just o getObject _ = Nothing getArray (JArray a) = Just a getArray _ = Nothing isNull v = v == JNull renderJValue :: JValue -> Doc renderJValue (JString s) = string s renderJValue (JNumber n) = double n renderJValue (JBool True) = text "true" renderJValue (JBool False) = text "false" renderJValue JNull = text "null" renderJValue (JArray a) = series '[' ']' renderJValue (fromJAry a) renderJValue (JObject o) = series '{' '}' field (fromJObj o) where field (name, val) = string name <> text ": " <> renderJValue val {- renderJValue (JObject o) = "{" ++ pairs o ++ "}" where pairs [] = "" pairs ps = intercalate ", " (map renderPair ps) renderPair (k, v) = show k ++ " " ++ renderJValue v -} {- renderJValue (JArray a) = "[" ++ values a ++ "]" where values [] = "" values vs = intercalate ", " (map renderJValue vs) -}
sudo apt install python3-pip sudo /usr/bin/python3 -m pip install --upgrade pip sudo pip3 install enquiries sudo pip3 install requests sudo pip3 install colorama cd Tools/torghost ./build.sh echo Process finish, now you can run delvedleak.py
using UnityEngine; public interface IDamageable { void GetDamage(float damageValue); }
# Developer Guide This guide is intended for plugin developers. If you are not developing kubectl plugins, read the [User Guide](./USER_GUIDE.md) to learn how to use krew. This guide explains how to package, test, run plugins locally and make them available on the krew index. <!-- TOC depthFrom:2 --> - [Developing a Plugin](#developing-a-plugin) - [Packaging plugins for krew](#packaging-plugins-for-krew) - [Writing a plugin manifest](#writing-a-plugin-manifest) - [Specifying platform-specific instructions](#specifying-platform-specific-instructions) - [Specifying files to install](#specifying-files-to-install) - [Specifying plugin executable](#specifying-plugin-executable) - [Specifying a plugin download URL](#specifying-a-plugin-download-url) - [Installing Plugins Locally](#installing-plugins-locally) - [Publishing Plugins](#publishing-plugins) - [Submitting a plugin to krew](#submitting-a-plugin-to-krew) - [Updating existing plugins](#updating-existing-plugins) <!-- /TOC --> ## Developing a Plugin Before creating a plugin, read the [Kubernetes Plugins documentation][plugins]. **If you are writing a plugin in Go:** Consider using the [cli-runtime](https://github.com/kubernetes/cli-runtime/) project which is designed to provide the same command-line arguments, kubeconfig parser, Kubernetes API REST client, and printing logic. **Unofficial Quickstart for Go:** For Go plugins, there's a [GitHub template repo](https://github.com/replicatedhq/krew-plugin-template) that implements these best practices and also configures GoReleaser and a GitHub Action to create releases when a tag is pushed. Note: this template repo is not maintained by the Krew project. Below you will create a small plugin named `foo` which prints the environment variables to the screen and exits. Read the [Naming Guide](./NAMING_GUIDE.md) for choosing a name for your plugin. Create an executable file named `kubectl-foo` with the following contents: ```bash #!/usr/bin/env bash env ``` Then make this script executable: chmod +x ./kubectl-foo (Since this plugin requires `bash`, it will only work on Unix platforms. If you need to support windows, develop a `kubectl-foo.exe` executable.) Now, if you place this plugin to anywhere in your `$PATH` directories, you should be able to call it like: kubectl foo ### Packaging plugins for krew To package a plugin via krew, you need to: 1. Develop a plugin and archive it into a `.zip` or `.tar.gz`. 2. Write a [plugin manifest file](#writing-a-plugin-manifest). 3. Test installation locally with the archive and the manifest file. To publish a plugin in `krew-index` to make it available via krew, you need to: 1. Make the plugin source code publicly available. 1. Make the archive file (`.zip` or `.tar.gz`) **publicly downloadable** on a URL (you can host it yourself or use GitHub releases feature). 1. Submit the plugin manifest file to the [krew index][index] repository. Plugin packages need to be available to download from the public Internet. A service like [GitHub Releases](https://help.github.com/articles/creating-releases/) is recommended. ### Writing a plugin manifest Each krew plugin has a "plugin manifest" file that lives in the [krew index repository][index]. This file describes which files krew must copy out of your plugin archive and how to run your plugin. It is also used to determine if an upgrade to your plugin is available and how to install it. For a plugin named `foo`, the plugin manifest file should be named `foo.yaml`. An example manifest for this plugin that runs only on Linux and macOS looks like this (see [krew index](https://github.com/kubernetes-sigs/krew-index/tree/master/plugins) for all plugin manifests): ```yaml apiVersion: krew.googlecontainertools.github.com/v1alpha2 kind: Plugin metadata: name: foo # plugin name must match your manifest file name (e.g. foo.yaml) spec: version: "v0.0.1" # required, must be in semver format, prefixed with "v" platforms: # specify installation script for linux and darwin (macOS) - selector: # a regular Kubernetes selector matchExpressions: - {key: os, operator: In, values: [darwin, linux]} # url for downloading the package archive: uri: https://github.com/example/foo/releases/v1.0.zip # sha256sum of the above archive file: sha256: "208fde0b9f42ef71f79864b1ce594a70832c47dc5426e10ca73bf02e54d499d0" # copy the used files out of the zip archive, defaults to `[{from: "*", to: "."}]` files: - from: "foo-*/unix/*.sh" # path to the files extracted from archive to: "." # '.' refers to the root of plugin install directory - from: "foo-*/LICENSE" # always install your LICENSE file to: "." bin: "kubectl-foo" # path to the plugin executable after copying files above shortDescription: >- # short description gets truncated at ~50 chars Prints the environment variables. # (optional) url of the project homepage homepage: https://github.com/kubernetes-sigs/krew # (optional) use caveats field to show post-installation recommendations caveats: | This plugin needs the following programs: * env(1) description: | # should print nicely on standard 80 char wide terminals This plugin shows all environment variables that get injected when launching a program as a plugin. You can use this field for longer description and example usages. ``` #### Specifying platform-specific instructions krew makes it possible to install the same plugin on different operating systems (like `windows`, `darwin` (macOS), and `linux`) and different architectures (like `amd64`, `386`, `arm`). To support multiple platforms, you may need to define multiple `platforms` in the plugin manifest. The `selector` field matches to operating systems and architectures using the keys `os` and `arch` respectively. **Example:** Match to Linux: ```yaml platforms: - selector: matchLabels: os: linux ``` **Example:** Match to a Linux or macOS platform, any architecture: ```yaml ... platforms: - selector: # A regular Kubernetes label selector matchExpressions: - {key: os, operator: In, values: [darwin, linux]} ``` **Example:** Match to Windows 64-bit: ```yaml platforms: - selector: matchLabels: os: windows arch: amd64 ``` The possible values for `os` and `arch` come from the Go runtime. Run `go tool dist list` to see all possible platforms and architectures. #### Specifying files to install Each operating system may require a different set of files from the archive to be installed. You can use the `files` field in the plugin manifest to specify which files should be copied into the plugin directory after extracting the plugin archive. The `files:` list specifies the copy operations (like `mv(1) <from> <to>`) to the files `from` the archive `to` the installation destination. If the `files` list is unspecified, it defaults to `[{from: "*", to: "."}]`. Mind that a wildcard may install more files than desired. **Example:** Consider a plugin whose extracted archive looks like ```text . ├── README.txt ├── README.txt └── bin │   └── kubectl-foo-linux └── kubectl-foo-windows.exe ``` - To copy all files in the `bin/` directory of the extracted archive to the root of your plugin, leave out the `files:` field, which is equivalent to ```yaml files: [{from: "*", to: "."}] ``` This copies out binaries for both platforms to the installation directory onto the user’s machine, despite only one of them will be used: ```text . └── krew-foo-windows.exe └── krew-foo-linux ``` - For a more fine-grained control, specify each copy operation: ```yaml files: - from: bin/*.exe to: . ``` This will result in the following files in the installation directory: ```text . └── krew-foo-windows.exe ``` #### Specifying plugin executable Each `platform` field requires a path to the plugin executable in the plugin's installation directory. krew creates a symbolic link to the plugin executable specified in the `bin` field in `$HOME/.krew/bin/` (which all krew users need to add to their `$PATH`). For example, if your plugin executable is named `start-foo.sh`, specify: ```yaml platforms: - bin: "./start-foo.sh" ... ``` krew will create a [symbolic link](https://en.wikipedia.org/wiki/Symbolic_link) named `kubectl-foo` (and `kubectl-foo.exe` on Windows) to your plugin executable after installation is complete. The name of the symbolic link comes from the plugin name. > **Note on underscore conversion:** If your plugin name contains dashes, krew > will automatically convert them to underscores for kubectl to be able to find > your plugin. > > For example, if your is named `view-logs` and your plugin binary is named > `run.sh`, krew will create a symbolic named `kubectl-view_logs` automatically. #### Specifying a plugin download URL krew plugins must be packaged as `.zip` or `.tar.gz` archives and should be made available for download publicly. Downloading from a URL also requires a checksum of the downloaded content: - `uri`: URL to the archive file (`.zip` or `.tar.gz`) - `sha256`: sha256 sum of the archive file ```yaml platforms: - uri: https://github.com/barbaz/foo/archive/v1.2.3.zip sha256: "29C9C411AF879AB85049344B81B8E8A9FBC1D657D493694E2783A2D0DB240775" ... ``` ## Installing Plugins Locally After you have: - written your `<PLUGIN>.yaml` - archived your plugin into a `.zip` or `.tar.gz` file you can now test whether your plugin installs correctly on krew by running: ```bash kubectl krew install --manifest=foo.yaml --archive=foo.tar.gz ``` - `--manifest` flag specifies a custom manifest rather than picking it up from the default [krew index][index] - `--archive` overrides the download `url` specified in the plugin manifest and uses a local file instead. If the installation fails, run the command with `-v=4` flag for verbose logs. If your installation has succeeded, you should be able to run: kubectl foo If you made your archive file available to download on the Internet, run the same command without `--archive` and actually test downloading the file from `url`. If you need other `platforms` definitions that don't match your current machine, you can use `KREW_OS` and/or `KREW_ARCH` environment variables. For example, if you're on a Linux machine, you can test Windows installation with: KREW_OS=windows krew install --manifest=[...] After you have tested your plugin, uninstall it with `kubectl krew uninstall foo`. ## Publishing Plugins ### Submitting a plugin to krew After you have tested that the plugin can be installed and works you should create a pull request to the [Krew Index][index] with your `<PLUGIN>.yaml` manifest file. The new plugin file should be submitted to the `plugins/` directory in the index repository. After the pull request gets accepted into the main index, the plugin will be available for all users. Please make sure to include dependencies of your plugin and extra configuration needed to run the plugin in the `caveats:` field. ### Updating existing plugins When you have a newer version of your plugin, create a new pull request that updates thew `version`, `uri` and `sha256` fields of the plugin manifest file. Ideally, the `version` specified should match the release tag of the plugin. This helps users and maintainers to easily identify which version of the plugin they have installed. [index]: https://github.com/kubernetes-sigs/krew-index [plugins]: https://kubernetes.io/docs/tasks/extend-kubectl/kubectl-plugins/
package de.adorsys.dfs.connection.api.domain; import java.io.Closeable; import java.io.InputStream; /** * Created by peter on 05.03.18 at 08:33. */ public interface PayloadStream extends Closeable { /** * returns the inputstream of the data. The receiver is responsible for closing the stream */ InputStream openStream(); }
addEventListener('fetch', (e) => { e.respondWith(new Response('Page ok')) })
import { CoordGrid, Node } from 'engine/models'; import _config from 'engine/config'; import _map from 'engine/map'; import _coords from './coords'; /** * Checks whether the provided coordinates lie within the zone specified * @param from The start coords of the zone * @param to The end coords of the zone (inclusive) * @param coords The coordinates to check */ export function inZone(from: CoordGrid, to: CoordGrid, coord: CoordGrid): boolean { return MAP_ENGINE.inZone(from, to, coord); } export function getCoordHash(coords: CoordGrid): number { return ENGINE.getCoordHash(coords); } export function getGlobalCoord(squareCoord: number, localCoord: number): number { return (localCoord + ((squareCoord & 0xff) << 6)); } export function getRotatedCoord( srcCoord: CoordGrid, zoneCoord: CoordGrid, mapRotation: number, locTypeId: number, locRotation: number ) { let tmp; let sizeX = _config.locSizeX(locTypeId); let sizeY = _config.locSizeY(locTypeId); if ((locRotation & 0x1) === 1) { tmp = sizeX; sizeX = sizeY; sizeY = tmp; } let localX = _map.getCoordX(srcCoord) & 0x7; let localY = _map.getCoordY(srcCoord) & 0x7; if (mapRotation == 1) { tmp = localX; localX = localY; localY = 7 - tmp - (sizeX - 1); } else if (mapRotation == 2) { localX = 7 - localX - (sizeX - 1); localY = 7 - localY - (sizeY - 1); } else if (mapRotation == 3) { tmp = localX; localX = 7 - localY - (sizeY - 1); localY = tmp; } return _coords(zoneCoord, localX, localY, 0); } export function getZoneCoord (node: Node) { var zoneX = _map.getLocalX(node) >> 3; var zoneY = _map.getLocalY(node) >> 3; var level = _map.getLevel(node); return _coords(level, _map.getSquareX(node), _map.getSquareY(node), zoneX << 3, zoneY << 3); }
<?php namespace Sujip\PayPal\Notification\Http; use Exception; use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; use Sujip\PayPal\Notification\Contracts\Service; use Sujip\PayPal\Notification\Exceptions\ServiceException; use Sujip\PayPal\Notification\Payload; /** * Class Request. * * @package Sujip\PayPal\Notification\Http */ class Request implements Service { /** * The guzzle http client. * * @var \GuzzleHttp\ClientInterface */ protected $client; /** * The service end-point. * * @var string */ protected $url; /** * Create a new request instance. * * @param \GuzzleHttp\Client $client * @param $url */ public function __construct(ClientInterface $client = null, $url = null) { $this->client = $client; $this->url = $url; } /** * @param Payload $payload */ public function call(Payload $payload) { $body = array_merge( ['cmd' => '_notify-validate'], $payload->all() ); try { $response = $this->client->post( $this->url, ['form_params' => $body] ); } catch (Exception $e) { throw new ServiceException($e->getMessage()); } return new Response( $response->getStatusCode(), $response->getHeaders(), $response->getBody(), $response->getProtocolVersion(), $response->getReasonPhrase() ); } }
export interface Erro500 { message: string; } export interface Erro412 { level?: string; schema?: Schema; instance?: Instance; domain?: string; keyword?: string; message?: string; required?: string[]; missing?: string[]; } export interface Instance { pointer?: string; } export interface Schema { loadingURI?: string; pointer?: string; } export interface ErroValidacao { mensagens?: Mensagens; } export interface Mensagens { advertencias?: Regra[]; informacoes?: Regra[]; erros?: Regra[]; } export interface Regra { regra?: number; mensagem?: string; }
#!/bin/sh # Installing waagent echo "***WA Agent Installation***" if [ -e /root/agent.py ]; then dos2unix -q /root/agent.py echo "Setting Execute bit on agent.py" chmod +x /root/agent.py mv /root/agent.py /usr/sbin/waagent /usr/sbin/waagent -setup sts=$? if [ 0 -eq ${sts} ]; then echo "waagent installed : SUCESS" else echo "waagent installation : FAILED " exit 1 fi else echo "waagent installation script not found..!!" echo "waagent installation : FAILED " fi #Verify Installation of waaagent if [ -e /etc/init.d/waagent ]; then echo "Verify Install waagent : SUCESS" else echo "Verify Install waagent : FAILED" exit fi
module Plink class CampaignRecord < ActiveRecord::Base self.table_name = 'campaigns' include Plink::LegacyTimestamps alias_attribute :campaign_hash, :urlCParam alias_attribute :media_type, :mediaType alias_attribute :is_incent, :isIncent attr_accessible :campaign_hash, :name, :media_type, :creative, :is_incent, :start_date, :end_date validates_presence_of :name def self.for_campaign_hash(campaign_hash) where('urlCParam = ?', campaign_hash).first end end end
# require 'date' # class Person def initialize(h) h.keys.each do |key| instance_variable_set(('@' + key.to_s).to_sym, h[key]) self.class.send(:attr_reader, key) end end def age dob = Date.parse(@dob) today = Date.today if dob.month > today.month || dob.month == today.month && dob.day >= today.day today <<= 12 # one year younger end today.year - dob.year end end
object Main extends App { val source = scala.io.Source.fromFile(args(0)) val lines = source.getLines.filter(_.length > 0) def swp(s: String): String = s.takeRight(1) + s.slice(1, s.length - 1) + s.take(1) for (l <- lines) println(l.split(" ").map(swp).mkString(" ")) }
import React from "react" import Tag from './tag' export default class Tags extends React.Component { render() { const { tags } = this.props; const Tags = (tags || []).map(tag => <Tag key={tag} tag={tag} />) return ( Tags ) } }
s = 0 x = int(input()) while x != 0: s += x x = int(input()) print(s)
# you can write to stdout for debugging purposes, e.g. # puts "this is a debug message" def solution(n) binary_n = convert_to_binary(n) current, longest = 0, 0 seen_start_one = false seen_end_one = false binary_n.each_char do |c| if c == "0" current += 1 longest = [longest, current].max else current = 0 end end longest end def convert_to_binary(n) return n.to_s if n < 2 digits = [] until n.zero? result, rem = n.divmod(2) digits.unshift(rem) n = result end digits.join end
package retail.storage import cats.data.State import cats.effect.IO import cats.effect.concurrent.Ref import retail.fsm.{ AllocationState, Command, Event, InventoryItemAdded, NewInventoryItem, NewOrderItem, OrderItemAdded } case class Persister(state: Ref[IO, List[Event]]) extends ((Command, AllocationState) => IO[List[Event]]) { override def apply(v1: Command, s1: AllocationState): IO[List[Event]] = state.modifyState { State { st => val e: Event = v1 match { case NewInventoryItem(uuid, sku, level, location) => InventoryItemAdded(uuid = uuid, sku = sku, level = level, location = location) case NewOrderItem(uuid, sku) => OrderItemAdded(uuid, sku) case _ => throw new UnsupportedOperationException("not implemented") } (e :: st, e :: Nil) } } }
package com.wuruoye.know.util.orm.table import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey /** * Created at 2019/4/9 20:27 by wuruoye * Description: */ @Entity(tableName = "record_item", indices = [Index("createTime", "recordId", "type", "typeId")]) class RecordItem( @PrimaryKey(autoGenerate = true) override var id: Long?, var recordId: Long, var type: Int, var typeId: Long, var content: String, override var createTime: Long, override var updateTime: Long ) : BaseTable { constructor(): this(null, -1, -1, -1, "", -1, -1) constructor(recordId: Long, typeId: Long, type: Int): this(null, recordId, type, typeId, "", -1, -1) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RecordItem if (id != other.id) return false if (recordId != other.recordId) return false if (type != other.type) return false if (typeId != other.typeId) return false if (content != other.content) return false if (createTime != other.createTime) return false if (updateTime != other.updateTime) return false return true } override fun hashCode(): Int { var result = id?.hashCode() ?: 0 result = 31 * result + recordId.hashCode() result = 31 * result + type result = 31 * result + typeId.hashCode() result = 31 * result + content.hashCode() result = 31 * result + createTime.hashCode() result = 31 * result + updateTime.hashCode() return result } }
var should = require('chai').should(); var sep = require('path').sep; var libFolder = __dirname + sep + 'lib' + sep; describe('end to end test', function() { var loadIntervalPtr; var loadInterval = 1; before(function(){ loadIntervalPtr = setInterval(function(){ var randomOpResult = ((Math.random() * Math.random()) * 100) % 10; }, loadInterval); }); after(function(){ clearInterval(loadIntervalPtr); }); it('gets just the memory usage', function(done) { this.timeout(10000); var procStats = require('../index.js'); memoryUsage = procStats.getMemoryUsage(); console.log(memoryUsage); done(); }); it('gets process stats passing in parameters', function(done) { this.timeout(10000); var procStats = require('../index.js'); procStats.stats({}, function(e, result){ if (e) return done(e); console.log(result); done(); }); }); it('gets process stats, without passing in parameters', function(done) { this.timeout(10000); var procStats = require('../index.js'); procStats.stats(function(e, result){ if (e) return done(e); console.log(result); done(); }); }); it('emits stats, n times', function(done) { this.timeout(40000); var procStats = require('../index.js'); var runAmounts = 0; var interval = setInterval(function(){ procStats.stats(function(e, result){ if (e){ clearInterval(interval); return done(e); } console.log(result); runAmounts++; if (runAmounts >= 10){ clearInterval(interval); done(); } }); }, 1000) }); });
################################################################################ # (C) Copyright 2016-2020 Hewlett Packard Enterprise Development LP # # 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. ################################################################################ require 'spec_helper' provider_class = Puppet::Type.type(:oneview_server_profile).provider(:c7000) describe provider_class, integration: true do let(:resource) do Puppet::Type.type(:oneview_server_profile).new( name: 'Server Profile', ensure: 'present', data: { 'name' => 'Test Server Profile', 'serverHardwareUri' => '172.18.6.6' }, provider: 'c7000' ) end let(:provider) { resource.provider } let(:instance) { provider.class.instances.first } before(:each) do provider.exists? end context 'given the minimum parameters' do it 'should be an instance of the provider c7000' do expect(provider).to be_an_instance_of Puppet::Type.type(:oneview_server_profile).provider(:c7000) end it 'should be able to create the server profile' do expect(provider.create).to be end it 'should be able to find the server profile with no filters' do resource['data'] = {} expect(provider.found).to be end it 'should be able to get_available_targets' do expect(provider.get_available_targets).to be end it 'should be able to get_available_networks' do expect(provider.get_available_networks).to be end it 'should be able to get_available_servers' do expect(provider.get_available_servers).to be end it 'should be able to get_available_storage_systems' do expect(provider.get_available_storage_systems).to be end it 'should be able to get_available_storage_system' do expect(provider.get_available_storage_system).to be end it 'should be able to get_profile_ports' do expect(provider.get_profile_ports).to be end it 'should be able to get_compliance_preview' do expect(provider.get_compliance_preview).to be end it 'should be able to get_messages' do expect(provider.get_messages).to be end it 'should be able to get_transformation' do expect(provider.get_transformation).to be end it 'should be able to update_from_template' do expect(provider.update_from_template).to be end it 'should raise errors for unavailable methods' do expect { provider.get_sas_logical_jbods }.to raise_error(/This ensure method is not available for C7000./) expect { provider.get_sas_logical_jbod_drives }.to raise_error(/This ensure method is not available for C7000./) expect { provider.get_sas_logical_jbod_attachments }.to raise_error(/This ensure method is not available for C7000./) end it 'should be able to update the server profile' do resource['data'] = { 'name' => 'Test Server Profile', 'new_name' => 'Edited SP' } expect(provider.create).to be end it 'should be able to delete the server profile' do resource['data'] = { 'name' => 'Edited SP' } expect(provider.destroy).to be end end end