file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
BaseController.ts
/** * BaseController * * Classe abstrata com as funções comuns a todos os controllers * * @author Henrique de Castro * @since 12/2016 */ import * as express from 'express'; export class Ba
/** * showSuccess * * Exibe um retorno de sucesso * * @author Henrique de Castro * @since 12/2016 * @param array * @param object * @return void */ public showSucess(data: Object, res: express.Response) { // Adiciona o sucesso nos dados let ret = {}; ret['status'] = true; ret['error'] = false; ret['data'] = data; // Exibe o retorno res.json(ret); } /** * showError * * Exibe um retorno de erro * * @author Henrique de Castro * @since 12/2016 * @param string * @param object * @return void */ public showError(error: String, res: express.Response) { // Adiciona erro nos dados let data = {}; data['status'] = false; data['error'] = error; // Exibe o retorno res.json(data); } /** * showAccessDenied * * Exibe um retorno de acesso negado * * @author Henrique de Castro * @since 12/2016 * @param object * @return void */ public showAccessDenied(req: express.Request, res: express.Response) { // Adiciona erro nos dados let data = {}; data['status'] = false; data['error'] = 'Acesso negado'; // Exibe o retorno res.statusCode = 401; res.json(data); } }
seController {
identifier_name
blueprint.ts
import { Dependency } from './dependency' import * as debug from 'loglevel-debug' const logger = debug("typescript-injector-light") /** * */ export abstract class Blueprint { private static container:Map<string,Blueprint> = new Map(); private static deferredBlueprints:Map<string,Array<Blueprint>> = new Map(); private _isReady; public dependencies: Array<Dependency>; constructor( public key:string, public provider:any, dependencies:Array<string> ){ this._isReady = false; this.dependencies = new Array<Dependency>(); for (let dependency of dependencies){ this.dependencies.push( new Dependency(dependency) ); } logger.debug("Blueprint: " + this.key) if(Blueprint.container.has(this.key)){ throw new Error("A provider for "+this.key+" already exists in the container"); } else { Blueprint.container.set(this.key, this); } } private tryResolveDependencies():Array<string>{ let unresolved:Array<string> = []; for (let dependency of this.dependencies){ let blueprint = Blueprint.container.get(dependency.required); if(blueprint !== undefined && blueprint._isReady){ dependency.resolved = blueprint.instantiate(); } else { unresolved.push(dependency.required); } } return unresolved; } private deferDependencyResolution(unresolvedDependencies:Array<string>):void { logger.debug('Defer: ' + this.key + '. waiting for ' + unresolvedDependencies); for (let dependency of unresolvedDependencies){ let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(dependency) ? Blueprint.deferredBlueprints.get(dependency) : Blueprint.deferredBlueprints.set(dependency, new Array<Blueprint>()).get(dependency); if (dependents.findIndex(b => b.key === this.key) === -1){ dependents.push(this); Blueprint.deferredBlueprints.set(dependency, dependents); } } } protected getResolvedDependencies():Array<any>{ return this.dependencies.map( v => v.resolved) } build(): void{ logger.debug("build: "+ this.key); let unresolvedDependencies = this.tryResolveDependencies(); if (unresolvedDependencies.length !== 0){ this.deferDependencyResolution(unresolvedDependencies); } else { this._isReady = true; } let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(this.key) ? Blueprint.deferredBlueprints.get(this.key) : []; logger.debug('dependents waiting for ['+ this.key+ '] = '+ dependents.length); for (let dependent of dependents){ logger.debug('Update: ' + dependent.key); dependent.build(); } Blueprint.deferredBlueprints.delete(this.key); } instantiate() {} static instantiate(key:string)
}
{ if (Blueprint.container.has(key)){ var blueprint = Blueprint.container.get(key) if (blueprint._isReady){ return blueprint.instantiate(); } else { throw new Error("The provider for "+key+" is deferred and waiting for: [" + blueprint.tryResolveDependencies().join(',') + "]"); } } else { throw new Error("A provider for "+key+" does not exists in the container"); } }
identifier_body
blueprint.ts
import { Dependency } from './dependency' import * as debug from 'loglevel-debug' const logger = debug("typescript-injector-light") /** * */ export abstract class Blueprint { private static container:Map<string,Blueprint> = new Map(); private static deferredBlueprints:Map<string,Array<Blueprint>> = new Map(); private _isReady; public dependencies: Array<Dependency>; constructor( public key:string, public provider:any, dependencies:Array<string> ){ this._isReady = false; this.dependencies = new Array<Dependency>(); for (let dependency of dependencies){ this.dependencies.push( new Dependency(dependency) ); } logger.debug("Blueprint: " + this.key) if(Blueprint.container.has(this.key)){ throw new Error("A provider for "+this.key+" already exists in the container"); } else { Blueprint.container.set(this.key, this); } } private tryResolveDependencies():Array<string>{ let unresolved:Array<string> = []; for (let dependency of this.dependencies){ let blueprint = Blueprint.container.get(dependency.required); if(blueprint !== undefined && blueprint._isReady){ dependency.resolved = blueprint.instantiate(); } else { unresolved.push(dependency.required); } } return unresolved; } private deferDependencyResolution(unresolvedDependencies:Array<string>):void { logger.debug('Defer: ' + this.key + '. waiting for ' + unresolvedDependencies); for (let dependency of unresolvedDependencies){ let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(dependency) ? Blueprint.deferredBlueprints.get(dependency) : Blueprint.deferredBlueprints.set(dependency, new Array<Blueprint>()).get(dependency); if (dependents.findIndex(b => b.key === this.key) === -1){ dependents.push(this); Blueprint.deferredBlueprints.set(dependency, dependents); } } } protected getResolvedDependencies():Array<any>{ return this.dependencies.map( v => v.resolved) } build(): void{ logger.debug("build: "+ this.key); let unresolvedDependencies = this.tryResolveDependencies(); if (unresolvedDependencies.length !== 0){ this.deferDependencyResolution(unresolvedDependencies); } else { this._isReady = true; } let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(this.key) ? Blueprint.deferredBlueprints.get(this.key) : []; logger.debug('dependents waiting for ['+ this.key+ '] = '+ dependents.length); for (let dependent of dependents){ logger.debug('Update: ' + dependent.key); dependent.build(); } Blueprint.deferredBlueprints.delete(this.key); } instantiate() {} static instantiate(key:string) { if (Blueprint.container.has(key)){ var blueprint = Blueprint.container.get(key) if (blueprint._isReady){ return blueprint.instantiate(); } else { throw new Error("The provider for "+key+" is deferred and waiting for: [" + blueprint.tryResolveDependencies().join(',') + "]"); } } else { throw new Error("A provider for "+key+" does not exists in the container");
}
} }
random_line_split
blueprint.ts
import { Dependency } from './dependency' import * as debug from 'loglevel-debug' const logger = debug("typescript-injector-light") /** * */ export abstract class Blueprint { private static container:Map<string,Blueprint> = new Map(); private static deferredBlueprints:Map<string,Array<Blueprint>> = new Map(); private _isReady; public dependencies: Array<Dependency>; constructor( public key:string, public provider:any, dependencies:Array<string> ){ this._isReady = false; this.dependencies = new Array<Dependency>(); for (let dependency of dependencies){ this.dependencies.push( new Dependency(dependency) ); } logger.debug("Blueprint: " + this.key) if(Blueprint.container.has(this.key)){ throw new Error("A provider for "+this.key+" already exists in the container"); } else { Blueprint.container.set(this.key, this); } } private tryResolveDependencies():Array<string>{ let unresolved:Array<string> = []; for (let dependency of this.dependencies){ let blueprint = Blueprint.container.get(dependency.required); if(blueprint !== undefined && blueprint._isReady){ dependency.resolved = blueprint.instantiate(); } else { unresolved.push(dependency.required); } } return unresolved; } private deferDependencyResolution(unresolvedDependencies:Array<string>):void { logger.debug('Defer: ' + this.key + '. waiting for ' + unresolvedDependencies); for (let dependency of unresolvedDependencies){ let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(dependency) ? Blueprint.deferredBlueprints.get(dependency) : Blueprint.deferredBlueprints.set(dependency, new Array<Blueprint>()).get(dependency); if (dependents.findIndex(b => b.key === this.key) === -1){ dependents.push(this); Blueprint.deferredBlueprints.set(dependency, dependents); } } } protected getResolvedDependencies():Array<any>{ return this.dependencies.map( v => v.resolved) } build(): void{ logger.debug("build: "+ this.key); let unresolvedDependencies = this.tryResolveDependencies(); if (unresolvedDependencies.length !== 0){ this.deferDependencyResolution(unresolvedDependencies); } else { this._isReady = true; } let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(this.key) ? Blueprint.deferredBlueprints.get(this.key) : []; logger.debug('dependents waiting for ['+ this.key+ '] = '+ dependents.length); for (let dependent of dependents){ logger.debug('Update: ' + dependent.key); dependent.build(); } Blueprint.deferredBlueprints.delete(this.key); } instantiate() {} static instantiate(key:string) { if (Blueprint.container.has(key)){ var blueprint = Blueprint.container.get(key) if (blueprint._isReady){ return blueprint.instantiate(); } else { throw new Error("The provider for "+key+" is deferred and waiting for: [" + blueprint.tryResolveDependencies().join(',') + "]"); } } else
} }
{ throw new Error("A provider for "+key+" does not exists in the container"); }
conditional_block
blueprint.ts
import { Dependency } from './dependency' import * as debug from 'loglevel-debug' const logger = debug("typescript-injector-light") /** * */ export abstract class Blueprint { private static container:Map<string,Blueprint> = new Map(); private static deferredBlueprints:Map<string,Array<Blueprint>> = new Map(); private _isReady; public dependencies: Array<Dependency>; constructor( public key:string, public provider:any, dependencies:Array<string> ){ this._isReady = false; this.dependencies = new Array<Dependency>(); for (let dependency of dependencies){ this.dependencies.push( new Dependency(dependency) ); } logger.debug("Blueprint: " + this.key) if(Blueprint.container.has(this.key)){ throw new Error("A provider for "+this.key+" already exists in the container"); } else { Blueprint.container.set(this.key, this); } } private tryResolveDependencies():Array<string>{ let unresolved:Array<string> = []; for (let dependency of this.dependencies){ let blueprint = Blueprint.container.get(dependency.required); if(blueprint !== undefined && blueprint._isReady){ dependency.resolved = blueprint.instantiate(); } else { unresolved.push(dependency.required); } } return unresolved; } private deferDependencyResolution(unresolvedDependencies:Array<string>):void { logger.debug('Defer: ' + this.key + '. waiting for ' + unresolvedDependencies); for (let dependency of unresolvedDependencies){ let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(dependency) ? Blueprint.deferredBlueprints.get(dependency) : Blueprint.deferredBlueprints.set(dependency, new Array<Blueprint>()).get(dependency); if (dependents.findIndex(b => b.key === this.key) === -1){ dependents.push(this); Blueprint.deferredBlueprints.set(dependency, dependents); } } } protected getResolvedDependencies():Array<any>{ return this.dependencies.map( v => v.resolved) }
(): void{ logger.debug("build: "+ this.key); let unresolvedDependencies = this.tryResolveDependencies(); if (unresolvedDependencies.length !== 0){ this.deferDependencyResolution(unresolvedDependencies); } else { this._isReady = true; } let dependents:Array<Blueprint> = Blueprint.deferredBlueprints.has(this.key) ? Blueprint.deferredBlueprints.get(this.key) : []; logger.debug('dependents waiting for ['+ this.key+ '] = '+ dependents.length); for (let dependent of dependents){ logger.debug('Update: ' + dependent.key); dependent.build(); } Blueprint.deferredBlueprints.delete(this.key); } instantiate() {} static instantiate(key:string) { if (Blueprint.container.has(key)){ var blueprint = Blueprint.container.get(key) if (blueprint._isReady){ return blueprint.instantiate(); } else { throw new Error("The provider for "+key+" is deferred and waiting for: [" + blueprint.tryResolveDependencies().join(',') + "]"); } } else { throw new Error("A provider for "+key+" does not exists in the container"); } } }
build
identifier_name
scroll-to.ts
import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import { ScrollTo, ScrollToDuration } from '../../utils/scroll-to/scroll-to'; import { ModulVue } from '../../utils/vue/vue'; import { SCROLL_TO_NAME } from '../directive-names'; class ScrollToCallback {
(private speed: ScrollToDuration, private offset: number, private target: HTMLElement) { } callBack: (event: MouseEvent) => void = (event: MouseEvent) => { let scrollTo: ScrollTo = (Vue.prototype as ModulVue).$scrollTo; scrollTo.goTo(this.target, this.offset, this.speed); } } const MScrollTo: DirectiveOptions = { inserted(element: HTMLElement, binding: VNodeDirective, node: VNode): void { let speed: ScrollToDuration = binding.value.speed || ScrollToDuration.Regular; let offset: number = binding.value.offset || 0; if (!node.context) { throw new Error('Error node context is null'); } let target: HTMLElement = node.context.$refs[binding.arg!] as HTMLElement; const _scrollToCallback: ScrollToCallback = new ScrollToCallback(speed, offset, target); Object.defineProperty(element, '_scrollToCallback', { value: _scrollToCallback }); element.addEventListener('touchstart', _scrollToCallback.callBack); element.addEventListener('click', _scrollToCallback.callBack); }, update(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback) { (element as any)._scrollToCallback.speed = binding.value.speed || ScrollToDuration.Regular; (element as any)._scrollToCallback.offset = binding.value.offset || 0; } }, unbind(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback) { element.removeEventListener('touchstart', (element as any)._scrollToCallback.callBack); element.removeEventListener('click', (element as any)._scrollToCallback.callBack); } } }; const ScrollToPlugin: PluginObject<any> = { install(v, options): void { v.prototype.$log.error('ScrollToDirective will be deprecated in modul v.1.0'); v.use(ScrollToPlugin); v.directive(SCROLL_TO_NAME, MScrollTo); } }; export default ScrollToPlugin;
constructor
identifier_name
scroll-to.ts
import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import { ScrollTo, ScrollToDuration } from '../../utils/scroll-to/scroll-to'; import { ModulVue } from '../../utils/vue/vue'; import { SCROLL_TO_NAME } from '../directive-names'; class ScrollToCallback { constructor(private speed: ScrollToDuration, private offset: number, private target: HTMLElement) { } callBack: (event: MouseEvent) => void = (event: MouseEvent) => { let scrollTo: ScrollTo = (Vue.prototype as ModulVue).$scrollTo; scrollTo.goTo(this.target, this.offset, this.speed); } } const MScrollTo: DirectiveOptions = { inserted(element: HTMLElement, binding: VNodeDirective, node: VNode): void
, update(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback) { (element as any)._scrollToCallback.speed = binding.value.speed || ScrollToDuration.Regular; (element as any)._scrollToCallback.offset = binding.value.offset || 0; } }, unbind(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback) { element.removeEventListener('touchstart', (element as any)._scrollToCallback.callBack); element.removeEventListener('click', (element as any)._scrollToCallback.callBack); } } }; const ScrollToPlugin: PluginObject<any> = { install(v, options): void { v.prototype.$log.error('ScrollToDirective will be deprecated in modul v.1.0'); v.use(ScrollToPlugin); v.directive(SCROLL_TO_NAME, MScrollTo); } }; export default ScrollToPlugin;
{ let speed: ScrollToDuration = binding.value.speed || ScrollToDuration.Regular; let offset: number = binding.value.offset || 0; if (!node.context) { throw new Error('Error node context is null'); } let target: HTMLElement = node.context.$refs[binding.arg!] as HTMLElement; const _scrollToCallback: ScrollToCallback = new ScrollToCallback(speed, offset, target); Object.defineProperty(element, '_scrollToCallback', { value: _scrollToCallback }); element.addEventListener('touchstart', _scrollToCallback.callBack); element.addEventListener('click', _scrollToCallback.callBack); }
identifier_body
scroll-to.ts
import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import { ScrollTo, ScrollToDuration } from '../../utils/scroll-to/scroll-to'; import { ModulVue } from '../../utils/vue/vue'; import { SCROLL_TO_NAME } from '../directive-names'; class ScrollToCallback { constructor(private speed: ScrollToDuration, private offset: number, private target: HTMLElement) { } callBack: (event: MouseEvent) => void = (event: MouseEvent) => { let scrollTo: ScrollTo = (Vue.prototype as ModulVue).$scrollTo; scrollTo.goTo(this.target, this.offset, this.speed); } } const MScrollTo: DirectiveOptions = { inserted(element: HTMLElement, binding: VNodeDirective, node: VNode): void { let speed: ScrollToDuration = binding.value.speed || ScrollToDuration.Regular; let offset: number = binding.value.offset || 0; if (!node.context) { throw new Error('Error node context is null'); } let target: HTMLElement = node.context.$refs[binding.arg!] as HTMLElement; const _scrollToCallback: ScrollToCallback = new ScrollToCallback(speed, offset, target); Object.defineProperty(element, '_scrollToCallback', { value: _scrollToCallback }); element.addEventListener('touchstart', _scrollToCallback.callBack); element.addEventListener('click', _scrollToCallback.callBack); }, update(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback)
}, unbind(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback) { element.removeEventListener('touchstart', (element as any)._scrollToCallback.callBack); element.removeEventListener('click', (element as any)._scrollToCallback.callBack); } } }; const ScrollToPlugin: PluginObject<any> = { install(v, options): void { v.prototype.$log.error('ScrollToDirective will be deprecated in modul v.1.0'); v.use(ScrollToPlugin); v.directive(SCROLL_TO_NAME, MScrollTo); } }; export default ScrollToPlugin;
{ (element as any)._scrollToCallback.speed = binding.value.speed || ScrollToDuration.Regular; (element as any)._scrollToCallback.offset = binding.value.offset || 0; }
conditional_block
scroll-to.ts
import Vue, { DirectiveOptions, PluginObject, VNode, VNodeDirective } from 'vue'; import { ScrollTo, ScrollToDuration } from '../../utils/scroll-to/scroll-to'; import { ModulVue } from '../../utils/vue/vue'; import { SCROLL_TO_NAME } from '../directive-names'; class ScrollToCallback { constructor(private speed: ScrollToDuration, private offset: number, private target: HTMLElement) { } callBack: (event: MouseEvent) => void = (event: MouseEvent) => { let scrollTo: ScrollTo = (Vue.prototype as ModulVue).$scrollTo; scrollTo.goTo(this.target, this.offset, this.speed); } } const MScrollTo: DirectiveOptions = { inserted(element: HTMLElement, binding: VNodeDirective, node: VNode): void { let speed: ScrollToDuration = binding.value.speed || ScrollToDuration.Regular; let offset: number = binding.value.offset || 0; if (!node.context) { throw new Error('Error node context is null'); } let target: HTMLElement = node.context.$refs[binding.arg!] as HTMLElement; const _scrollToCallback: ScrollToCallback = new ScrollToCallback(speed, offset, target);
Object.defineProperty(element, '_scrollToCallback', { value: _scrollToCallback }); element.addEventListener('touchstart', _scrollToCallback.callBack); element.addEventListener('click', _scrollToCallback.callBack); }, update(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback) { (element as any)._scrollToCallback.speed = binding.value.speed || ScrollToDuration.Regular; (element as any)._scrollToCallback.offset = binding.value.offset || 0; } }, unbind(element: HTMLElement, binding: VNodeDirective): void { if (element && (element as any)._scrollToCallback) { element.removeEventListener('touchstart', (element as any)._scrollToCallback.callBack); element.removeEventListener('click', (element as any)._scrollToCallback.callBack); } } }; const ScrollToPlugin: PluginObject<any> = { install(v, options): void { v.prototype.$log.error('ScrollToDirective will be deprecated in modul v.1.0'); v.use(ScrollToPlugin); v.directive(SCROLL_TO_NAME, MScrollTo); } }; export default ScrollToPlugin;
random_line_split
animation_group_player.ts
import {AnimationPlayer} from './animation_player'; import {isPresent, scheduleMicroTask} from '../facade/lang'; import {Math} from '../facade/math'; export class AnimationGroupPlayer implements AnimationPlayer { private _subscriptions: Function[] = []; private _finished = false; public parentPlayer: AnimationPlayer = null; constructor(private _players: AnimationPlayer[]) { var count = 0; var total = this._players.length; if (total == 0) { scheduleMicroTask(() => this._onFinish()); } else { this._players.forEach(player => { player.parentPlayer = this; player.onDone(() => { if (++count >= total) { this._onFinish(); } }); }); } } private _onFinish() { if (!this._finished) { this._finished = true; if (!isPresent(this.parentPlayer)) { this.destroy(); } this._subscriptions.forEach(subscription => subscription()); this._subscriptions = []; } } onDone(fn: Function): void { this._subscriptions.push(fn); } play() { this._players.forEach(player => player.play()); } pause(): void { this._players.forEach(player => player.pause()); } restart(): void { this._players.forEach(player => player.restart()); } finish(): void { this._onFinish(); this._players.forEach(player => player.finish()); } destroy(): void { this._onFinish(); this._players.forEach(player => player.destroy()); } reset(): void { this._players.forEach(player => player.reset()); } setPosition(p): void {
getPosition(): number { var min = 0; this._players.forEach(player => { var p = player.getPosition(); min = Math.min(p, min); }); return min; } }
this._players.forEach(player => { player.setPosition(p); }); }
random_line_split
animation_group_player.ts
import {AnimationPlayer} from './animation_player'; import {isPresent, scheduleMicroTask} from '../facade/lang'; import {Math} from '../facade/math'; export class AnimationGroupPlayer implements AnimationPlayer { private _subscriptions: Function[] = []; private _finished = false; public parentPlayer: AnimationPlayer = null; constructor(private _players: AnimationPlayer[]) { var count = 0; var total = this._players.length; if (total == 0) { scheduleMicroTask(() => this._onFinish()); } else { this._players.forEach(player => { player.parentPlayer = this; player.onDone(() => { if (++count >= total) { this._onFinish(); } }); }); } } private _onFinish() { if (!this._finished) { this._finished = true; if (!isPresent(this.parentPlayer)) { this.destroy(); } this._subscriptions.forEach(subscription => subscription()); this._subscriptions = []; } } onDone(fn: Function): void { this._subscriptions.push(fn); } play() { this._players.forEach(player => player.play()); } pause(): void { this._players.forEach(player => player.pause()); } restart(): void { this._players.forEach(player => player.restart()); } finish(): void { this._onFinish(); this._players.forEach(player => player.finish()); }
(): void { this._onFinish(); this._players.forEach(player => player.destroy()); } reset(): void { this._players.forEach(player => player.reset()); } setPosition(p): void { this._players.forEach(player => { player.setPosition(p); }); } getPosition(): number { var min = 0; this._players.forEach(player => { var p = player.getPosition(); min = Math.min(p, min); }); return min; } }
destroy
identifier_name
animation_group_player.ts
import {AnimationPlayer} from './animation_player'; import {isPresent, scheduleMicroTask} from '../facade/lang'; import {Math} from '../facade/math'; export class AnimationGroupPlayer implements AnimationPlayer { private _subscriptions: Function[] = []; private _finished = false; public parentPlayer: AnimationPlayer = null; constructor(private _players: AnimationPlayer[]) { var count = 0; var total = this._players.length; if (total == 0)
else { this._players.forEach(player => { player.parentPlayer = this; player.onDone(() => { if (++count >= total) { this._onFinish(); } }); }); } } private _onFinish() { if (!this._finished) { this._finished = true; if (!isPresent(this.parentPlayer)) { this.destroy(); } this._subscriptions.forEach(subscription => subscription()); this._subscriptions = []; } } onDone(fn: Function): void { this._subscriptions.push(fn); } play() { this._players.forEach(player => player.play()); } pause(): void { this._players.forEach(player => player.pause()); } restart(): void { this._players.forEach(player => player.restart()); } finish(): void { this._onFinish(); this._players.forEach(player => player.finish()); } destroy(): void { this._onFinish(); this._players.forEach(player => player.destroy()); } reset(): void { this._players.forEach(player => player.reset()); } setPosition(p): void { this._players.forEach(player => { player.setPosition(p); }); } getPosition(): number { var min = 0; this._players.forEach(player => { var p = player.getPosition(); min = Math.min(p, min); }); return min; } }
{ scheduleMicroTask(() => this._onFinish()); }
conditional_block
animation_group_player.ts
import {AnimationPlayer} from './animation_player'; import {isPresent, scheduleMicroTask} from '../facade/lang'; import {Math} from '../facade/math'; export class AnimationGroupPlayer implements AnimationPlayer { private _subscriptions: Function[] = []; private _finished = false; public parentPlayer: AnimationPlayer = null; constructor(private _players: AnimationPlayer[]) { var count = 0; var total = this._players.length; if (total == 0) { scheduleMicroTask(() => this._onFinish()); } else { this._players.forEach(player => { player.parentPlayer = this; player.onDone(() => { if (++count >= total) { this._onFinish(); } }); }); } } private _onFinish() { if (!this._finished) { this._finished = true; if (!isPresent(this.parentPlayer)) { this.destroy(); } this._subscriptions.forEach(subscription => subscription()); this._subscriptions = []; } } onDone(fn: Function): void { this._subscriptions.push(fn); } play()
pause(): void { this._players.forEach(player => player.pause()); } restart(): void { this._players.forEach(player => player.restart()); } finish(): void { this._onFinish(); this._players.forEach(player => player.finish()); } destroy(): void { this._onFinish(); this._players.forEach(player => player.destroy()); } reset(): void { this._players.forEach(player => player.reset()); } setPosition(p): void { this._players.forEach(player => { player.setPosition(p); }); } getPosition(): number { var min = 0; this._players.forEach(player => { var p = player.getPosition(); min = Math.min(p, min); }); return min; } }
{ this._players.forEach(player => player.play()); }
identifier_body
res_partner.py
# -*- coding: utf-8 -*- # Copyright 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api from openerp.tools.translate import _ from openerp.exceptions import Warning as UserError class ResPartner(models.Model): _inherit = "res.partner" @api.multi def _compute_single_sale_policy(self): single_sale_order = 0.0 unset_single_sale_order = False criteria = [
policy = self.env["partner.risk_limit_policy"].search( criteria, limit=1) if len(policy) == 1: single_sale_order = policy.single_sale_order_limit unset_single_sale_order = policy.unset_single_sale_order_limit for partner in self: partner.single_sale_order_limit_policy = single_sale_order partner.unset_single_sale_order_limit_policy = \ unset_single_sale_order single_sale_order_limit_policy = fields.Float( string="Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) unset_single_sale_order_limit_policy = fields.Boolean( string="Unset Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) @api.model def _update_limit_check_context(self, values): _super = super(ResPartner, self) ctx = _super._update_limit_check_context(values) for field in iter(values): if field == "risk_single_sale_order_limit": ctx.update({"check_single_sale_order_limit": True}) return ctx @api.constrains( "risk_single_sale_order_limit", ) def _check_single_sale_limit_policy(self): for partner in self: if partner.single_sale_order_limit_policy and \ partner.single_sale_order_limit_policy < \ partner.risk_single_sale_order_limit and \ partner.risk_single_sale_order_limit > 0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError(_("Unauthorized single sale order amount")) if not partner.unset_single_sale_order_limit_policy and \ partner.risk_single_sale_order_limit <= 0.0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError( _("Unauthorized to unset single sale order limit amount"))
("user_ids.id", "in", [self.env.user.id]), ]
random_line_split
res_partner.py
# -*- coding: utf-8 -*- # Copyright 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api from openerp.tools.translate import _ from openerp.exceptions import Warning as UserError class ResPartner(models.Model): _inherit = "res.partner" @api.multi def _compute_single_sale_policy(self): single_sale_order = 0.0 unset_single_sale_order = False criteria = [ ("user_ids.id", "in", [self.env.user.id]), ] policy = self.env["partner.risk_limit_policy"].search( criteria, limit=1) if len(policy) == 1: single_sale_order = policy.single_sale_order_limit unset_single_sale_order = policy.unset_single_sale_order_limit for partner in self: partner.single_sale_order_limit_policy = single_sale_order partner.unset_single_sale_order_limit_policy = \ unset_single_sale_order single_sale_order_limit_policy = fields.Float( string="Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) unset_single_sale_order_limit_policy = fields.Boolean( string="Unset Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) @api.model def _update_limit_check_context(self, values): _super = super(ResPartner, self) ctx = _super._update_limit_check_context(values) for field in iter(values):
return ctx @api.constrains( "risk_single_sale_order_limit", ) def _check_single_sale_limit_policy(self): for partner in self: if partner.single_sale_order_limit_policy and \ partner.single_sale_order_limit_policy < \ partner.risk_single_sale_order_limit and \ partner.risk_single_sale_order_limit > 0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError(_("Unauthorized single sale order amount")) if not partner.unset_single_sale_order_limit_policy and \ partner.risk_single_sale_order_limit <= 0.0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError( _("Unauthorized to unset single sale order limit amount"))
if field == "risk_single_sale_order_limit": ctx.update({"check_single_sale_order_limit": True})
conditional_block
res_partner.py
# -*- coding: utf-8 -*- # Copyright 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api from openerp.tools.translate import _ from openerp.exceptions import Warning as UserError class ResPartner(models.Model): _inherit = "res.partner" @api.multi def _compute_single_sale_policy(self): single_sale_order = 0.0 unset_single_sale_order = False criteria = [ ("user_ids.id", "in", [self.env.user.id]), ] policy = self.env["partner.risk_limit_policy"].search( criteria, limit=1) if len(policy) == 1: single_sale_order = policy.single_sale_order_limit unset_single_sale_order = policy.unset_single_sale_order_limit for partner in self: partner.single_sale_order_limit_policy = single_sale_order partner.unset_single_sale_order_limit_policy = \ unset_single_sale_order single_sale_order_limit_policy = fields.Float( string="Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) unset_single_sale_order_limit_policy = fields.Boolean( string="Unset Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) @api.model def
(self, values): _super = super(ResPartner, self) ctx = _super._update_limit_check_context(values) for field in iter(values): if field == "risk_single_sale_order_limit": ctx.update({"check_single_sale_order_limit": True}) return ctx @api.constrains( "risk_single_sale_order_limit", ) def _check_single_sale_limit_policy(self): for partner in self: if partner.single_sale_order_limit_policy and \ partner.single_sale_order_limit_policy < \ partner.risk_single_sale_order_limit and \ partner.risk_single_sale_order_limit > 0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError(_("Unauthorized single sale order amount")) if not partner.unset_single_sale_order_limit_policy and \ partner.risk_single_sale_order_limit <= 0.0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError( _("Unauthorized to unset single sale order limit amount"))
_update_limit_check_context
identifier_name
res_partner.py
# -*- coding: utf-8 -*- # Copyright 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api from openerp.tools.translate import _ from openerp.exceptions import Warning as UserError class ResPartner(models.Model): _inherit = "res.partner" @api.multi def _compute_single_sale_policy(self): single_sale_order = 0.0 unset_single_sale_order = False criteria = [ ("user_ids.id", "in", [self.env.user.id]), ] policy = self.env["partner.risk_limit_policy"].search( criteria, limit=1) if len(policy) == 1: single_sale_order = policy.single_sale_order_limit unset_single_sale_order = policy.unset_single_sale_order_limit for partner in self: partner.single_sale_order_limit_policy = single_sale_order partner.unset_single_sale_order_limit_policy = \ unset_single_sale_order single_sale_order_limit_policy = fields.Float( string="Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) unset_single_sale_order_limit_policy = fields.Boolean( string="Unset Single Sale Order Limit Policy", compute="_compute_single_sale_policy", store=False, ) @api.model def _update_limit_check_context(self, values):
@api.constrains( "risk_single_sale_order_limit", ) def _check_single_sale_limit_policy(self): for partner in self: if partner.single_sale_order_limit_policy and \ partner.single_sale_order_limit_policy < \ partner.risk_single_sale_order_limit and \ partner.risk_single_sale_order_limit > 0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError(_("Unauthorized single sale order amount")) if not partner.unset_single_sale_order_limit_policy and \ partner.risk_single_sale_order_limit <= 0.0 and \ self._context.get("check_single_sale_order_limit", False): raise UserError( _("Unauthorized to unset single sale order limit amount"))
_super = super(ResPartner, self) ctx = _super._update_limit_check_context(values) for field in iter(values): if field == "risk_single_sale_order_limit": ctx.update({"check_single_sale_order_limit": True}) return ctx
identifier_body
error-handler.ts
import { init, captureException, withScope } from '@sentry/node'; import { assertEnv } from './assert-env'; const serviceName = 'api-frameworks'; let sentryInitDone = false; function initSentry() { if (sentryInitDone) { return; } sentryInitDone = true; init({ dsn: assertEnv('SENTRY_DSN'), environment: process.env.NODE_ENV || 'production', release: `${serviceName}`, }); } export function errorHandler(error: Error, extras?: { [key: string]: any }) { if (!process.env.SENTRY_DSN) {
initSentry(); try { withScope(scope => { scope.setTag('service', serviceName); scope.setTag('function_name', assertEnv('AWS_LAMBDA_FUNCTION_NAME')); for (const [k, v] of Object.entries(extras)) { scope.setExtra(k, v); } captureException(error); }); } catch (e) { console.error(`Failed to report error to Sentry: ${e}`); } }
return; }
random_line_split
error-handler.ts
import { init, captureException, withScope } from '@sentry/node'; import { assertEnv } from './assert-env'; const serviceName = 'api-frameworks'; let sentryInitDone = false; function initSentry() { if (sentryInitDone) { return; } sentryInitDone = true; init({ dsn: assertEnv('SENTRY_DSN'), environment: process.env.NODE_ENV || 'production', release: `${serviceName}`, }); } export function errorHandler(error: Error, extras?: { [key: string]: any }) { if (!process.env.SENTRY_DSN)
initSentry(); try { withScope(scope => { scope.setTag('service', serviceName); scope.setTag('function_name', assertEnv('AWS_LAMBDA_FUNCTION_NAME')); for (const [k, v] of Object.entries(extras)) { scope.setExtra(k, v); } captureException(error); }); } catch (e) { console.error(`Failed to report error to Sentry: ${e}`); } }
{ return; }
conditional_block
error-handler.ts
import { init, captureException, withScope } from '@sentry/node'; import { assertEnv } from './assert-env'; const serviceName = 'api-frameworks'; let sentryInitDone = false; function initSentry() { if (sentryInitDone) { return; } sentryInitDone = true; init({ dsn: assertEnv('SENTRY_DSN'), environment: process.env.NODE_ENV || 'production', release: `${serviceName}`, }); } export function errorHandler(error: Error, extras?: { [key: string]: any })
{ if (!process.env.SENTRY_DSN) { return; } initSentry(); try { withScope(scope => { scope.setTag('service', serviceName); scope.setTag('function_name', assertEnv('AWS_LAMBDA_FUNCTION_NAME')); for (const [k, v] of Object.entries(extras)) { scope.setExtra(k, v); } captureException(error); }); } catch (e) { console.error(`Failed to report error to Sentry: ${e}`); } }
identifier_body
error-handler.ts
import { init, captureException, withScope } from '@sentry/node'; import { assertEnv } from './assert-env'; const serviceName = 'api-frameworks'; let sentryInitDone = false; function initSentry() { if (sentryInitDone) { return; } sentryInitDone = true; init({ dsn: assertEnv('SENTRY_DSN'), environment: process.env.NODE_ENV || 'production', release: `${serviceName}`, }); } export function
(error: Error, extras?: { [key: string]: any }) { if (!process.env.SENTRY_DSN) { return; } initSentry(); try { withScope(scope => { scope.setTag('service', serviceName); scope.setTag('function_name', assertEnv('AWS_LAMBDA_FUNCTION_NAME')); for (const [k, v] of Object.entries(extras)) { scope.setExtra(k, v); } captureException(error); }); } catch (e) { console.error(`Failed to report error to Sentry: ${e}`); } }
errorHandler
identifier_name
integration_tests.py
#!/usr/bin/env python import fnmatch import os from pathlib import Path import re import shlex import shutil import subprocess import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from typing import Optional import click import git import typer import yaml from packaging.version import Version from typer import colors as c # Editable configuration DEFAULT_HOST_OS = "cc7" DEFAULT_MYSQL_VER = "mysql:8.0" DEFAULT_ES_VER = "elasticsearch:7.9.1" FEATURE_VARIABLES = { "DIRACOSVER": "master", "DIRACOS_TARBALL_PATH": None, "TEST_HTTPS": "No", "DIRAC_FEWER_CFG_LOCKS": None, "DIRAC_USE_JSON_ENCODE": None, "DIRAC_USE_JSON_DECODE": None, } DEFAULT_MODULES = { "DIRAC": Path(__file__).parent.absolute(), } # Static configuration DB_USER = "Dirac" DB_PASSWORD = "Dirac" DB_ROOTUSER = "root" DB_ROOTPWD = "password" DB_HOST = "mysql" DB_PORT = "3306" # Implementation details LOG_LEVEL_MAP = { "ALWAYS": (c.BLACK, c.WHITE), "NOTICE": (None, c.MAGENTA), "INFO": (None, c.GREEN), "VERBOSE": (None, c.CYAN), "DEBUG": (None, c.BLUE), "WARN": (None, c.YELLOW), "ERROR": (None, c.RED), "FATAL": (c.RED, c.BLACK), } LOG_PATTERN = re.compile(r"^[\d\-]{10} [\d:]{8} UTC [^\s]+ ([A-Z]+):") class NaturalOrderGroup(click.Group): """Group for showing subcommands in the correct order""" def list_commands(self, ctx): return self.commands.keys() app = typer.Typer( cls=NaturalOrderGroup, help=f"""Run the DIRAC integration tests. A local DIRAC setup can be created and tested by running: \b ./integration_tests.py create This is equivalent to running: \b ./integration_tests.py prepare-environment ./integration_tests.py install-server ./integration_tests.py install-client ./integration_tests.py test-server ./integration_tests.py test-client The test setup can be shutdown using: \b ./integration_tests.py destroy See below for additional subcommands which are useful during local development. ## Features The currently known features and their default values are: \b HOST_OS: {DEFAULT_HOST_OS!r} MYSQL_VER: {DEFAULT_MYSQL_VER!r} ES_VER: {DEFAULT_ES_VER!r} {(os.linesep + ' ').join(['%s: %r' % x for x in FEATURE_VARIABLES.items()])} All features can be prefixed with "SERVER_" or "CLIENT_" to limit their scope. ## Extensions Integration tests can be ran for extensions to DIRAC by specifying the module name and path such as: \b ./integration_tests.py create --extra-module MyDIRAC=/path/to/MyDIRAC This will modify the setup process based on the contents of `MyDIRAC/tests/.dirac-ci-config.yaml`. See the Vanilla DIRAC file for the available options. ## Command completion Command completion of typer based scripts can be enabled by running: typer --install-completion After restarting your terminal you command completion is available using: typer ./integration_tests.py run ... """, ) @app.command() def create( flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None, release_var: Optional[str] = None, run_server_tests: bool = True, run_client_tests: bool = True, ): """Start a local instance of the integration tests""" prepare_environment(flags, editable, extra_module, release_var) install_server() install_client() exit_code = 0 if run_server_tests: try: test_server() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if run_client_tests: try: test_client() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if exit_code != 0: typer.secho("One or more tests failed", err=True, fg=c.RED) raise typer.Exit(exit_code) @app.command() def destroy(): """Destroy a local instance of the integration tests""" typer.secho("Shutting down and removing containers", err=True, fg=c.GREEN) with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: os.execvpe( "docker-compose", ["docker-compose", "-f", docker_compose_fn, "down", "--remove-orphans", "-t", "0"], _make_env({}), ) @app.command() def prepare_environment( flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None, release_var: Optional[str] = None, ): """Prepare the local environment for installing DIRAC.""" _check_containers_running(is_up=False) if editable is None: editable = sys.stdout.isatty() typer.secho( f"No value passed for --[no-]editable, automatically detected: {editable}", fg=c.YELLOW, ) typer.echo(f"Preparing environment") modules = DEFAULT_MODULES | dict(f.split("=", 1) for f in extra_module) modules = {k: Path(v).absolute() for k, v in modules.items()} flags = dict(f.split("=", 1) for f in flags) docker_compose_env = _make_env(flags) server_flags = {} client_flags = {} for key, value in flags.items(): if key.startswith("SERVER_"): server_flags[key[len("SERVER_") :]] = value elif key.startswith("CLIENT_"): client_flags[key[len("CLIENT_") :]] = value else: server_flags[key] = value client_flags[key] = value server_config = _make_config(modules, server_flags, release_var, editable) client_config = _make_config(modules, client_flags, release_var, editable) typer.secho("Running docker-compose to create containers", fg=c.GREEN) with _gen_docker_compose(modules) as docker_compose_fn: subprocess.run( ["docker-compose", "-f", docker_compose_fn, "up", "-d"], check=True, env=docker_compose_env, ) typer.secho("Creating users in server and client containers", fg=c.GREEN) for container_name in ["server", "client"]: if os.getuid() == 0: continue cmd = _build_docker_cmd(container_name, use_root=True, cwd="/") gid = str(os.getgid()) uid = str(os.getuid()) ret = subprocess.run(cmd + ["groupadd", "--gid", gid, "dirac"], check=False) if ret.returncode != 0: typer.secho(f"Failed to add add group dirac with id={gid}", fg=c.YELLOW) subprocess.run( cmd + [ "useradd", "--uid", uid, "--gid", gid, "-s", "/bin/bash", "-d", "/home/dirac", "dirac", ], check=True, ) subprocess.run(cmd + ["chown", "dirac", "/home/dirac"], check=True) typer.secho("Creating MySQL user", fg=c.GREEN) cmd = ["docker", "exec", "mysql", "mysql", f"--password={DB_ROOTPWD}", "-e"] # It sometimes takes a while for MySQL to be ready so wait for a while if needed for _ in range(10): ret = subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'%' IDENTIFIED BY '{DB_PASSWORD}';"], check=False, ) if ret.returncode == 0: break typer.secho("Failed to connect to MySQL, will retry in 10 seconds", fg=c.YELLOW) time.sleep(10) else: raise Exception(ret) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'localhost' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'mysql' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) typer.secho("Copying files to containers", fg=c.GREEN) for name, config in [("server", server_config), ("client", client_config)]: if path := config.get("DIRACOS_TARBALL_PATH"): path = Path(path) config["DIRACOS_TARBALL_PATH"] = f"/{path.name}" subprocess.run( ["docker", "cp", str(path), f"{name}:/{config['DIRACOS_TARBALL_PATH']}"], check=True, ) config_as_shell = _dict_to_shell(config) typer.secho(f"## {name.title()} config is:", fg=c.BRIGHT_WHITE, bg=c.BLACK) typer.secho(config_as_shell) with tempfile.TemporaryDirectory() as tmpdir: path = Path(tmpdir) / "CONFIG" path.write_text(config_as_shell) subprocess.run( ["docker", "cp", str(path), f"{name}:/home/dirac"], check=True, ) for module_name, module_configs in _load_module_configs(modules).items(): for command in module_configs.get("commands", {}).get("post-prepare", []): typer.secho( f"Running post-prepare command for {module_name}: {command}", err=True, fg=c.GREEN, ) subprocess.run(command, check=True, shell=True) @app.command() def install_server(): """Install DIRAC in the server container.""" _check_containers_running() typer.secho("Running server installation", fg=c.GREEN) base_cmd = _build_docker_cmd("server", tty=False) subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_server.sh"], check=True, ) typer.secho("Copying credentials and certificates", fg=c.GREEN) base_cmd = _build_docker_cmd("client", tty=False) subprocess.run( base_cmd + [ "mkdir", "-p", "/home/dirac/ServerInstallDIR/user", "/home/dirac/ClientInstallDIR/etc", "/home/dirac/.globus", ], check=True, ) for path in [ "etc/grid-security", "user/client.pem", "user/client.key", f"/tmp/x509up_u{os.getuid()}", ]: source = os.path.join("/home/dirac/ServerInstallDIR", path) ret = subprocess.run( ["docker", "cp", f"server:{source}", "-"], check=True, text=False, stdout=subprocess.PIPE, ) if path.startswith("user/"): dest = f"client:/home/dirac/ServerInstallDIR/{os.path.dirname(path)}" elif path.startswith("/"): dest = f"client:{os.path.dirname(path)}" else: dest = f"client:/home/dirac/ClientInstallDIR/{os.path.dirname(path)}" subprocess.run(["docker", "cp", "-", dest], check=True, text=False, input=ret.stdout) subprocess.run( base_cmd + [ "bash", "-c", "cp /home/dirac/ServerInstallDIR/user/client.* /home/dirac/.globus/", ], check=True, ) @app.command() def install_client(): """Install DIRAC in the client container.""" _check_containers_running() typer.secho("Running client installation", fg=c.GREEN) base_cmd = _build_docker_cmd("client") subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_client.sh"], check=True, ) @app.command() def test_server(): """Run the server integration tests.""" _check_containers_running() typer.secho("Running server tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("server") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Server tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def test_client(): """Run the client integration tests.""" _check_containers_running() typer.secho("Running client tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("client") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Client tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def exec_server(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ServerInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_client(): """Start an interactive session in the client container.""" _check_containers_running() cmd = _build_docker_cmd("client") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ClientInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside client container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_mysql(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("mysql", use_root=True, cwd="/") cmd += [ "bash", "-c", f"exec mysql --user={DB_USER} --password={DB_PASSWORD}", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def list_services(): """List the services which have been running. Only the services for which /log/current exists are shown. """ _check_containers_running() typer.secho("Known services:", err=True) for service in _list_services()[1]: typer.secho(f"* {service}", err=True) @app.command() def runsvctrl(command: str, pattern: str): """Execute runsvctrl inside the server container.""" _check_containers_running() runit_dir, services = _list_services() cmd = _build_docker_cmd("server", cwd=runit_dir) services = fnmatch.filter(services, pattern) if not services: typer.secho(f"No services match {pattern!r}", fg=c.RED) raise typer.Exit(code=1) cmd += ["runsvctrl", command] + services os.execvp(cmd[0], cmd) @app.command() def logs(pattern: str = "*", lines: int = 10, follow: bool = True): """Show DIRAC's logs from the service container. For services matching [--pattern] show the most recent [--lines] from the logs. If [--follow] is True, continiously stream the logs. """ _check_containers_running() runit_dir, services = _list_services() base_cmd = _build_docker_cmd("server", tty=False) + ["tail"] base_cmd += [f"--lines={lines}"] if follow: base_cmd += ["-f"] with ThreadPoolExecutor(len(services)) as pool: for service in fnmatch.filter(services, pattern): cmd = base_cmd + [f"{runit_dir}/{service}/log/current"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None, text=True) pool.submit(_log_popen_stdout, p) class TestExit(typer.Exit): pass @contextmanager def _gen_docker_compose(modules): # Load the docker-compose configuration and mount the necessary volumes input_fn = Path(__file__).parent / "tests/CI/docker-compose.yml" docker_compose = yaml.safe_load(input_fn.read_text()) volumes = [f"{path}:/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name, path in modules.items()] volumes += [f"{path}:/home/dirac/LocalRepo/TestCode/{name}" for name, path in modules.items()] docker_compose["services"]["dirac-server"]["volumes"] = volumes[:] docker_compose["services"]["dirac-client"]["volumes"] = volumes[:] # Add any extension services for module_name, module_configs in _load_module_configs(modules).items(): for service_name, service_config in module_configs["extra-services"].items(): typer.secho(f"Adding service {service_name} for {module_name}", err=True, fg=c.GREEN) docker_compose["services"][service_name] = service_config.copy() docker_compose["services"][service_name]["volumes"] = volumes[:] # Write to a tempory file with the appropriate profile name prefix = "ci" with tempfile.TemporaryDirectory() as tmpdir: input_docker_compose_dir = Path(__file__).parent / "tests/CI/" output_fn = Path(tmpdir) / prefix / "docker-compose.yml" output_fn.parent.mkdir() output_fn.write_text(yaml.safe_dump(docker_compose, sort_keys=False)) shutil.copytree(input_docker_compose_dir / "envs", str(Path(tmpdir) / prefix), dirs_exist_ok=True) yield output_fn def _check_containers_running(*, is_up=True): with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: running_containers = subprocess.run( ["docker-compose", "-f", docker_compose_fn, "ps", "-q", "-a"], stdout=subprocess.PIPE, env=_make_env({}), check=True, text=True, ).stdout.split("\n") if is_up: if not any(running_containers): typer.secho( f"No running containers found, environment must be prepared first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) else: if any(running_containers): typer.secho( f"Running instance already found, it must be destroyed first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) def _find_dirac_release_and_branch(): # Start by looking for the GitHub/GitLab environment variables ref = os.environ.get("CI_COMMIT_REF_NAME", os.environ.get("GITHUB_REF")) if ref == "refs/heads/integration": return "integration", "" ref = os.environ.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", os.environ.get("GITHUB_BASE_REF")) if ref == "integration": return "integration", "" repo = git.Repo(os.getcwd()) # Try to make sure the upstream remote is up to date try: upstream = repo.remote("upstream") except ValueError: typer.secho("No upstream remote found, adding", err=True, fg=c.YELLOW) upstream = repo.create_remote("upstream", "https://github.com/DIRACGrid/DIRAC.git") try: upstream.fetch() except Exception: typer.secho("Failed to fetch from remote 'upstream'", err=True, fg=c.YELLOW) # Find the most recent tag on the current branch version = Version( repo.git.describe( dirty=True, tags=True, long=True, match="*[0-9]*", exclude=["v[0-9]r*", "v[0-9][0-9]r*"], ).split("-")[0] ) # See if there is a remote branch named "rel-vXrY" version_branch = f"rel-v{version.major}r{version.minor}" try: upstream.refs[version_branch] except IndexError: typer.secho( f"Failed to find branch for {version_branch}, defaulting to integration", err=True, fg=c.YELLOW, ) return "integration", "" else: return "", f"v{version.major}r{version.minor}" def _make_env(flags): env = os.environ.copy() env["DIRAC_UID"] = str(os.getuid()) env["DIRAC_GID"] = str(os.getgid()) env["HOST_OS"] = flags.pop("HOST_OS", DEFAULT_HOST_OS) env["CI_REGISTRY_IMAGE"] = flags.pop("CI_REGISTRY_IMAGE", "diracgrid") env["MYSQL_VER"] = flags.pop("MYSQL_VER", DEFAULT_MYSQL_VER) env["ES_VER"] = flags.pop("ES_VER", DEFAULT_ES_VER) return env def _dict_to_shell(variables): lines = [] for name, value in variables.items(): if value is None: continue elif isinstance(value, list): lines += [f"declare -a {name}"] lines += [f"{name}+=({shlex.quote(v)})" for v in value] elif isinstance(value, bool): lines += [f"export {name}={'Yes' if value else 'No'}"] elif isinstance(value, str): lines += [f"export {name}={shlex.quote(value)}"] else: raise NotImplementedError(name, value, type(value)) return "\n".join(lines) def _make_config(modules, flags, release_var, editable): config = { "DEBUG": "True", # MYSQL Settings "DB_USER": DB_USER, "DB_PASSWORD": DB_PASSWORD, "DB_ROOTUSER": DB_ROOTUSER, "DB_ROOTPWD": DB_ROOTPWD, "DB_HOST": DB_HOST, "DB_PORT": DB_PORT, # ElasticSearch settings "NoSQLDB_HOST": "elasticsearch", "NoSQLDB_PORT": "9200", # Hostnames "SERVER_HOST": "server", "CLIENT_HOST": "client", # Test specific variables "WORKSPACE": "/home/dirac", } if editable: config["PIP_INSTALL_EXTRA_ARGS"] = "-e" required_feature_flags = [] for module_name, module_ci_config in _load_module_configs(modules).items(): config |= module_ci_config["config"] required_feature_flags += module_ci_config.get("required-feature-flags", []) config["DIRAC_CI_SETUP_SCRIPT"] = "/home/dirac/LocalRepo/TestCode/" + config["DIRAC_CI_SETUP_SCRIPT"] # This can likely be removed after the Python 3 migration if release_var: config |= dict([release_var.split("=", 1)]) else: config["DIRAC_RELEASE"], config["DIRACBRANCH"] = _find_dirac_release_and_branch() for key, default_value in FEATURE_VARIABLES.items(): config[key] = flags.pop(key, default_value) for key in required_feature_flags: try: config[key] = flags.pop(key) except KeyError: typer.secho(f"Required feature variable {key!r} is missing", err=True, fg=c.RED) raise typer.Exit(code=1) config["TESTREPO"] = [f"/home/dirac/LocalRepo/TestCode/{name}" for name in modules] config["ALTERNATIVE_MODULES"] = [f"/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name in modules] # Exit with an error if there are unused feature flags remaining if flags: typer.secho(f"Unrecognised feature flags {flags!r}", err=True, fg=c.RED) raise typer.Exit(code=1) return config def
(modules): module_ci_configs = {} for module_name, module_path in modules.items(): module_ci_config_path = module_path / "tests/.dirac-ci-config.yaml" if not module_ci_config_path.exists(): continue module_ci_configs[module_name] = yaml.safe_load(module_ci_config_path.read_text()) return module_ci_configs def _build_docker_cmd(container_name, *, use_root=False, cwd="/home/dirac", tty=True): if use_root or os.getuid() == 0: user = "root" else: user = "dirac" cmd = ["docker", "exec"] if tty: if sys.stdout.isatty(): cmd += ["-it"] else: typer.secho( 'Not passing "-it" to docker as stdout is not a tty', err=True, fg=c.YELLOW, ) cmd += [ "-e=TERM=xterm-color", "-e=INSTALLROOT=/home/dirac", f"-e=INSTALLTYPE={container_name}", f"-u={user}", f"-w={cwd}", container_name, ] return cmd def _list_services(): # The Python 3 runit dir ends up in /diracos for runit_dir in ["ServerInstallDIR/runit", "ServerInstallDIR/diracos/runit"]: cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", f'cd {runit_dir}/ && for fn in */*/log/current; do echo "$(dirname "$(dirname "$fn")")"; done', ] ret = subprocess.run(cmd, check=False, stdout=subprocess.PIPE, text=True) if not ret.returncode: return runit_dir, ret.stdout.split() else: typer.secho("Failed to find list of available services", err=True, fg=c.RED) typer.secho(f"stdout was: {ret.stdout!r}", err=True) typer.secho(f"stderr was: {ret.stderr!r}", err=True) raise typer.Exit(1) def _log_popen_stdout(p): while p.poll() is None: line = p.stdout.readline().rstrip() if not line: continue bg, fg = None, None if match := LOG_PATTERN.match(line): bg, fg = LOG_LEVEL_MAP.get(match.groups()[0], (bg, fg)) typer.secho(line, err=True, bg=bg, fg=fg) if __name__ == "__main__": app()
_load_module_configs
identifier_name
integration_tests.py
#!/usr/bin/env python import fnmatch import os from pathlib import Path import re import shlex import shutil import subprocess import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from typing import Optional import click import git import typer import yaml from packaging.version import Version from typer import colors as c # Editable configuration DEFAULT_HOST_OS = "cc7" DEFAULT_MYSQL_VER = "mysql:8.0" DEFAULT_ES_VER = "elasticsearch:7.9.1" FEATURE_VARIABLES = { "DIRACOSVER": "master", "DIRACOS_TARBALL_PATH": None, "TEST_HTTPS": "No", "DIRAC_FEWER_CFG_LOCKS": None, "DIRAC_USE_JSON_ENCODE": None, "DIRAC_USE_JSON_DECODE": None, } DEFAULT_MODULES = { "DIRAC": Path(__file__).parent.absolute(), } # Static configuration DB_USER = "Dirac" DB_PASSWORD = "Dirac" DB_ROOTUSER = "root" DB_ROOTPWD = "password" DB_HOST = "mysql" DB_PORT = "3306" # Implementation details LOG_LEVEL_MAP = { "ALWAYS": (c.BLACK, c.WHITE), "NOTICE": (None, c.MAGENTA), "INFO": (None, c.GREEN), "VERBOSE": (None, c.CYAN), "DEBUG": (None, c.BLUE), "WARN": (None, c.YELLOW), "ERROR": (None, c.RED), "FATAL": (c.RED, c.BLACK), } LOG_PATTERN = re.compile(r"^[\d\-]{10} [\d:]{8} UTC [^\s]+ ([A-Z]+):") class NaturalOrderGroup(click.Group): """Group for showing subcommands in the correct order""" def list_commands(self, ctx): return self.commands.keys() app = typer.Typer( cls=NaturalOrderGroup, help=f"""Run the DIRAC integration tests. A local DIRAC setup can be created and tested by running: \b ./integration_tests.py create This is equivalent to running: \b ./integration_tests.py prepare-environment ./integration_tests.py install-server ./integration_tests.py install-client ./integration_tests.py test-server ./integration_tests.py test-client The test setup can be shutdown using: \b ./integration_tests.py destroy See below for additional subcommands which are useful during local development. ## Features The currently known features and their default values are: \b HOST_OS: {DEFAULT_HOST_OS!r} MYSQL_VER: {DEFAULT_MYSQL_VER!r} ES_VER: {DEFAULT_ES_VER!r} {(os.linesep + ' ').join(['%s: %r' % x for x in FEATURE_VARIABLES.items()])} All features can be prefixed with "SERVER_" or "CLIENT_" to limit their scope. ## Extensions Integration tests can be ran for extensions to DIRAC by specifying the module name and path such as: \b ./integration_tests.py create --extra-module MyDIRAC=/path/to/MyDIRAC This will modify the setup process based on the contents of `MyDIRAC/tests/.dirac-ci-config.yaml`. See the Vanilla DIRAC file for the available options. ## Command completion Command completion of typer based scripts can be enabled by running: typer --install-completion After restarting your terminal you command completion is available using: typer ./integration_tests.py run ... """, ) @app.command() def create(
release_var: Optional[str] = None, run_server_tests: bool = True, run_client_tests: bool = True, ): """Start a local instance of the integration tests""" prepare_environment(flags, editable, extra_module, release_var) install_server() install_client() exit_code = 0 if run_server_tests: try: test_server() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if run_client_tests: try: test_client() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if exit_code != 0: typer.secho("One or more tests failed", err=True, fg=c.RED) raise typer.Exit(exit_code) @app.command() def destroy(): """Destroy a local instance of the integration tests""" typer.secho("Shutting down and removing containers", err=True, fg=c.GREEN) with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: os.execvpe( "docker-compose", ["docker-compose", "-f", docker_compose_fn, "down", "--remove-orphans", "-t", "0"], _make_env({}), ) @app.command() def prepare_environment( flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None, release_var: Optional[str] = None, ): """Prepare the local environment for installing DIRAC.""" _check_containers_running(is_up=False) if editable is None: editable = sys.stdout.isatty() typer.secho( f"No value passed for --[no-]editable, automatically detected: {editable}", fg=c.YELLOW, ) typer.echo(f"Preparing environment") modules = DEFAULT_MODULES | dict(f.split("=", 1) for f in extra_module) modules = {k: Path(v).absolute() for k, v in modules.items()} flags = dict(f.split("=", 1) for f in flags) docker_compose_env = _make_env(flags) server_flags = {} client_flags = {} for key, value in flags.items(): if key.startswith("SERVER_"): server_flags[key[len("SERVER_") :]] = value elif key.startswith("CLIENT_"): client_flags[key[len("CLIENT_") :]] = value else: server_flags[key] = value client_flags[key] = value server_config = _make_config(modules, server_flags, release_var, editable) client_config = _make_config(modules, client_flags, release_var, editable) typer.secho("Running docker-compose to create containers", fg=c.GREEN) with _gen_docker_compose(modules) as docker_compose_fn: subprocess.run( ["docker-compose", "-f", docker_compose_fn, "up", "-d"], check=True, env=docker_compose_env, ) typer.secho("Creating users in server and client containers", fg=c.GREEN) for container_name in ["server", "client"]: if os.getuid() == 0: continue cmd = _build_docker_cmd(container_name, use_root=True, cwd="/") gid = str(os.getgid()) uid = str(os.getuid()) ret = subprocess.run(cmd + ["groupadd", "--gid", gid, "dirac"], check=False) if ret.returncode != 0: typer.secho(f"Failed to add add group dirac with id={gid}", fg=c.YELLOW) subprocess.run( cmd + [ "useradd", "--uid", uid, "--gid", gid, "-s", "/bin/bash", "-d", "/home/dirac", "dirac", ], check=True, ) subprocess.run(cmd + ["chown", "dirac", "/home/dirac"], check=True) typer.secho("Creating MySQL user", fg=c.GREEN) cmd = ["docker", "exec", "mysql", "mysql", f"--password={DB_ROOTPWD}", "-e"] # It sometimes takes a while for MySQL to be ready so wait for a while if needed for _ in range(10): ret = subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'%' IDENTIFIED BY '{DB_PASSWORD}';"], check=False, ) if ret.returncode == 0: break typer.secho("Failed to connect to MySQL, will retry in 10 seconds", fg=c.YELLOW) time.sleep(10) else: raise Exception(ret) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'localhost' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'mysql' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) typer.secho("Copying files to containers", fg=c.GREEN) for name, config in [("server", server_config), ("client", client_config)]: if path := config.get("DIRACOS_TARBALL_PATH"): path = Path(path) config["DIRACOS_TARBALL_PATH"] = f"/{path.name}" subprocess.run( ["docker", "cp", str(path), f"{name}:/{config['DIRACOS_TARBALL_PATH']}"], check=True, ) config_as_shell = _dict_to_shell(config) typer.secho(f"## {name.title()} config is:", fg=c.BRIGHT_WHITE, bg=c.BLACK) typer.secho(config_as_shell) with tempfile.TemporaryDirectory() as tmpdir: path = Path(tmpdir) / "CONFIG" path.write_text(config_as_shell) subprocess.run( ["docker", "cp", str(path), f"{name}:/home/dirac"], check=True, ) for module_name, module_configs in _load_module_configs(modules).items(): for command in module_configs.get("commands", {}).get("post-prepare", []): typer.secho( f"Running post-prepare command for {module_name}: {command}", err=True, fg=c.GREEN, ) subprocess.run(command, check=True, shell=True) @app.command() def install_server(): """Install DIRAC in the server container.""" _check_containers_running() typer.secho("Running server installation", fg=c.GREEN) base_cmd = _build_docker_cmd("server", tty=False) subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_server.sh"], check=True, ) typer.secho("Copying credentials and certificates", fg=c.GREEN) base_cmd = _build_docker_cmd("client", tty=False) subprocess.run( base_cmd + [ "mkdir", "-p", "/home/dirac/ServerInstallDIR/user", "/home/dirac/ClientInstallDIR/etc", "/home/dirac/.globus", ], check=True, ) for path in [ "etc/grid-security", "user/client.pem", "user/client.key", f"/tmp/x509up_u{os.getuid()}", ]: source = os.path.join("/home/dirac/ServerInstallDIR", path) ret = subprocess.run( ["docker", "cp", f"server:{source}", "-"], check=True, text=False, stdout=subprocess.PIPE, ) if path.startswith("user/"): dest = f"client:/home/dirac/ServerInstallDIR/{os.path.dirname(path)}" elif path.startswith("/"): dest = f"client:{os.path.dirname(path)}" else: dest = f"client:/home/dirac/ClientInstallDIR/{os.path.dirname(path)}" subprocess.run(["docker", "cp", "-", dest], check=True, text=False, input=ret.stdout) subprocess.run( base_cmd + [ "bash", "-c", "cp /home/dirac/ServerInstallDIR/user/client.* /home/dirac/.globus/", ], check=True, ) @app.command() def install_client(): """Install DIRAC in the client container.""" _check_containers_running() typer.secho("Running client installation", fg=c.GREEN) base_cmd = _build_docker_cmd("client") subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_client.sh"], check=True, ) @app.command() def test_server(): """Run the server integration tests.""" _check_containers_running() typer.secho("Running server tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("server") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Server tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def test_client(): """Run the client integration tests.""" _check_containers_running() typer.secho("Running client tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("client") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Client tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def exec_server(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ServerInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_client(): """Start an interactive session in the client container.""" _check_containers_running() cmd = _build_docker_cmd("client") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ClientInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside client container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_mysql(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("mysql", use_root=True, cwd="/") cmd += [ "bash", "-c", f"exec mysql --user={DB_USER} --password={DB_PASSWORD}", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def list_services(): """List the services which have been running. Only the services for which /log/current exists are shown. """ _check_containers_running() typer.secho("Known services:", err=True) for service in _list_services()[1]: typer.secho(f"* {service}", err=True) @app.command() def runsvctrl(command: str, pattern: str): """Execute runsvctrl inside the server container.""" _check_containers_running() runit_dir, services = _list_services() cmd = _build_docker_cmd("server", cwd=runit_dir) services = fnmatch.filter(services, pattern) if not services: typer.secho(f"No services match {pattern!r}", fg=c.RED) raise typer.Exit(code=1) cmd += ["runsvctrl", command] + services os.execvp(cmd[0], cmd) @app.command() def logs(pattern: str = "*", lines: int = 10, follow: bool = True): """Show DIRAC's logs from the service container. For services matching [--pattern] show the most recent [--lines] from the logs. If [--follow] is True, continiously stream the logs. """ _check_containers_running() runit_dir, services = _list_services() base_cmd = _build_docker_cmd("server", tty=False) + ["tail"] base_cmd += [f"--lines={lines}"] if follow: base_cmd += ["-f"] with ThreadPoolExecutor(len(services)) as pool: for service in fnmatch.filter(services, pattern): cmd = base_cmd + [f"{runit_dir}/{service}/log/current"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None, text=True) pool.submit(_log_popen_stdout, p) class TestExit(typer.Exit): pass @contextmanager def _gen_docker_compose(modules): # Load the docker-compose configuration and mount the necessary volumes input_fn = Path(__file__).parent / "tests/CI/docker-compose.yml" docker_compose = yaml.safe_load(input_fn.read_text()) volumes = [f"{path}:/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name, path in modules.items()] volumes += [f"{path}:/home/dirac/LocalRepo/TestCode/{name}" for name, path in modules.items()] docker_compose["services"]["dirac-server"]["volumes"] = volumes[:] docker_compose["services"]["dirac-client"]["volumes"] = volumes[:] # Add any extension services for module_name, module_configs in _load_module_configs(modules).items(): for service_name, service_config in module_configs["extra-services"].items(): typer.secho(f"Adding service {service_name} for {module_name}", err=True, fg=c.GREEN) docker_compose["services"][service_name] = service_config.copy() docker_compose["services"][service_name]["volumes"] = volumes[:] # Write to a tempory file with the appropriate profile name prefix = "ci" with tempfile.TemporaryDirectory() as tmpdir: input_docker_compose_dir = Path(__file__).parent / "tests/CI/" output_fn = Path(tmpdir) / prefix / "docker-compose.yml" output_fn.parent.mkdir() output_fn.write_text(yaml.safe_dump(docker_compose, sort_keys=False)) shutil.copytree(input_docker_compose_dir / "envs", str(Path(tmpdir) / prefix), dirs_exist_ok=True) yield output_fn def _check_containers_running(*, is_up=True): with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: running_containers = subprocess.run( ["docker-compose", "-f", docker_compose_fn, "ps", "-q", "-a"], stdout=subprocess.PIPE, env=_make_env({}), check=True, text=True, ).stdout.split("\n") if is_up: if not any(running_containers): typer.secho( f"No running containers found, environment must be prepared first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) else: if any(running_containers): typer.secho( f"Running instance already found, it must be destroyed first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) def _find_dirac_release_and_branch(): # Start by looking for the GitHub/GitLab environment variables ref = os.environ.get("CI_COMMIT_REF_NAME", os.environ.get("GITHUB_REF")) if ref == "refs/heads/integration": return "integration", "" ref = os.environ.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", os.environ.get("GITHUB_BASE_REF")) if ref == "integration": return "integration", "" repo = git.Repo(os.getcwd()) # Try to make sure the upstream remote is up to date try: upstream = repo.remote("upstream") except ValueError: typer.secho("No upstream remote found, adding", err=True, fg=c.YELLOW) upstream = repo.create_remote("upstream", "https://github.com/DIRACGrid/DIRAC.git") try: upstream.fetch() except Exception: typer.secho("Failed to fetch from remote 'upstream'", err=True, fg=c.YELLOW) # Find the most recent tag on the current branch version = Version( repo.git.describe( dirty=True, tags=True, long=True, match="*[0-9]*", exclude=["v[0-9]r*", "v[0-9][0-9]r*"], ).split("-")[0] ) # See if there is a remote branch named "rel-vXrY" version_branch = f"rel-v{version.major}r{version.minor}" try: upstream.refs[version_branch] except IndexError: typer.secho( f"Failed to find branch for {version_branch}, defaulting to integration", err=True, fg=c.YELLOW, ) return "integration", "" else: return "", f"v{version.major}r{version.minor}" def _make_env(flags): env = os.environ.copy() env["DIRAC_UID"] = str(os.getuid()) env["DIRAC_GID"] = str(os.getgid()) env["HOST_OS"] = flags.pop("HOST_OS", DEFAULT_HOST_OS) env["CI_REGISTRY_IMAGE"] = flags.pop("CI_REGISTRY_IMAGE", "diracgrid") env["MYSQL_VER"] = flags.pop("MYSQL_VER", DEFAULT_MYSQL_VER) env["ES_VER"] = flags.pop("ES_VER", DEFAULT_ES_VER) return env def _dict_to_shell(variables): lines = [] for name, value in variables.items(): if value is None: continue elif isinstance(value, list): lines += [f"declare -a {name}"] lines += [f"{name}+=({shlex.quote(v)})" for v in value] elif isinstance(value, bool): lines += [f"export {name}={'Yes' if value else 'No'}"] elif isinstance(value, str): lines += [f"export {name}={shlex.quote(value)}"] else: raise NotImplementedError(name, value, type(value)) return "\n".join(lines) def _make_config(modules, flags, release_var, editable): config = { "DEBUG": "True", # MYSQL Settings "DB_USER": DB_USER, "DB_PASSWORD": DB_PASSWORD, "DB_ROOTUSER": DB_ROOTUSER, "DB_ROOTPWD": DB_ROOTPWD, "DB_HOST": DB_HOST, "DB_PORT": DB_PORT, # ElasticSearch settings "NoSQLDB_HOST": "elasticsearch", "NoSQLDB_PORT": "9200", # Hostnames "SERVER_HOST": "server", "CLIENT_HOST": "client", # Test specific variables "WORKSPACE": "/home/dirac", } if editable: config["PIP_INSTALL_EXTRA_ARGS"] = "-e" required_feature_flags = [] for module_name, module_ci_config in _load_module_configs(modules).items(): config |= module_ci_config["config"] required_feature_flags += module_ci_config.get("required-feature-flags", []) config["DIRAC_CI_SETUP_SCRIPT"] = "/home/dirac/LocalRepo/TestCode/" + config["DIRAC_CI_SETUP_SCRIPT"] # This can likely be removed after the Python 3 migration if release_var: config |= dict([release_var.split("=", 1)]) else: config["DIRAC_RELEASE"], config["DIRACBRANCH"] = _find_dirac_release_and_branch() for key, default_value in FEATURE_VARIABLES.items(): config[key] = flags.pop(key, default_value) for key in required_feature_flags: try: config[key] = flags.pop(key) except KeyError: typer.secho(f"Required feature variable {key!r} is missing", err=True, fg=c.RED) raise typer.Exit(code=1) config["TESTREPO"] = [f"/home/dirac/LocalRepo/TestCode/{name}" for name in modules] config["ALTERNATIVE_MODULES"] = [f"/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name in modules] # Exit with an error if there are unused feature flags remaining if flags: typer.secho(f"Unrecognised feature flags {flags!r}", err=True, fg=c.RED) raise typer.Exit(code=1) return config def _load_module_configs(modules): module_ci_configs = {} for module_name, module_path in modules.items(): module_ci_config_path = module_path / "tests/.dirac-ci-config.yaml" if not module_ci_config_path.exists(): continue module_ci_configs[module_name] = yaml.safe_load(module_ci_config_path.read_text()) return module_ci_configs def _build_docker_cmd(container_name, *, use_root=False, cwd="/home/dirac", tty=True): if use_root or os.getuid() == 0: user = "root" else: user = "dirac" cmd = ["docker", "exec"] if tty: if sys.stdout.isatty(): cmd += ["-it"] else: typer.secho( 'Not passing "-it" to docker as stdout is not a tty', err=True, fg=c.YELLOW, ) cmd += [ "-e=TERM=xterm-color", "-e=INSTALLROOT=/home/dirac", f"-e=INSTALLTYPE={container_name}", f"-u={user}", f"-w={cwd}", container_name, ] return cmd def _list_services(): # The Python 3 runit dir ends up in /diracos for runit_dir in ["ServerInstallDIR/runit", "ServerInstallDIR/diracos/runit"]: cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", f'cd {runit_dir}/ && for fn in */*/log/current; do echo "$(dirname "$(dirname "$fn")")"; done', ] ret = subprocess.run(cmd, check=False, stdout=subprocess.PIPE, text=True) if not ret.returncode: return runit_dir, ret.stdout.split() else: typer.secho("Failed to find list of available services", err=True, fg=c.RED) typer.secho(f"stdout was: {ret.stdout!r}", err=True) typer.secho(f"stderr was: {ret.stderr!r}", err=True) raise typer.Exit(1) def _log_popen_stdout(p): while p.poll() is None: line = p.stdout.readline().rstrip() if not line: continue bg, fg = None, None if match := LOG_PATTERN.match(line): bg, fg = LOG_LEVEL_MAP.get(match.groups()[0], (bg, fg)) typer.secho(line, err=True, bg=bg, fg=fg) if __name__ == "__main__": app()
flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None,
random_line_split
integration_tests.py
#!/usr/bin/env python import fnmatch import os from pathlib import Path import re import shlex import shutil import subprocess import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from typing import Optional import click import git import typer import yaml from packaging.version import Version from typer import colors as c # Editable configuration DEFAULT_HOST_OS = "cc7" DEFAULT_MYSQL_VER = "mysql:8.0" DEFAULT_ES_VER = "elasticsearch:7.9.1" FEATURE_VARIABLES = { "DIRACOSVER": "master", "DIRACOS_TARBALL_PATH": None, "TEST_HTTPS": "No", "DIRAC_FEWER_CFG_LOCKS": None, "DIRAC_USE_JSON_ENCODE": None, "DIRAC_USE_JSON_DECODE": None, } DEFAULT_MODULES = { "DIRAC": Path(__file__).parent.absolute(), } # Static configuration DB_USER = "Dirac" DB_PASSWORD = "Dirac" DB_ROOTUSER = "root" DB_ROOTPWD = "password" DB_HOST = "mysql" DB_PORT = "3306" # Implementation details LOG_LEVEL_MAP = { "ALWAYS": (c.BLACK, c.WHITE), "NOTICE": (None, c.MAGENTA), "INFO": (None, c.GREEN), "VERBOSE": (None, c.CYAN), "DEBUG": (None, c.BLUE), "WARN": (None, c.YELLOW), "ERROR": (None, c.RED), "FATAL": (c.RED, c.BLACK), } LOG_PATTERN = re.compile(r"^[\d\-]{10} [\d:]{8} UTC [^\s]+ ([A-Z]+):") class NaturalOrderGroup(click.Group): """Group for showing subcommands in the correct order""" def list_commands(self, ctx): return self.commands.keys() app = typer.Typer( cls=NaturalOrderGroup, help=f"""Run the DIRAC integration tests. A local DIRAC setup can be created and tested by running: \b ./integration_tests.py create This is equivalent to running: \b ./integration_tests.py prepare-environment ./integration_tests.py install-server ./integration_tests.py install-client ./integration_tests.py test-server ./integration_tests.py test-client The test setup can be shutdown using: \b ./integration_tests.py destroy See below for additional subcommands which are useful during local development. ## Features The currently known features and their default values are: \b HOST_OS: {DEFAULT_HOST_OS!r} MYSQL_VER: {DEFAULT_MYSQL_VER!r} ES_VER: {DEFAULT_ES_VER!r} {(os.linesep + ' ').join(['%s: %r' % x for x in FEATURE_VARIABLES.items()])} All features can be prefixed with "SERVER_" or "CLIENT_" to limit their scope. ## Extensions Integration tests can be ran for extensions to DIRAC by specifying the module name and path such as: \b ./integration_tests.py create --extra-module MyDIRAC=/path/to/MyDIRAC This will modify the setup process based on the contents of `MyDIRAC/tests/.dirac-ci-config.yaml`. See the Vanilla DIRAC file for the available options. ## Command completion Command completion of typer based scripts can be enabled by running: typer --install-completion After restarting your terminal you command completion is available using: typer ./integration_tests.py run ... """, ) @app.command() def create( flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None, release_var: Optional[str] = None, run_server_tests: bool = True, run_client_tests: bool = True, ): """Start a local instance of the integration tests""" prepare_environment(flags, editable, extra_module, release_var) install_server() install_client() exit_code = 0 if run_server_tests: try: test_server() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if run_client_tests: try: test_client() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if exit_code != 0: typer.secho("One or more tests failed", err=True, fg=c.RED) raise typer.Exit(exit_code) @app.command() def destroy(): """Destroy a local instance of the integration tests""" typer.secho("Shutting down and removing containers", err=True, fg=c.GREEN) with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: os.execvpe( "docker-compose", ["docker-compose", "-f", docker_compose_fn, "down", "--remove-orphans", "-t", "0"], _make_env({}), ) @app.command() def prepare_environment( flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None, release_var: Optional[str] = None, ): """Prepare the local environment for installing DIRAC.""" _check_containers_running(is_up=False) if editable is None: editable = sys.stdout.isatty() typer.secho( f"No value passed for --[no-]editable, automatically detected: {editable}", fg=c.YELLOW, ) typer.echo(f"Preparing environment") modules = DEFAULT_MODULES | dict(f.split("=", 1) for f in extra_module) modules = {k: Path(v).absolute() for k, v in modules.items()} flags = dict(f.split("=", 1) for f in flags) docker_compose_env = _make_env(flags) server_flags = {} client_flags = {} for key, value in flags.items(): if key.startswith("SERVER_"): server_flags[key[len("SERVER_") :]] = value elif key.startswith("CLIENT_"): client_flags[key[len("CLIENT_") :]] = value else: server_flags[key] = value client_flags[key] = value server_config = _make_config(modules, server_flags, release_var, editable) client_config = _make_config(modules, client_flags, release_var, editable) typer.secho("Running docker-compose to create containers", fg=c.GREEN) with _gen_docker_compose(modules) as docker_compose_fn: subprocess.run( ["docker-compose", "-f", docker_compose_fn, "up", "-d"], check=True, env=docker_compose_env, ) typer.secho("Creating users in server and client containers", fg=c.GREEN) for container_name in ["server", "client"]: if os.getuid() == 0: continue cmd = _build_docker_cmd(container_name, use_root=True, cwd="/") gid = str(os.getgid()) uid = str(os.getuid()) ret = subprocess.run(cmd + ["groupadd", "--gid", gid, "dirac"], check=False) if ret.returncode != 0: typer.secho(f"Failed to add add group dirac with id={gid}", fg=c.YELLOW) subprocess.run( cmd + [ "useradd", "--uid", uid, "--gid", gid, "-s", "/bin/bash", "-d", "/home/dirac", "dirac", ], check=True, ) subprocess.run(cmd + ["chown", "dirac", "/home/dirac"], check=True) typer.secho("Creating MySQL user", fg=c.GREEN) cmd = ["docker", "exec", "mysql", "mysql", f"--password={DB_ROOTPWD}", "-e"] # It sometimes takes a while for MySQL to be ready so wait for a while if needed for _ in range(10): ret = subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'%' IDENTIFIED BY '{DB_PASSWORD}';"], check=False, ) if ret.returncode == 0: break typer.secho("Failed to connect to MySQL, will retry in 10 seconds", fg=c.YELLOW) time.sleep(10) else: raise Exception(ret) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'localhost' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'mysql' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) typer.secho("Copying files to containers", fg=c.GREEN) for name, config in [("server", server_config), ("client", client_config)]: if path := config.get("DIRACOS_TARBALL_PATH"): path = Path(path) config["DIRACOS_TARBALL_PATH"] = f"/{path.name}" subprocess.run( ["docker", "cp", str(path), f"{name}:/{config['DIRACOS_TARBALL_PATH']}"], check=True, ) config_as_shell = _dict_to_shell(config) typer.secho(f"## {name.title()} config is:", fg=c.BRIGHT_WHITE, bg=c.BLACK) typer.secho(config_as_shell) with tempfile.TemporaryDirectory() as tmpdir: path = Path(tmpdir) / "CONFIG" path.write_text(config_as_shell) subprocess.run( ["docker", "cp", str(path), f"{name}:/home/dirac"], check=True, ) for module_name, module_configs in _load_module_configs(modules).items(): for command in module_configs.get("commands", {}).get("post-prepare", []): typer.secho( f"Running post-prepare command for {module_name}: {command}", err=True, fg=c.GREEN, ) subprocess.run(command, check=True, shell=True) @app.command() def install_server(): """Install DIRAC in the server container.""" _check_containers_running() typer.secho("Running server installation", fg=c.GREEN) base_cmd = _build_docker_cmd("server", tty=False) subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_server.sh"], check=True, ) typer.secho("Copying credentials and certificates", fg=c.GREEN) base_cmd = _build_docker_cmd("client", tty=False) subprocess.run( base_cmd + [ "mkdir", "-p", "/home/dirac/ServerInstallDIR/user", "/home/dirac/ClientInstallDIR/etc", "/home/dirac/.globus", ], check=True, ) for path in [ "etc/grid-security", "user/client.pem", "user/client.key", f"/tmp/x509up_u{os.getuid()}", ]: source = os.path.join("/home/dirac/ServerInstallDIR", path) ret = subprocess.run( ["docker", "cp", f"server:{source}", "-"], check=True, text=False, stdout=subprocess.PIPE, ) if path.startswith("user/"): dest = f"client:/home/dirac/ServerInstallDIR/{os.path.dirname(path)}" elif path.startswith("/"): dest = f"client:{os.path.dirname(path)}" else: dest = f"client:/home/dirac/ClientInstallDIR/{os.path.dirname(path)}" subprocess.run(["docker", "cp", "-", dest], check=True, text=False, input=ret.stdout) subprocess.run( base_cmd + [ "bash", "-c", "cp /home/dirac/ServerInstallDIR/user/client.* /home/dirac/.globus/", ], check=True, ) @app.command() def install_client(): """Install DIRAC in the client container.""" _check_containers_running() typer.secho("Running client installation", fg=c.GREEN) base_cmd = _build_docker_cmd("client") subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_client.sh"], check=True, ) @app.command() def test_server(): """Run the server integration tests.""" _check_containers_running() typer.secho("Running server tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("server") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Server tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def test_client(): """Run the client integration tests.""" _check_containers_running() typer.secho("Running client tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("client") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Client tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def exec_server(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ServerInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_client(): """Start an interactive session in the client container.""" _check_containers_running() cmd = _build_docker_cmd("client") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ClientInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside client container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_mysql(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("mysql", use_root=True, cwd="/") cmd += [ "bash", "-c", f"exec mysql --user={DB_USER} --password={DB_PASSWORD}", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def list_services():
@app.command() def runsvctrl(command: str, pattern: str): """Execute runsvctrl inside the server container.""" _check_containers_running() runit_dir, services = _list_services() cmd = _build_docker_cmd("server", cwd=runit_dir) services = fnmatch.filter(services, pattern) if not services: typer.secho(f"No services match {pattern!r}", fg=c.RED) raise typer.Exit(code=1) cmd += ["runsvctrl", command] + services os.execvp(cmd[0], cmd) @app.command() def logs(pattern: str = "*", lines: int = 10, follow: bool = True): """Show DIRAC's logs from the service container. For services matching [--pattern] show the most recent [--lines] from the logs. If [--follow] is True, continiously stream the logs. """ _check_containers_running() runit_dir, services = _list_services() base_cmd = _build_docker_cmd("server", tty=False) + ["tail"] base_cmd += [f"--lines={lines}"] if follow: base_cmd += ["-f"] with ThreadPoolExecutor(len(services)) as pool: for service in fnmatch.filter(services, pattern): cmd = base_cmd + [f"{runit_dir}/{service}/log/current"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None, text=True) pool.submit(_log_popen_stdout, p) class TestExit(typer.Exit): pass @contextmanager def _gen_docker_compose(modules): # Load the docker-compose configuration and mount the necessary volumes input_fn = Path(__file__).parent / "tests/CI/docker-compose.yml" docker_compose = yaml.safe_load(input_fn.read_text()) volumes = [f"{path}:/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name, path in modules.items()] volumes += [f"{path}:/home/dirac/LocalRepo/TestCode/{name}" for name, path in modules.items()] docker_compose["services"]["dirac-server"]["volumes"] = volumes[:] docker_compose["services"]["dirac-client"]["volumes"] = volumes[:] # Add any extension services for module_name, module_configs in _load_module_configs(modules).items(): for service_name, service_config in module_configs["extra-services"].items(): typer.secho(f"Adding service {service_name} for {module_name}", err=True, fg=c.GREEN) docker_compose["services"][service_name] = service_config.copy() docker_compose["services"][service_name]["volumes"] = volumes[:] # Write to a tempory file with the appropriate profile name prefix = "ci" with tempfile.TemporaryDirectory() as tmpdir: input_docker_compose_dir = Path(__file__).parent / "tests/CI/" output_fn = Path(tmpdir) / prefix / "docker-compose.yml" output_fn.parent.mkdir() output_fn.write_text(yaml.safe_dump(docker_compose, sort_keys=False)) shutil.copytree(input_docker_compose_dir / "envs", str(Path(tmpdir) / prefix), dirs_exist_ok=True) yield output_fn def _check_containers_running(*, is_up=True): with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: running_containers = subprocess.run( ["docker-compose", "-f", docker_compose_fn, "ps", "-q", "-a"], stdout=subprocess.PIPE, env=_make_env({}), check=True, text=True, ).stdout.split("\n") if is_up: if not any(running_containers): typer.secho( f"No running containers found, environment must be prepared first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) else: if any(running_containers): typer.secho( f"Running instance already found, it must be destroyed first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) def _find_dirac_release_and_branch(): # Start by looking for the GitHub/GitLab environment variables ref = os.environ.get("CI_COMMIT_REF_NAME", os.environ.get("GITHUB_REF")) if ref == "refs/heads/integration": return "integration", "" ref = os.environ.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", os.environ.get("GITHUB_BASE_REF")) if ref == "integration": return "integration", "" repo = git.Repo(os.getcwd()) # Try to make sure the upstream remote is up to date try: upstream = repo.remote("upstream") except ValueError: typer.secho("No upstream remote found, adding", err=True, fg=c.YELLOW) upstream = repo.create_remote("upstream", "https://github.com/DIRACGrid/DIRAC.git") try: upstream.fetch() except Exception: typer.secho("Failed to fetch from remote 'upstream'", err=True, fg=c.YELLOW) # Find the most recent tag on the current branch version = Version( repo.git.describe( dirty=True, tags=True, long=True, match="*[0-9]*", exclude=["v[0-9]r*", "v[0-9][0-9]r*"], ).split("-")[0] ) # See if there is a remote branch named "rel-vXrY" version_branch = f"rel-v{version.major}r{version.minor}" try: upstream.refs[version_branch] except IndexError: typer.secho( f"Failed to find branch for {version_branch}, defaulting to integration", err=True, fg=c.YELLOW, ) return "integration", "" else: return "", f"v{version.major}r{version.minor}" def _make_env(flags): env = os.environ.copy() env["DIRAC_UID"] = str(os.getuid()) env["DIRAC_GID"] = str(os.getgid()) env["HOST_OS"] = flags.pop("HOST_OS", DEFAULT_HOST_OS) env["CI_REGISTRY_IMAGE"] = flags.pop("CI_REGISTRY_IMAGE", "diracgrid") env["MYSQL_VER"] = flags.pop("MYSQL_VER", DEFAULT_MYSQL_VER) env["ES_VER"] = flags.pop("ES_VER", DEFAULT_ES_VER) return env def _dict_to_shell(variables): lines = [] for name, value in variables.items(): if value is None: continue elif isinstance(value, list): lines += [f"declare -a {name}"] lines += [f"{name}+=({shlex.quote(v)})" for v in value] elif isinstance(value, bool): lines += [f"export {name}={'Yes' if value else 'No'}"] elif isinstance(value, str): lines += [f"export {name}={shlex.quote(value)}"] else: raise NotImplementedError(name, value, type(value)) return "\n".join(lines) def _make_config(modules, flags, release_var, editable): config = { "DEBUG": "True", # MYSQL Settings "DB_USER": DB_USER, "DB_PASSWORD": DB_PASSWORD, "DB_ROOTUSER": DB_ROOTUSER, "DB_ROOTPWD": DB_ROOTPWD, "DB_HOST": DB_HOST, "DB_PORT": DB_PORT, # ElasticSearch settings "NoSQLDB_HOST": "elasticsearch", "NoSQLDB_PORT": "9200", # Hostnames "SERVER_HOST": "server", "CLIENT_HOST": "client", # Test specific variables "WORKSPACE": "/home/dirac", } if editable: config["PIP_INSTALL_EXTRA_ARGS"] = "-e" required_feature_flags = [] for module_name, module_ci_config in _load_module_configs(modules).items(): config |= module_ci_config["config"] required_feature_flags += module_ci_config.get("required-feature-flags", []) config["DIRAC_CI_SETUP_SCRIPT"] = "/home/dirac/LocalRepo/TestCode/" + config["DIRAC_CI_SETUP_SCRIPT"] # This can likely be removed after the Python 3 migration if release_var: config |= dict([release_var.split("=", 1)]) else: config["DIRAC_RELEASE"], config["DIRACBRANCH"] = _find_dirac_release_and_branch() for key, default_value in FEATURE_VARIABLES.items(): config[key] = flags.pop(key, default_value) for key in required_feature_flags: try: config[key] = flags.pop(key) except KeyError: typer.secho(f"Required feature variable {key!r} is missing", err=True, fg=c.RED) raise typer.Exit(code=1) config["TESTREPO"] = [f"/home/dirac/LocalRepo/TestCode/{name}" for name in modules] config["ALTERNATIVE_MODULES"] = [f"/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name in modules] # Exit with an error if there are unused feature flags remaining if flags: typer.secho(f"Unrecognised feature flags {flags!r}", err=True, fg=c.RED) raise typer.Exit(code=1) return config def _load_module_configs(modules): module_ci_configs = {} for module_name, module_path in modules.items(): module_ci_config_path = module_path / "tests/.dirac-ci-config.yaml" if not module_ci_config_path.exists(): continue module_ci_configs[module_name] = yaml.safe_load(module_ci_config_path.read_text()) return module_ci_configs def _build_docker_cmd(container_name, *, use_root=False, cwd="/home/dirac", tty=True): if use_root or os.getuid() == 0: user = "root" else: user = "dirac" cmd = ["docker", "exec"] if tty: if sys.stdout.isatty(): cmd += ["-it"] else: typer.secho( 'Not passing "-it" to docker as stdout is not a tty', err=True, fg=c.YELLOW, ) cmd += [ "-e=TERM=xterm-color", "-e=INSTALLROOT=/home/dirac", f"-e=INSTALLTYPE={container_name}", f"-u={user}", f"-w={cwd}", container_name, ] return cmd def _list_services(): # The Python 3 runit dir ends up in /diracos for runit_dir in ["ServerInstallDIR/runit", "ServerInstallDIR/diracos/runit"]: cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", f'cd {runit_dir}/ && for fn in */*/log/current; do echo "$(dirname "$(dirname "$fn")")"; done', ] ret = subprocess.run(cmd, check=False, stdout=subprocess.PIPE, text=True) if not ret.returncode: return runit_dir, ret.stdout.split() else: typer.secho("Failed to find list of available services", err=True, fg=c.RED) typer.secho(f"stdout was: {ret.stdout!r}", err=True) typer.secho(f"stderr was: {ret.stderr!r}", err=True) raise typer.Exit(1) def _log_popen_stdout(p): while p.poll() is None: line = p.stdout.readline().rstrip() if not line: continue bg, fg = None, None if match := LOG_PATTERN.match(line): bg, fg = LOG_LEVEL_MAP.get(match.groups()[0], (bg, fg)) typer.secho(line, err=True, bg=bg, fg=fg) if __name__ == "__main__": app()
"""List the services which have been running. Only the services for which /log/current exists are shown. """ _check_containers_running() typer.secho("Known services:", err=True) for service in _list_services()[1]: typer.secho(f"* {service}", err=True)
identifier_body
integration_tests.py
#!/usr/bin/env python import fnmatch import os from pathlib import Path import re import shlex import shutil import subprocess import sys import tempfile import time from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from typing import Optional import click import git import typer import yaml from packaging.version import Version from typer import colors as c # Editable configuration DEFAULT_HOST_OS = "cc7" DEFAULT_MYSQL_VER = "mysql:8.0" DEFAULT_ES_VER = "elasticsearch:7.9.1" FEATURE_VARIABLES = { "DIRACOSVER": "master", "DIRACOS_TARBALL_PATH": None, "TEST_HTTPS": "No", "DIRAC_FEWER_CFG_LOCKS": None, "DIRAC_USE_JSON_ENCODE": None, "DIRAC_USE_JSON_DECODE": None, } DEFAULT_MODULES = { "DIRAC": Path(__file__).parent.absolute(), } # Static configuration DB_USER = "Dirac" DB_PASSWORD = "Dirac" DB_ROOTUSER = "root" DB_ROOTPWD = "password" DB_HOST = "mysql" DB_PORT = "3306" # Implementation details LOG_LEVEL_MAP = { "ALWAYS": (c.BLACK, c.WHITE), "NOTICE": (None, c.MAGENTA), "INFO": (None, c.GREEN), "VERBOSE": (None, c.CYAN), "DEBUG": (None, c.BLUE), "WARN": (None, c.YELLOW), "ERROR": (None, c.RED), "FATAL": (c.RED, c.BLACK), } LOG_PATTERN = re.compile(r"^[\d\-]{10} [\d:]{8} UTC [^\s]+ ([A-Z]+):") class NaturalOrderGroup(click.Group): """Group for showing subcommands in the correct order""" def list_commands(self, ctx): return self.commands.keys() app = typer.Typer( cls=NaturalOrderGroup, help=f"""Run the DIRAC integration tests. A local DIRAC setup can be created and tested by running: \b ./integration_tests.py create This is equivalent to running: \b ./integration_tests.py prepare-environment ./integration_tests.py install-server ./integration_tests.py install-client ./integration_tests.py test-server ./integration_tests.py test-client The test setup can be shutdown using: \b ./integration_tests.py destroy See below for additional subcommands which are useful during local development. ## Features The currently known features and their default values are: \b HOST_OS: {DEFAULT_HOST_OS!r} MYSQL_VER: {DEFAULT_MYSQL_VER!r} ES_VER: {DEFAULT_ES_VER!r} {(os.linesep + ' ').join(['%s: %r' % x for x in FEATURE_VARIABLES.items()])} All features can be prefixed with "SERVER_" or "CLIENT_" to limit their scope. ## Extensions Integration tests can be ran for extensions to DIRAC by specifying the module name and path such as: \b ./integration_tests.py create --extra-module MyDIRAC=/path/to/MyDIRAC This will modify the setup process based on the contents of `MyDIRAC/tests/.dirac-ci-config.yaml`. See the Vanilla DIRAC file for the available options. ## Command completion Command completion of typer based scripts can be enabled by running: typer --install-completion After restarting your terminal you command completion is available using: typer ./integration_tests.py run ... """, ) @app.command() def create( flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None, release_var: Optional[str] = None, run_server_tests: bool = True, run_client_tests: bool = True, ): """Start a local instance of the integration tests""" prepare_environment(flags, editable, extra_module, release_var) install_server() install_client() exit_code = 0 if run_server_tests: try: test_server() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if run_client_tests: try: test_client() except TestExit as e: exit_code += e.exit_code else: raise NotImplementedError() if exit_code != 0: typer.secho("One or more tests failed", err=True, fg=c.RED) raise typer.Exit(exit_code) @app.command() def destroy(): """Destroy a local instance of the integration tests""" typer.secho("Shutting down and removing containers", err=True, fg=c.GREEN) with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: os.execvpe( "docker-compose", ["docker-compose", "-f", docker_compose_fn, "down", "--remove-orphans", "-t", "0"], _make_env({}), ) @app.command() def prepare_environment( flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None, release_var: Optional[str] = None, ): """Prepare the local environment for installing DIRAC.""" _check_containers_running(is_up=False) if editable is None: editable = sys.stdout.isatty() typer.secho( f"No value passed for --[no-]editable, automatically detected: {editable}", fg=c.YELLOW, ) typer.echo(f"Preparing environment") modules = DEFAULT_MODULES | dict(f.split("=", 1) for f in extra_module) modules = {k: Path(v).absolute() for k, v in modules.items()} flags = dict(f.split("=", 1) for f in flags) docker_compose_env = _make_env(flags) server_flags = {} client_flags = {} for key, value in flags.items(): if key.startswith("SERVER_"): server_flags[key[len("SERVER_") :]] = value elif key.startswith("CLIENT_"): client_flags[key[len("CLIENT_") :]] = value else: server_flags[key] = value client_flags[key] = value server_config = _make_config(modules, server_flags, release_var, editable) client_config = _make_config(modules, client_flags, release_var, editable) typer.secho("Running docker-compose to create containers", fg=c.GREEN) with _gen_docker_compose(modules) as docker_compose_fn: subprocess.run( ["docker-compose", "-f", docker_compose_fn, "up", "-d"], check=True, env=docker_compose_env, ) typer.secho("Creating users in server and client containers", fg=c.GREEN) for container_name in ["server", "client"]: if os.getuid() == 0: continue cmd = _build_docker_cmd(container_name, use_root=True, cwd="/") gid = str(os.getgid()) uid = str(os.getuid()) ret = subprocess.run(cmd + ["groupadd", "--gid", gid, "dirac"], check=False) if ret.returncode != 0: typer.secho(f"Failed to add add group dirac with id={gid}", fg=c.YELLOW) subprocess.run( cmd + [ "useradd", "--uid", uid, "--gid", gid, "-s", "/bin/bash", "-d", "/home/dirac", "dirac", ], check=True, ) subprocess.run(cmd + ["chown", "dirac", "/home/dirac"], check=True) typer.secho("Creating MySQL user", fg=c.GREEN) cmd = ["docker", "exec", "mysql", "mysql", f"--password={DB_ROOTPWD}", "-e"] # It sometimes takes a while for MySQL to be ready so wait for a while if needed for _ in range(10): ret = subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'%' IDENTIFIED BY '{DB_PASSWORD}';"], check=False, ) if ret.returncode == 0: break typer.secho("Failed to connect to MySQL, will retry in 10 seconds", fg=c.YELLOW) time.sleep(10) else: raise Exception(ret) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'localhost' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) subprocess.run( cmd + [f"CREATE USER '{DB_USER}'@'mysql' IDENTIFIED BY '{DB_PASSWORD}';"], check=True, ) typer.secho("Copying files to containers", fg=c.GREEN) for name, config in [("server", server_config), ("client", client_config)]: if path := config.get("DIRACOS_TARBALL_PATH"): path = Path(path) config["DIRACOS_TARBALL_PATH"] = f"/{path.name}" subprocess.run( ["docker", "cp", str(path), f"{name}:/{config['DIRACOS_TARBALL_PATH']}"], check=True, ) config_as_shell = _dict_to_shell(config) typer.secho(f"## {name.title()} config is:", fg=c.BRIGHT_WHITE, bg=c.BLACK) typer.secho(config_as_shell) with tempfile.TemporaryDirectory() as tmpdir: path = Path(tmpdir) / "CONFIG" path.write_text(config_as_shell) subprocess.run( ["docker", "cp", str(path), f"{name}:/home/dirac"], check=True, ) for module_name, module_configs in _load_module_configs(modules).items(): for command in module_configs.get("commands", {}).get("post-prepare", []): typer.secho( f"Running post-prepare command for {module_name}: {command}", err=True, fg=c.GREEN, ) subprocess.run(command, check=True, shell=True) @app.command() def install_server(): """Install DIRAC in the server container.""" _check_containers_running() typer.secho("Running server installation", fg=c.GREEN) base_cmd = _build_docker_cmd("server", tty=False) subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_server.sh"], check=True, ) typer.secho("Copying credentials and certificates", fg=c.GREEN) base_cmd = _build_docker_cmd("client", tty=False) subprocess.run( base_cmd + [ "mkdir", "-p", "/home/dirac/ServerInstallDIR/user", "/home/dirac/ClientInstallDIR/etc", "/home/dirac/.globus", ], check=True, ) for path in [ "etc/grid-security", "user/client.pem", "user/client.key", f"/tmp/x509up_u{os.getuid()}", ]: source = os.path.join("/home/dirac/ServerInstallDIR", path) ret = subprocess.run( ["docker", "cp", f"server:{source}", "-"], check=True, text=False, stdout=subprocess.PIPE, ) if path.startswith("user/"): dest = f"client:/home/dirac/ServerInstallDIR/{os.path.dirname(path)}" elif path.startswith("/"): dest = f"client:{os.path.dirname(path)}" else: dest = f"client:/home/dirac/ClientInstallDIR/{os.path.dirname(path)}" subprocess.run(["docker", "cp", "-", dest], check=True, text=False, input=ret.stdout) subprocess.run( base_cmd + [ "bash", "-c", "cp /home/dirac/ServerInstallDIR/user/client.* /home/dirac/.globus/", ], check=True, ) @app.command() def install_client(): """Install DIRAC in the client container.""" _check_containers_running() typer.secho("Running client installation", fg=c.GREEN) base_cmd = _build_docker_cmd("client") subprocess.run( base_cmd + ["bash", "/home/dirac/LocalRepo/TestCode/DIRAC/tests/CI/install_client.sh"], check=True, ) @app.command() def test_server(): """Run the server integration tests.""" _check_containers_running() typer.secho("Running server tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("server") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Server tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def test_client(): """Run the client integration tests.""" _check_containers_running() typer.secho("Running client tests", err=True, fg=c.GREEN) base_cmd = _build_docker_cmd("client") ret = subprocess.run(base_cmd + ["bash", "TestCode/DIRAC/tests/CI/run_tests.sh"], check=False) color = c.GREEN if ret.returncode == 0 else c.RED typer.secho(f"Client tests finished with {ret.returncode}", err=True, fg=color) raise TestExit(ret.returncode) @app.command() def exec_server(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ServerInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_client(): """Start an interactive session in the client container.""" _check_containers_running() cmd = _build_docker_cmd("client") cmd += [ "bash", "-c", ". $HOME/CONFIG && . $HOME/ClientInstallDIR/bashrc && exec bash", ] typer.secho("Opening prompt inside client container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def exec_mysql(): """Start an interactive session in the server container.""" _check_containers_running() cmd = _build_docker_cmd("mysql", use_root=True, cwd="/") cmd += [ "bash", "-c", f"exec mysql --user={DB_USER} --password={DB_PASSWORD}", ] typer.secho("Opening prompt inside server container", err=True, fg=c.GREEN) os.execvp(cmd[0], cmd) @app.command() def list_services(): """List the services which have been running. Only the services for which /log/current exists are shown. """ _check_containers_running() typer.secho("Known services:", err=True) for service in _list_services()[1]: typer.secho(f"* {service}", err=True) @app.command() def runsvctrl(command: str, pattern: str): """Execute runsvctrl inside the server container.""" _check_containers_running() runit_dir, services = _list_services() cmd = _build_docker_cmd("server", cwd=runit_dir) services = fnmatch.filter(services, pattern) if not services: typer.secho(f"No services match {pattern!r}", fg=c.RED) raise typer.Exit(code=1) cmd += ["runsvctrl", command] + services os.execvp(cmd[0], cmd) @app.command() def logs(pattern: str = "*", lines: int = 10, follow: bool = True): """Show DIRAC's logs from the service container. For services matching [--pattern] show the most recent [--lines] from the logs. If [--follow] is True, continiously stream the logs. """ _check_containers_running() runit_dir, services = _list_services() base_cmd = _build_docker_cmd("server", tty=False) + ["tail"] base_cmd += [f"--lines={lines}"] if follow: base_cmd += ["-f"] with ThreadPoolExecutor(len(services)) as pool: for service in fnmatch.filter(services, pattern): cmd = base_cmd + [f"{runit_dir}/{service}/log/current"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None, text=True) pool.submit(_log_popen_stdout, p) class TestExit(typer.Exit): pass @contextmanager def _gen_docker_compose(modules): # Load the docker-compose configuration and mount the necessary volumes input_fn = Path(__file__).parent / "tests/CI/docker-compose.yml" docker_compose = yaml.safe_load(input_fn.read_text()) volumes = [f"{path}:/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name, path in modules.items()] volumes += [f"{path}:/home/dirac/LocalRepo/TestCode/{name}" for name, path in modules.items()] docker_compose["services"]["dirac-server"]["volumes"] = volumes[:] docker_compose["services"]["dirac-client"]["volumes"] = volumes[:] # Add any extension services for module_name, module_configs in _load_module_configs(modules).items(): for service_name, service_config in module_configs["extra-services"].items(): typer.secho(f"Adding service {service_name} for {module_name}", err=True, fg=c.GREEN) docker_compose["services"][service_name] = service_config.copy() docker_compose["services"][service_name]["volumes"] = volumes[:] # Write to a tempory file with the appropriate profile name prefix = "ci" with tempfile.TemporaryDirectory() as tmpdir: input_docker_compose_dir = Path(__file__).parent / "tests/CI/" output_fn = Path(tmpdir) / prefix / "docker-compose.yml" output_fn.parent.mkdir() output_fn.write_text(yaml.safe_dump(docker_compose, sort_keys=False)) shutil.copytree(input_docker_compose_dir / "envs", str(Path(tmpdir) / prefix), dirs_exist_ok=True) yield output_fn def _check_containers_running(*, is_up=True): with _gen_docker_compose(DEFAULT_MODULES) as docker_compose_fn: running_containers = subprocess.run( ["docker-compose", "-f", docker_compose_fn, "ps", "-q", "-a"], stdout=subprocess.PIPE, env=_make_env({}), check=True, text=True, ).stdout.split("\n") if is_up: if not any(running_containers): typer.secho( f"No running containers found, environment must be prepared first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) else: if any(running_containers): typer.secho( f"Running instance already found, it must be destroyed first!", err=True, fg=c.RED, ) raise typer.Exit(code=1) def _find_dirac_release_and_branch(): # Start by looking for the GitHub/GitLab environment variables ref = os.environ.get("CI_COMMIT_REF_NAME", os.environ.get("GITHUB_REF")) if ref == "refs/heads/integration": return "integration", "" ref = os.environ.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", os.environ.get("GITHUB_BASE_REF")) if ref == "integration": return "integration", "" repo = git.Repo(os.getcwd()) # Try to make sure the upstream remote is up to date try: upstream = repo.remote("upstream") except ValueError: typer.secho("No upstream remote found, adding", err=True, fg=c.YELLOW) upstream = repo.create_remote("upstream", "https://github.com/DIRACGrid/DIRAC.git") try: upstream.fetch() except Exception: typer.secho("Failed to fetch from remote 'upstream'", err=True, fg=c.YELLOW) # Find the most recent tag on the current branch version = Version( repo.git.describe( dirty=True, tags=True, long=True, match="*[0-9]*", exclude=["v[0-9]r*", "v[0-9][0-9]r*"], ).split("-")[0] ) # See if there is a remote branch named "rel-vXrY" version_branch = f"rel-v{version.major}r{version.minor}" try: upstream.refs[version_branch] except IndexError: typer.secho( f"Failed to find branch for {version_branch}, defaulting to integration", err=True, fg=c.YELLOW, ) return "integration", "" else: return "", f"v{version.major}r{version.minor}" def _make_env(flags): env = os.environ.copy() env["DIRAC_UID"] = str(os.getuid()) env["DIRAC_GID"] = str(os.getgid()) env["HOST_OS"] = flags.pop("HOST_OS", DEFAULT_HOST_OS) env["CI_REGISTRY_IMAGE"] = flags.pop("CI_REGISTRY_IMAGE", "diracgrid") env["MYSQL_VER"] = flags.pop("MYSQL_VER", DEFAULT_MYSQL_VER) env["ES_VER"] = flags.pop("ES_VER", DEFAULT_ES_VER) return env def _dict_to_shell(variables): lines = [] for name, value in variables.items(): if value is None: continue elif isinstance(value, list): lines += [f"declare -a {name}"] lines += [f"{name}+=({shlex.quote(v)})" for v in value] elif isinstance(value, bool): lines += [f"export {name}={'Yes' if value else 'No'}"] elif isinstance(value, str): lines += [f"export {name}={shlex.quote(value)}"] else: raise NotImplementedError(name, value, type(value)) return "\n".join(lines) def _make_config(modules, flags, release_var, editable): config = { "DEBUG": "True", # MYSQL Settings "DB_USER": DB_USER, "DB_PASSWORD": DB_PASSWORD, "DB_ROOTUSER": DB_ROOTUSER, "DB_ROOTPWD": DB_ROOTPWD, "DB_HOST": DB_HOST, "DB_PORT": DB_PORT, # ElasticSearch settings "NoSQLDB_HOST": "elasticsearch", "NoSQLDB_PORT": "9200", # Hostnames "SERVER_HOST": "server", "CLIENT_HOST": "client", # Test specific variables "WORKSPACE": "/home/dirac", } if editable: config["PIP_INSTALL_EXTRA_ARGS"] = "-e" required_feature_flags = [] for module_name, module_ci_config in _load_module_configs(modules).items(): config |= module_ci_config["config"] required_feature_flags += module_ci_config.get("required-feature-flags", []) config["DIRAC_CI_SETUP_SCRIPT"] = "/home/dirac/LocalRepo/TestCode/" + config["DIRAC_CI_SETUP_SCRIPT"] # This can likely be removed after the Python 3 migration if release_var: config |= dict([release_var.split("=", 1)]) else: config["DIRAC_RELEASE"], config["DIRACBRANCH"] = _find_dirac_release_and_branch() for key, default_value in FEATURE_VARIABLES.items(): config[key] = flags.pop(key, default_value) for key in required_feature_flags: try: config[key] = flags.pop(key) except KeyError: typer.secho(f"Required feature variable {key!r} is missing", err=True, fg=c.RED) raise typer.Exit(code=1) config["TESTREPO"] = [f"/home/dirac/LocalRepo/TestCode/{name}" for name in modules] config["ALTERNATIVE_MODULES"] = [f"/home/dirac/LocalRepo/ALTERNATIVE_MODULES/{name}" for name in modules] # Exit with an error if there are unused feature flags remaining if flags: typer.secho(f"Unrecognised feature flags {flags!r}", err=True, fg=c.RED) raise typer.Exit(code=1) return config def _load_module_configs(modules): module_ci_configs = {} for module_name, module_path in modules.items(): module_ci_config_path = module_path / "tests/.dirac-ci-config.yaml" if not module_ci_config_path.exists(): continue module_ci_configs[module_name] = yaml.safe_load(module_ci_config_path.read_text()) return module_ci_configs def _build_docker_cmd(container_name, *, use_root=False, cwd="/home/dirac", tty=True): if use_root or os.getuid() == 0: user = "root" else: user = "dirac" cmd = ["docker", "exec"] if tty: if sys.stdout.isatty(): cmd += ["-it"] else: typer.secho( 'Not passing "-it" to docker as stdout is not a tty', err=True, fg=c.YELLOW, ) cmd += [ "-e=TERM=xterm-color", "-e=INSTALLROOT=/home/dirac", f"-e=INSTALLTYPE={container_name}", f"-u={user}", f"-w={cwd}", container_name, ] return cmd def _list_services(): # The Python 3 runit dir ends up in /diracos for runit_dir in ["ServerInstallDIR/runit", "ServerInstallDIR/diracos/runit"]: cmd = _build_docker_cmd("server") cmd += [ "bash", "-c", f'cd {runit_dir}/ && for fn in */*/log/current; do echo "$(dirname "$(dirname "$fn")")"; done', ] ret = subprocess.run(cmd, check=False, stdout=subprocess.PIPE, text=True) if not ret.returncode: return runit_dir, ret.stdout.split() else: typer.secho("Failed to find list of available services", err=True, fg=c.RED) typer.secho(f"stdout was: {ret.stdout!r}", err=True) typer.secho(f"stderr was: {ret.stderr!r}", err=True) raise typer.Exit(1) def _log_popen_stdout(p): while p.poll() is None: line = p.stdout.readline().rstrip() if not line:
bg, fg = None, None if match := LOG_PATTERN.match(line): bg, fg = LOG_LEVEL_MAP.get(match.groups()[0], (bg, fg)) typer.secho(line, err=True, bg=bg, fg=fg) if __name__ == "__main__": app()
continue
conditional_block
sharing.py
import data from utils import assert_403, assert_404, assert_200, parse_xml, xpath PRD = 'prd' def test_sharing(IndivoClient): DS = 'ds' def get_datastore(obj): if hasattr(obj, DS): return getattr(obj, DS).values() return False def set_datastore(obj, **kwargs): if hasattr(obj, DS): ds = getattr(obj, DS) for kwarg, value in kwargs.items(): if hasattr(ds, kwarg): setattr(ds, kwarg, value) return obj raise ValueError def alice_setup(record_id, bob_account_id): allergy_type = {'type' : 'http://indivo.org/vocab/xml/documents#Allergy'} alice_chrome_client = IndivoClient('chrome', 'chrome') alice_chrome_client.create_session(data.account) alice_chrome_client.read_record(record_id=record_id) alice_chrome_client.get_account_permissions(account_id=data.account['account_id']) alice_chrome_client.get_account_records(account_id = data.account['account_id']) # Alice posts a document # (We save the first doc instead of zero # due to the contact doc already in alice's account) alice_chrome_client.post_document(data=data.doc01) document_id = alice_chrome_client.read_documents().response[PRD]['Document'][1] # Save the document_id in the client's datastore alice_chrome_client.ds.document_id = document_id # Save the first carenet_id in the client's datastore carenet_id = alice_chrome_client.get_record_carenets().response[PRD]['Carenet'][0] # post four documents to Alice's record, 2 allergies and 2 immunizations document_1_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy00)), "/Document/@id")[0] document_2_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy01)), "/Document/@id")[0] document_3_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization)), "/Document/@id")[0] document_4_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization2)), "/Document/@id")[0] # and one more to test nevershare document_5_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy02)), "/Document/@id")[0] # auto-share allergies alice_chrome_client.post_autoshare(data=allergy_type, carenet_id=carenet_id) assert_200(alice_chrome_client.get_autoshare_bytype_all(record_id=record_id)) # unshare that one allergy, which should negate the autoshare alice_chrome_client.delete_carenet_document(record_id = record_id, document_id = document_2_id, carenet_id=carenet_id) # nevershare the third allergy alice_chrome_client.document_nevershare_set(record_id = record_id, document_id = document_5_id) # immunizations are individually shared (well only one of them) alice_chrome_client.post_carenet_document(document_id = document_3_id, carenet_id=carenet_id) # Alice shares her contact document(s) with the carenet contact_doc = parse_xml(alice_chrome_client.read_documents(record_id = record_id, parameters={'type':'Contact'})) for doc_id in xpath(contact_doc, '/Documents/Document/@id'): alice_chrome_client.post_carenet_document(record_id = record_id, document_id = doc_id, carenet_id = carenet_id) # Alice adds bob_account_id to carenet[0] alice_chrome_client.post_carenet_account(carenet_id = carenet_id, data='account_id=' + bob_account_id + '&write=false') # Review all accounts within carenet[0] assert xpath(parse_xml(alice_chrome_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts') alice_chrome_client.get_carenet_apps(carenet_id = carenet_id) alice_chrome_client.read_allergies(record_id = record_id) # Finally, return the carenet_id, document_id # in order to check Bob's access # and a second document that is disallowed return carenet_id, [document_1_id, document_3_id], [document_2_id, document_4_id, document_5_id] def bob_setup(bob_account_id, record_id, carenet_id, allowed_docs, disallowed_docs): bob_chrome_client = IndivoClient('chrome', 'chrome') bob_chrome_client.create_session(data.account02) # SZ: Bob should NOT be able to read the docs directly in the record for doc_id in allowed_docs+disallowed_docs: assert_403(bob_chrome_client.read_document(record_id=record_id, document_id=doc_id)) assert_403(bob_chrome_client.get_record_carenets(record_id=record_id)) # Bob should be able to read the allowed docs for doc_id in allowed_docs: assert_200(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should not be able to read the disallowed docs for doc_id in disallowed_docs: assert_404(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should be able to list docs in the carenet carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id).response[PRD]['Document'] # with a parameter carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id, parameters={'type': 'http://indivo.org/vocab/xml/documents#Allergy'}).response[PRD]['Document'] # Read carenet allergies assert_200(bob_chrome_client.read_carenet_allergies(carenet_id = carenet_id)) assert_200(bob_chrome_client.read_carenet_problems(carenet_id = carenet_id)) # Read the contact document, this should work contact_doc = parse_xml(bob_chrome_client.read_carenet_special_document(carenet_id = carenet_id, special_document='contact')) contact_name = xpath(contact_doc, '/ns:Contact/ns:name/ns:fullName/text()', namespaces={'ns':'http://indivo.org/vocab/xml/documents#'}) assert(contact_name) bob_chrome_client.get_account_permissions(account_id=bob_account_id) bob_chrome_client.get_carenet_account_permissions(carenet_id= carenet_id, record_id=record_id, account_id=bob_account_id) # Not yet implemented #bob_chrome_client.get_carenet_app_permissions(account_id=bob_account_id) return True def admin_setup(bob_account_id): admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret) admin_client.set_app_id(data.app_email) # Create a record for Alice and set her at the owner record_id = admin_client.create_record(data=data.contact).response[PRD]['Record'][0] admin_client.set_record_owner(data=data.account['account_id']) # Create a basic set of carenets carenet_names = ['Family2', 'Friends2', 'School/Office'] for cname in carenet_names: admin_client.create_carenet(data='name=' + cname) # Check to make sure the admin can list the carenets and the accounts within each one carenets = xpath(parse_xml(admin_client.get_record_carenets(record_id = record_id)),'/Carenets/Carenet/@id') for carenet_id in carenets: assert len(xpath(parse_xml(admin_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts')) > 0 return record_id bob_account_id = 'benadida@informedcohort.org' # Admin spawning carenets under Alice's newly created record record_id = admin_setup(bob_account_id) # Given Bob's account id and a record that has been set up for her # Alice gives Bob the document_id that she'd like to share with him # Even though Alice gives Bob a document_id, Bob has the ability # to read all documents within the carenet that Alice added him to # 2010-09-13 now Alice also shares her contact URL and we check # that Bob can read it at the special URL carenet_id, allowed_documents, disallowed_documents = alice_setup(record_id, bob_account_id)
return bob_setup(bob_account_id, record_id, carenet_id, allowed_documents, disallowed_documents)
random_line_split
sharing.py
import data from utils import assert_403, assert_404, assert_200, parse_xml, xpath PRD = 'prd' def test_sharing(IndivoClient): DS = 'ds' def get_datastore(obj): if hasattr(obj, DS):
return False def set_datastore(obj, **kwargs): if hasattr(obj, DS): ds = getattr(obj, DS) for kwarg, value in kwargs.items(): if hasattr(ds, kwarg): setattr(ds, kwarg, value) return obj raise ValueError def alice_setup(record_id, bob_account_id): allergy_type = {'type' : 'http://indivo.org/vocab/xml/documents#Allergy'} alice_chrome_client = IndivoClient('chrome', 'chrome') alice_chrome_client.create_session(data.account) alice_chrome_client.read_record(record_id=record_id) alice_chrome_client.get_account_permissions(account_id=data.account['account_id']) alice_chrome_client.get_account_records(account_id = data.account['account_id']) # Alice posts a document # (We save the first doc instead of zero # due to the contact doc already in alice's account) alice_chrome_client.post_document(data=data.doc01) document_id = alice_chrome_client.read_documents().response[PRD]['Document'][1] # Save the document_id in the client's datastore alice_chrome_client.ds.document_id = document_id # Save the first carenet_id in the client's datastore carenet_id = alice_chrome_client.get_record_carenets().response[PRD]['Carenet'][0] # post four documents to Alice's record, 2 allergies and 2 immunizations document_1_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy00)), "/Document/@id")[0] document_2_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy01)), "/Document/@id")[0] document_3_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization)), "/Document/@id")[0] document_4_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization2)), "/Document/@id")[0] # and one more to test nevershare document_5_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy02)), "/Document/@id")[0] # auto-share allergies alice_chrome_client.post_autoshare(data=allergy_type, carenet_id=carenet_id) assert_200(alice_chrome_client.get_autoshare_bytype_all(record_id=record_id)) # unshare that one allergy, which should negate the autoshare alice_chrome_client.delete_carenet_document(record_id = record_id, document_id = document_2_id, carenet_id=carenet_id) # nevershare the third allergy alice_chrome_client.document_nevershare_set(record_id = record_id, document_id = document_5_id) # immunizations are individually shared (well only one of them) alice_chrome_client.post_carenet_document(document_id = document_3_id, carenet_id=carenet_id) # Alice shares her contact document(s) with the carenet contact_doc = parse_xml(alice_chrome_client.read_documents(record_id = record_id, parameters={'type':'Contact'})) for doc_id in xpath(contact_doc, '/Documents/Document/@id'): alice_chrome_client.post_carenet_document(record_id = record_id, document_id = doc_id, carenet_id = carenet_id) # Alice adds bob_account_id to carenet[0] alice_chrome_client.post_carenet_account(carenet_id = carenet_id, data='account_id=' + bob_account_id + '&write=false') # Review all accounts within carenet[0] assert xpath(parse_xml(alice_chrome_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts') alice_chrome_client.get_carenet_apps(carenet_id = carenet_id) alice_chrome_client.read_allergies(record_id = record_id) # Finally, return the carenet_id, document_id # in order to check Bob's access # and a second document that is disallowed return carenet_id, [document_1_id, document_3_id], [document_2_id, document_4_id, document_5_id] def bob_setup(bob_account_id, record_id, carenet_id, allowed_docs, disallowed_docs): bob_chrome_client = IndivoClient('chrome', 'chrome') bob_chrome_client.create_session(data.account02) # SZ: Bob should NOT be able to read the docs directly in the record for doc_id in allowed_docs+disallowed_docs: assert_403(bob_chrome_client.read_document(record_id=record_id, document_id=doc_id)) assert_403(bob_chrome_client.get_record_carenets(record_id=record_id)) # Bob should be able to read the allowed docs for doc_id in allowed_docs: assert_200(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should not be able to read the disallowed docs for doc_id in disallowed_docs: assert_404(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should be able to list docs in the carenet carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id).response[PRD]['Document'] # with a parameter carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id, parameters={'type': 'http://indivo.org/vocab/xml/documents#Allergy'}).response[PRD]['Document'] # Read carenet allergies assert_200(bob_chrome_client.read_carenet_allergies(carenet_id = carenet_id)) assert_200(bob_chrome_client.read_carenet_problems(carenet_id = carenet_id)) # Read the contact document, this should work contact_doc = parse_xml(bob_chrome_client.read_carenet_special_document(carenet_id = carenet_id, special_document='contact')) contact_name = xpath(contact_doc, '/ns:Contact/ns:name/ns:fullName/text()', namespaces={'ns':'http://indivo.org/vocab/xml/documents#'}) assert(contact_name) bob_chrome_client.get_account_permissions(account_id=bob_account_id) bob_chrome_client.get_carenet_account_permissions(carenet_id= carenet_id, record_id=record_id, account_id=bob_account_id) # Not yet implemented #bob_chrome_client.get_carenet_app_permissions(account_id=bob_account_id) return True def admin_setup(bob_account_id): admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret) admin_client.set_app_id(data.app_email) # Create a record for Alice and set her at the owner record_id = admin_client.create_record(data=data.contact).response[PRD]['Record'][0] admin_client.set_record_owner(data=data.account['account_id']) # Create a basic set of carenets carenet_names = ['Family2', 'Friends2', 'School/Office'] for cname in carenet_names: admin_client.create_carenet(data='name=' + cname) # Check to make sure the admin can list the carenets and the accounts within each one carenets = xpath(parse_xml(admin_client.get_record_carenets(record_id = record_id)),'/Carenets/Carenet/@id') for carenet_id in carenets: assert len(xpath(parse_xml(admin_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts')) > 0 return record_id bob_account_id = 'benadida@informedcohort.org' # Admin spawning carenets under Alice's newly created record record_id = admin_setup(bob_account_id) # Given Bob's account id and a record that has been set up for her # Alice gives Bob the document_id that she'd like to share with him # Even though Alice gives Bob a document_id, Bob has the ability # to read all documents within the carenet that Alice added him to # 2010-09-13 now Alice also shares her contact URL and we check # that Bob can read it at the special URL carenet_id, allowed_documents, disallowed_documents = alice_setup(record_id, bob_account_id) return bob_setup(bob_account_id, record_id, carenet_id, allowed_documents, disallowed_documents)
return getattr(obj, DS).values()
conditional_block
sharing.py
import data from utils import assert_403, assert_404, assert_200, parse_xml, xpath PRD = 'prd' def test_sharing(IndivoClient): DS = 'ds' def get_datastore(obj): if hasattr(obj, DS): return getattr(obj, DS).values() return False def set_datastore(obj, **kwargs): if hasattr(obj, DS): ds = getattr(obj, DS) for kwarg, value in kwargs.items(): if hasattr(ds, kwarg): setattr(ds, kwarg, value) return obj raise ValueError def alice_setup(record_id, bob_account_id): allergy_type = {'type' : 'http://indivo.org/vocab/xml/documents#Allergy'} alice_chrome_client = IndivoClient('chrome', 'chrome') alice_chrome_client.create_session(data.account) alice_chrome_client.read_record(record_id=record_id) alice_chrome_client.get_account_permissions(account_id=data.account['account_id']) alice_chrome_client.get_account_records(account_id = data.account['account_id']) # Alice posts a document # (We save the first doc instead of zero # due to the contact doc already in alice's account) alice_chrome_client.post_document(data=data.doc01) document_id = alice_chrome_client.read_documents().response[PRD]['Document'][1] # Save the document_id in the client's datastore alice_chrome_client.ds.document_id = document_id # Save the first carenet_id in the client's datastore carenet_id = alice_chrome_client.get_record_carenets().response[PRD]['Carenet'][0] # post four documents to Alice's record, 2 allergies and 2 immunizations document_1_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy00)), "/Document/@id")[0] document_2_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy01)), "/Document/@id")[0] document_3_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization)), "/Document/@id")[0] document_4_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization2)), "/Document/@id")[0] # and one more to test nevershare document_5_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy02)), "/Document/@id")[0] # auto-share allergies alice_chrome_client.post_autoshare(data=allergy_type, carenet_id=carenet_id) assert_200(alice_chrome_client.get_autoshare_bytype_all(record_id=record_id)) # unshare that one allergy, which should negate the autoshare alice_chrome_client.delete_carenet_document(record_id = record_id, document_id = document_2_id, carenet_id=carenet_id) # nevershare the third allergy alice_chrome_client.document_nevershare_set(record_id = record_id, document_id = document_5_id) # immunizations are individually shared (well only one of them) alice_chrome_client.post_carenet_document(document_id = document_3_id, carenet_id=carenet_id) # Alice shares her contact document(s) with the carenet contact_doc = parse_xml(alice_chrome_client.read_documents(record_id = record_id, parameters={'type':'Contact'})) for doc_id in xpath(contact_doc, '/Documents/Document/@id'): alice_chrome_client.post_carenet_document(record_id = record_id, document_id = doc_id, carenet_id = carenet_id) # Alice adds bob_account_id to carenet[0] alice_chrome_client.post_carenet_account(carenet_id = carenet_id, data='account_id=' + bob_account_id + '&write=false') # Review all accounts within carenet[0] assert xpath(parse_xml(alice_chrome_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts') alice_chrome_client.get_carenet_apps(carenet_id = carenet_id) alice_chrome_client.read_allergies(record_id = record_id) # Finally, return the carenet_id, document_id # in order to check Bob's access # and a second document that is disallowed return carenet_id, [document_1_id, document_3_id], [document_2_id, document_4_id, document_5_id] def bob_setup(bob_account_id, record_id, carenet_id, allowed_docs, disallowed_docs): bob_chrome_client = IndivoClient('chrome', 'chrome') bob_chrome_client.create_session(data.account02) # SZ: Bob should NOT be able to read the docs directly in the record for doc_id in allowed_docs+disallowed_docs: assert_403(bob_chrome_client.read_document(record_id=record_id, document_id=doc_id)) assert_403(bob_chrome_client.get_record_carenets(record_id=record_id)) # Bob should be able to read the allowed docs for doc_id in allowed_docs: assert_200(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should not be able to read the disallowed docs for doc_id in disallowed_docs: assert_404(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should be able to list docs in the carenet carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id).response[PRD]['Document'] # with a parameter carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id, parameters={'type': 'http://indivo.org/vocab/xml/documents#Allergy'}).response[PRD]['Document'] # Read carenet allergies assert_200(bob_chrome_client.read_carenet_allergies(carenet_id = carenet_id)) assert_200(bob_chrome_client.read_carenet_problems(carenet_id = carenet_id)) # Read the contact document, this should work contact_doc = parse_xml(bob_chrome_client.read_carenet_special_document(carenet_id = carenet_id, special_document='contact')) contact_name = xpath(contact_doc, '/ns:Contact/ns:name/ns:fullName/text()', namespaces={'ns':'http://indivo.org/vocab/xml/documents#'}) assert(contact_name) bob_chrome_client.get_account_permissions(account_id=bob_account_id) bob_chrome_client.get_carenet_account_permissions(carenet_id= carenet_id, record_id=record_id, account_id=bob_account_id) # Not yet implemented #bob_chrome_client.get_carenet_app_permissions(account_id=bob_account_id) return True def
(bob_account_id): admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret) admin_client.set_app_id(data.app_email) # Create a record for Alice and set her at the owner record_id = admin_client.create_record(data=data.contact).response[PRD]['Record'][0] admin_client.set_record_owner(data=data.account['account_id']) # Create a basic set of carenets carenet_names = ['Family2', 'Friends2', 'School/Office'] for cname in carenet_names: admin_client.create_carenet(data='name=' + cname) # Check to make sure the admin can list the carenets and the accounts within each one carenets = xpath(parse_xml(admin_client.get_record_carenets(record_id = record_id)),'/Carenets/Carenet/@id') for carenet_id in carenets: assert len(xpath(parse_xml(admin_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts')) > 0 return record_id bob_account_id = 'benadida@informedcohort.org' # Admin spawning carenets under Alice's newly created record record_id = admin_setup(bob_account_id) # Given Bob's account id and a record that has been set up for her # Alice gives Bob the document_id that she'd like to share with him # Even though Alice gives Bob a document_id, Bob has the ability # to read all documents within the carenet that Alice added him to # 2010-09-13 now Alice also shares her contact URL and we check # that Bob can read it at the special URL carenet_id, allowed_documents, disallowed_documents = alice_setup(record_id, bob_account_id) return bob_setup(bob_account_id, record_id, carenet_id, allowed_documents, disallowed_documents)
admin_setup
identifier_name
sharing.py
import data from utils import assert_403, assert_404, assert_200, parse_xml, xpath PRD = 'prd' def test_sharing(IndivoClient): DS = 'ds' def get_datastore(obj): if hasattr(obj, DS): return getattr(obj, DS).values() return False def set_datastore(obj, **kwargs):
def alice_setup(record_id, bob_account_id): allergy_type = {'type' : 'http://indivo.org/vocab/xml/documents#Allergy'} alice_chrome_client = IndivoClient('chrome', 'chrome') alice_chrome_client.create_session(data.account) alice_chrome_client.read_record(record_id=record_id) alice_chrome_client.get_account_permissions(account_id=data.account['account_id']) alice_chrome_client.get_account_records(account_id = data.account['account_id']) # Alice posts a document # (We save the first doc instead of zero # due to the contact doc already in alice's account) alice_chrome_client.post_document(data=data.doc01) document_id = alice_chrome_client.read_documents().response[PRD]['Document'][1] # Save the document_id in the client's datastore alice_chrome_client.ds.document_id = document_id # Save the first carenet_id in the client's datastore carenet_id = alice_chrome_client.get_record_carenets().response[PRD]['Carenet'][0] # post four documents to Alice's record, 2 allergies and 2 immunizations document_1_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy00)), "/Document/@id")[0] document_2_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy01)), "/Document/@id")[0] document_3_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization)), "/Document/@id")[0] document_4_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.immunization2)), "/Document/@id")[0] # and one more to test nevershare document_5_id = xpath(parse_xml(alice_chrome_client.post_document(data=data.allergy02)), "/Document/@id")[0] # auto-share allergies alice_chrome_client.post_autoshare(data=allergy_type, carenet_id=carenet_id) assert_200(alice_chrome_client.get_autoshare_bytype_all(record_id=record_id)) # unshare that one allergy, which should negate the autoshare alice_chrome_client.delete_carenet_document(record_id = record_id, document_id = document_2_id, carenet_id=carenet_id) # nevershare the third allergy alice_chrome_client.document_nevershare_set(record_id = record_id, document_id = document_5_id) # immunizations are individually shared (well only one of them) alice_chrome_client.post_carenet_document(document_id = document_3_id, carenet_id=carenet_id) # Alice shares her contact document(s) with the carenet contact_doc = parse_xml(alice_chrome_client.read_documents(record_id = record_id, parameters={'type':'Contact'})) for doc_id in xpath(contact_doc, '/Documents/Document/@id'): alice_chrome_client.post_carenet_document(record_id = record_id, document_id = doc_id, carenet_id = carenet_id) # Alice adds bob_account_id to carenet[0] alice_chrome_client.post_carenet_account(carenet_id = carenet_id, data='account_id=' + bob_account_id + '&write=false') # Review all accounts within carenet[0] assert xpath(parse_xml(alice_chrome_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts') alice_chrome_client.get_carenet_apps(carenet_id = carenet_id) alice_chrome_client.read_allergies(record_id = record_id) # Finally, return the carenet_id, document_id # in order to check Bob's access # and a second document that is disallowed return carenet_id, [document_1_id, document_3_id], [document_2_id, document_4_id, document_5_id] def bob_setup(bob_account_id, record_id, carenet_id, allowed_docs, disallowed_docs): bob_chrome_client = IndivoClient('chrome', 'chrome') bob_chrome_client.create_session(data.account02) # SZ: Bob should NOT be able to read the docs directly in the record for doc_id in allowed_docs+disallowed_docs: assert_403(bob_chrome_client.read_document(record_id=record_id, document_id=doc_id)) assert_403(bob_chrome_client.get_record_carenets(record_id=record_id)) # Bob should be able to read the allowed docs for doc_id in allowed_docs: assert_200(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should not be able to read the disallowed docs for doc_id in disallowed_docs: assert_404(bob_chrome_client.get_carenet_document(carenet_id = carenet_id, document_id = doc_id)) # Bob should be able to list docs in the carenet carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id).response[PRD]['Document'] # with a parameter carenet_documents_list = bob_chrome_client.get_carenet_documents(carenet_id = carenet_id, parameters={'type': 'http://indivo.org/vocab/xml/documents#Allergy'}).response[PRD]['Document'] # Read carenet allergies assert_200(bob_chrome_client.read_carenet_allergies(carenet_id = carenet_id)) assert_200(bob_chrome_client.read_carenet_problems(carenet_id = carenet_id)) # Read the contact document, this should work contact_doc = parse_xml(bob_chrome_client.read_carenet_special_document(carenet_id = carenet_id, special_document='contact')) contact_name = xpath(contact_doc, '/ns:Contact/ns:name/ns:fullName/text()', namespaces={'ns':'http://indivo.org/vocab/xml/documents#'}) assert(contact_name) bob_chrome_client.get_account_permissions(account_id=bob_account_id) bob_chrome_client.get_carenet_account_permissions(carenet_id= carenet_id, record_id=record_id, account_id=bob_account_id) # Not yet implemented #bob_chrome_client.get_carenet_app_permissions(account_id=bob_account_id) return True def admin_setup(bob_account_id): admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret) admin_client.set_app_id(data.app_email) # Create a record for Alice and set her at the owner record_id = admin_client.create_record(data=data.contact).response[PRD]['Record'][0] admin_client.set_record_owner(data=data.account['account_id']) # Create a basic set of carenets carenet_names = ['Family2', 'Friends2', 'School/Office'] for cname in carenet_names: admin_client.create_carenet(data='name=' + cname) # Check to make sure the admin can list the carenets and the accounts within each one carenets = xpath(parse_xml(admin_client.get_record_carenets(record_id = record_id)),'/Carenets/Carenet/@id') for carenet_id in carenets: assert len(xpath(parse_xml(admin_client.get_carenet_accounts(carenet_id = carenet_id)), '/CarenetAccounts')) > 0 return record_id bob_account_id = 'benadida@informedcohort.org' # Admin spawning carenets under Alice's newly created record record_id = admin_setup(bob_account_id) # Given Bob's account id and a record that has been set up for her # Alice gives Bob the document_id that she'd like to share with him # Even though Alice gives Bob a document_id, Bob has the ability # to read all documents within the carenet that Alice added him to # 2010-09-13 now Alice also shares her contact URL and we check # that Bob can read it at the special URL carenet_id, allowed_documents, disallowed_documents = alice_setup(record_id, bob_account_id) return bob_setup(bob_account_id, record_id, carenet_id, allowed_documents, disallowed_documents)
if hasattr(obj, DS): ds = getattr(obj, DS) for kwarg, value in kwargs.items(): if hasattr(ds, kwarg): setattr(ds, kwarg, value) return obj raise ValueError
identifier_body
angular-locale_ha-latn-ng.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n)
function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Lahadi", "Litinin", "Talata", "Laraba", "Alhamis", "Jumma\u02bca", "Asabar" ], "MONTH": [ "Janairu", "Faburairu", "Maris", "Afirilu", "Mayu", "Yuni", "Yuli", "Agusta", "Satumba", "Oktoba", "Nuwamba", "Disamba" ], "SHORTDAY": [ "Lh", "Li", "Ta", "Lr", "Al", "Ju", "As" ], "SHORTMONTH": [ "Jan", "Fab", "Mar", "Afi", "May", "Yun", "Yul", "Agu", "Sat", "Okt", "Nuw", "Dis" ], "fullDate": "EEEE, d MMMM, y", "longDate": "d MMMM, y", "medium": "d MMM, y HH:mm:ss", "mediumDate": "d MMM, y", "mediumTime": "HH:mm:ss", "short": "d/M/yy HH:mm", "shortDate": "d/M/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20a6", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "ha-latn-ng", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; }
identifier_body
angular-locale_ha-latn-ng.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Lahadi", "Litinin", "Talata", "Laraba", "Alhamis", "Jumma\u02bca", "Asabar" ], "MONTH": [ "Janairu", "Faburairu", "Maris", "Afirilu", "Mayu", "Yuni", "Yuli", "Agusta", "Satumba", "Oktoba", "Nuwamba", "Disamba" ], "SHORTDAY": [ "Lh", "Li", "Ta", "Lr", "Al", "Ju", "As" ], "SHORTMONTH": [ "Jan", "Fab", "Mar", "Afi", "May", "Yun",
"Agu", "Sat", "Okt", "Nuw", "Dis" ], "fullDate": "EEEE, d MMMM, y", "longDate": "d MMMM, y", "medium": "d MMM, y HH:mm:ss", "mediumDate": "d MMM, y", "mediumTime": "HH:mm:ss", "short": "d/M/yy HH:mm", "shortDate": "d/M/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20a6", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "ha-latn-ng", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
"Yul",
random_line_split
angular-locale_ha-latn-ng.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Lahadi", "Litinin", "Talata", "Laraba", "Alhamis", "Jumma\u02bca", "Asabar" ], "MONTH": [ "Janairu", "Faburairu", "Maris", "Afirilu", "Mayu", "Yuni", "Yuli", "Agusta", "Satumba", "Oktoba", "Nuwamba", "Disamba" ], "SHORTDAY": [ "Lh", "Li", "Ta", "Lr", "Al", "Ju", "As" ], "SHORTMONTH": [ "Jan", "Fab", "Mar", "Afi", "May", "Yun", "Yul", "Agu", "Sat", "Okt", "Nuw", "Dis" ], "fullDate": "EEEE, d MMMM, y", "longDate": "d MMMM, y", "medium": "d MMM, y HH:mm:ss", "mediumDate": "d MMM, y", "mediumTime": "HH:mm:ss", "short": "d/M/yy HH:mm", "shortDate": "d/M/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20a6", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "ha-latn-ng", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0)
return PLURAL_CATEGORY.OTHER;} }); }]);
{ return PLURAL_CATEGORY.ONE; }
conditional_block
angular-locale_ha-latn-ng.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function
(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Lahadi", "Litinin", "Talata", "Laraba", "Alhamis", "Jumma\u02bca", "Asabar" ], "MONTH": [ "Janairu", "Faburairu", "Maris", "Afirilu", "Mayu", "Yuni", "Yuli", "Agusta", "Satumba", "Oktoba", "Nuwamba", "Disamba" ], "SHORTDAY": [ "Lh", "Li", "Ta", "Lr", "Al", "Ju", "As" ], "SHORTMONTH": [ "Jan", "Fab", "Mar", "Afi", "May", "Yun", "Yul", "Agu", "Sat", "Okt", "Nuw", "Dis" ], "fullDate": "EEEE, d MMMM, y", "longDate": "d MMMM, y", "medium": "d MMM, y HH:mm:ss", "mediumDate": "d MMM, y", "mediumTime": "HH:mm:ss", "short": "d/M/yy HH:mm", "shortDate": "d/M/yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20a6", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4\u00a0-", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "ha-latn-ng", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
getVF
identifier_name
initialize-storage.ts
import type { Document } from './dom/Document'; import type { DocumentStub } from './dom/DocumentStub'; import { createStorage } from './Storage'; import { StorageLocation } from '../transfer/TransferrableStorage'; type InitStorageMap = { storage: { [key: string]: string }; errorMsg: null }; type InitStorageError = { storage: null; errorMsg: string }; export type WorkerStorageInit = InitStorageMap | InitStorageError; export function initializeStorage(document: Document | DocumentStub, localStorageInit: WorkerStorageInit, sessionStorageInit: WorkerStorageInit) { const window = document.defaultView; if (localStorageInit.storage)
else { console.warn(localStorageInit.errorMsg); } if (sessionStorageInit.storage) { window.sessionStorage = createStorage(document, StorageLocation.Session, sessionStorageInit.storage); } else { console.warn(sessionStorageInit.errorMsg); } }
{ window.localStorage = createStorage(document, StorageLocation.Local, localStorageInit.storage); }
conditional_block
initialize-storage.ts
import type { Document } from './dom/Document'; import type { DocumentStub } from './dom/DocumentStub'; import { createStorage } from './Storage'; import { StorageLocation } from '../transfer/TransferrableStorage'; type InitStorageMap = { storage: { [key: string]: string }; errorMsg: null }; type InitStorageError = { storage: null; errorMsg: string }; export type WorkerStorageInit = InitStorageMap | InitStorageError; export function initializeStorage(document: Document | DocumentStub, localStorageInit: WorkerStorageInit, sessionStorageInit: WorkerStorageInit)
{ const window = document.defaultView; if (localStorageInit.storage) { window.localStorage = createStorage(document, StorageLocation.Local, localStorageInit.storage); } else { console.warn(localStorageInit.errorMsg); } if (sessionStorageInit.storage) { window.sessionStorage = createStorage(document, StorageLocation.Session, sessionStorageInit.storage); } else { console.warn(sessionStorageInit.errorMsg); } }
identifier_body
initialize-storage.ts
import type { Document } from './dom/Document'; import type { DocumentStub } from './dom/DocumentStub'; import { createStorage } from './Storage'; import { StorageLocation } from '../transfer/TransferrableStorage'; type InitStorageMap = { storage: { [key: string]: string }; errorMsg: null }; type InitStorageError = { storage: null; errorMsg: string }; export type WorkerStorageInit = InitStorageMap | InitStorageError; export function
(document: Document | DocumentStub, localStorageInit: WorkerStorageInit, sessionStorageInit: WorkerStorageInit) { const window = document.defaultView; if (localStorageInit.storage) { window.localStorage = createStorage(document, StorageLocation.Local, localStorageInit.storage); } else { console.warn(localStorageInit.errorMsg); } if (sessionStorageInit.storage) { window.sessionStorage = createStorage(document, StorageLocation.Session, sessionStorageInit.storage); } else { console.warn(sessionStorageInit.errorMsg); } }
initializeStorage
identifier_name
initialize-storage.ts
import type { Document } from './dom/Document'; import type { DocumentStub } from './dom/DocumentStub'; import { createStorage } from './Storage'; import { StorageLocation } from '../transfer/TransferrableStorage'; type InitStorageMap = { storage: { [key: string]: string }; errorMsg: null }; type InitStorageError = { storage: null; errorMsg: string }; export type WorkerStorageInit = InitStorageMap | InitStorageError; export function initializeStorage(document: Document | DocumentStub, localStorageInit: WorkerStorageInit, sessionStorageInit: WorkerStorageInit) { const window = document.defaultView;
if (localStorageInit.storage) { window.localStorage = createStorage(document, StorageLocation.Local, localStorageInit.storage); } else { console.warn(localStorageInit.errorMsg); } if (sessionStorageInit.storage) { window.sessionStorage = createStorage(document, StorageLocation.Session, sessionStorageInit.storage); } else { console.warn(sessionStorageInit.errorMsg); } }
random_line_split
gallery.js
/* * @Author: justinwebb * @Date: 2015-09-24 21:08:23 * @Last Modified by: justinwebb * @Last Modified time: 2015-09-24 22:19:45 */ (function (window) { 'use strict';
window.JWLB.View = window.JWLB.View || {}; //-------------------------------------------------------------------- // Event handling //-------------------------------------------------------------------- var wallOnClick = function (event) { if (event.target.tagName.toLowerCase() === 'img') { var id = event.target.parentNode.dataset.id; var selectedPhoto = this.photos.filter(function (photo) { if (photo.id === id) { photo.portrait.id = id; return photo; } })[0]; this.sendEvent('gallery', selectedPhoto.portrait); } }; //-------------------------------------------------------------------- // View overrides //-------------------------------------------------------------------- var addUIListeners = function () { this.ui.wall.addEventListener('click', wallOnClick.bind(this)); }; var initUI = function () { var isUIValid = false; var comp = document.querySelector(this.selector); this.ui.wall = comp; if (this.ui.wall) { this.reset(); isUIValid = true; } return isUIValid; }; //-------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------- var Gallery = function (domId) { // Overriden View class methods this.initUI = initUI; this.addUIListeners = addUIListeners; this.name = 'Gallery'; // Instance properties this.photos = []; // Initialize View JWLB.View.call(this, domId); }; //-------------------------------------------------------------------- // Inheritance //-------------------------------------------------------------------- Gallery.prototype = Object.create(JWLB.View.prototype); Gallery.prototype.constructor = Gallery; //-------------------------------------------------------------------- // Instance methods //-------------------------------------------------------------------- Gallery.prototype.addThumb = function (data, id) { // Store image data for future reference var photo = { id: id, thumb: null, portrait: data.size[0] }; data.size.forEach(function (elem) { if (elem.label === 'Square') { photo.thumb = elem; } if (elem.height > photo.portrait.height) { photo.portrait = elem; } }); this.photos.push(photo); // Build thumbnail UI var node = document.createElement('div'); node.setAttribute('data-id', id); node.setAttribute('class', 'thumb'); var img = document.createElement('img'); img.setAttribute('src', photo.thumb.source); img.setAttribute('title', 'id: '+ id); node.appendChild(img); this.ui.wall.querySelector('article[name=foobar]').appendChild(node); }; Gallery.prototype.reset = function () { if (this.ui.wall.children.length > 0) { var article = this.ui.wall.children.item(0) article.parentElement.removeChild(article); } var article = document.createElement('article'); article.setAttribute('name', 'foobar'); this.ui.wall.appendChild(article); }; window.JWLB.View.Gallery = Gallery; })(window);
window.JWLB = window.JWLB || {};
random_line_split
gallery.js
/* * @Author: justinwebb * @Date: 2015-09-24 21:08:23 * @Last Modified by: justinwebb * @Last Modified time: 2015-09-24 22:19:45 */ (function (window) { 'use strict'; window.JWLB = window.JWLB || {}; window.JWLB.View = window.JWLB.View || {}; //-------------------------------------------------------------------- // Event handling //-------------------------------------------------------------------- var wallOnClick = function (event) { if (event.target.tagName.toLowerCase() === 'img') { var id = event.target.parentNode.dataset.id; var selectedPhoto = this.photos.filter(function (photo) { if (photo.id === id) { photo.portrait.id = id; return photo; } })[0]; this.sendEvent('gallery', selectedPhoto.portrait); } }; //-------------------------------------------------------------------- // View overrides //-------------------------------------------------------------------- var addUIListeners = function () { this.ui.wall.addEventListener('click', wallOnClick.bind(this)); }; var initUI = function () { var isUIValid = false; var comp = document.querySelector(this.selector); this.ui.wall = comp; if (this.ui.wall) { this.reset(); isUIValid = true; } return isUIValid; }; //-------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------- var Gallery = function (domId) { // Overriden View class methods this.initUI = initUI; this.addUIListeners = addUIListeners; this.name = 'Gallery'; // Instance properties this.photos = []; // Initialize View JWLB.View.call(this, domId); }; //-------------------------------------------------------------------- // Inheritance //-------------------------------------------------------------------- Gallery.prototype = Object.create(JWLB.View.prototype); Gallery.prototype.constructor = Gallery; //-------------------------------------------------------------------- // Instance methods //-------------------------------------------------------------------- Gallery.prototype.addThumb = function (data, id) { // Store image data for future reference var photo = { id: id, thumb: null, portrait: data.size[0] }; data.size.forEach(function (elem) { if (elem.label === 'Square') { photo.thumb = elem; } if (elem.height > photo.portrait.height)
}); this.photos.push(photo); // Build thumbnail UI var node = document.createElement('div'); node.setAttribute('data-id', id); node.setAttribute('class', 'thumb'); var img = document.createElement('img'); img.setAttribute('src', photo.thumb.source); img.setAttribute('title', 'id: '+ id); node.appendChild(img); this.ui.wall.querySelector('article[name=foobar]').appendChild(node); }; Gallery.prototype.reset = function () { if (this.ui.wall.children.length > 0) { var article = this.ui.wall.children.item(0) article.parentElement.removeChild(article); } var article = document.createElement('article'); article.setAttribute('name', 'foobar'); this.ui.wall.appendChild(article); }; window.JWLB.View.Gallery = Gallery; })(window);
{ photo.portrait = elem; }
conditional_block
primitive.components.ts
import { Directive, Input, forwardRef } from '@angular/core' import { AnimationConfig } from './interfaces/animation.interface' import * as THREE from 'three' export abstract class PrimitiveComponent { @Input() textureUrl?: string @Input() wSegments: number = 256 @Input() hSegments: number = 256 @Input() position: THREE.Vector3 = new THREE.Vector3() @Input() animConfig: AnimationConfig abstract get object(): THREE.Mesh } @Directive({ selector: 'three-sphere', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => SphereComponent) }] }) export class SphereComponent extends PrimitiveComponent { @Input() sphereSize: number = 20 private _object: THREE.Mesh get object(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj} ngOnInit() { let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) let material: THREE.Material if (this.textureUrl) { material = new THREE.MeshLambertMaterial( { map: texture } ) } else { material = new THREE.MeshNormalMaterial() } // Creating a sphere and giving the geometry a name let geometry = new THREE.SphereGeometry(this.sphereSize, this.wSegments, this.hSegments) geometry.name = 'Sphere' let sphere = new THREE.Mesh(geometry, material) sphere.position.set(this.position[0], this.position[1], this.position[2]) this.object = sphere } } @Directive({ selector: 'three-plane', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => PlaneComponent) }] }) export class PlaneComponent extends PrimitiveComponent { @Input() width: number = 1000 @Input() height: number = 1000 private _object: THREE.Mesh get
(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj} ngOnInit() { let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) texture.wrapS = texture.wrapT = THREE.RepeatWrapping texture.repeat.set( 2, 2 ) let material: THREE.Material if (this.textureUrl) { material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide } ) } else { material = new THREE.MeshNormalMaterial() } // Create a plane and giving the geometry a name let geometry = new THREE.PlaneGeometry(this.width, this.height, this.wSegments, this.hSegments) geometry.name = 'Plane' let plane = new THREE.Mesh(geometry, material) plane.position.y = -0.5 //floor.rotation.x = Math.PI / 2 this.object = plane } }
object
identifier_name
primitive.components.ts
import { Directive, Input, forwardRef } from '@angular/core' import { AnimationConfig } from './interfaces/animation.interface' import * as THREE from 'three' export abstract class PrimitiveComponent { @Input() textureUrl?: string @Input() wSegments: number = 256 @Input() hSegments: number = 256 @Input() position: THREE.Vector3 = new THREE.Vector3() @Input() animConfig: AnimationConfig abstract get object(): THREE.Mesh } @Directive({ selector: 'three-sphere', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => SphereComponent) }] }) export class SphereComponent extends PrimitiveComponent { @Input() sphereSize: number = 20 private _object: THREE.Mesh get object(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj}
let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) let material: THREE.Material if (this.textureUrl) { material = new THREE.MeshLambertMaterial( { map: texture } ) } else { material = new THREE.MeshNormalMaterial() } // Creating a sphere and giving the geometry a name let geometry = new THREE.SphereGeometry(this.sphereSize, this.wSegments, this.hSegments) geometry.name = 'Sphere' let sphere = new THREE.Mesh(geometry, material) sphere.position.set(this.position[0], this.position[1], this.position[2]) this.object = sphere } } @Directive({ selector: 'three-plane', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => PlaneComponent) }] }) export class PlaneComponent extends PrimitiveComponent { @Input() width: number = 1000 @Input() height: number = 1000 private _object: THREE.Mesh get object(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj} ngOnInit() { let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) texture.wrapS = texture.wrapT = THREE.RepeatWrapping texture.repeat.set( 2, 2 ) let material: THREE.Material if (this.textureUrl) { material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide } ) } else { material = new THREE.MeshNormalMaterial() } // Create a plane and giving the geometry a name let geometry = new THREE.PlaneGeometry(this.width, this.height, this.wSegments, this.hSegments) geometry.name = 'Plane' let plane = new THREE.Mesh(geometry, material) plane.position.y = -0.5 //floor.rotation.x = Math.PI / 2 this.object = plane } }
ngOnInit() {
random_line_split
primitive.components.ts
import { Directive, Input, forwardRef } from '@angular/core' import { AnimationConfig } from './interfaces/animation.interface' import * as THREE from 'three' export abstract class PrimitiveComponent { @Input() textureUrl?: string @Input() wSegments: number = 256 @Input() hSegments: number = 256 @Input() position: THREE.Vector3 = new THREE.Vector3() @Input() animConfig: AnimationConfig abstract get object(): THREE.Mesh } @Directive({ selector: 'three-sphere', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => SphereComponent) }] }) export class SphereComponent extends PrimitiveComponent { @Input() sphereSize: number = 20 private _object: THREE.Mesh get object(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj} ngOnInit() { let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) let material: THREE.Material if (this.textureUrl) { material = new THREE.MeshLambertMaterial( { map: texture } ) } else { material = new THREE.MeshNormalMaterial() } // Creating a sphere and giving the geometry a name let geometry = new THREE.SphereGeometry(this.sphereSize, this.wSegments, this.hSegments) geometry.name = 'Sphere' let sphere = new THREE.Mesh(geometry, material) sphere.position.set(this.position[0], this.position[1], this.position[2]) this.object = sphere } } @Directive({ selector: 'three-plane', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => PlaneComponent) }] }) export class PlaneComponent extends PrimitiveComponent { @Input() width: number = 1000 @Input() height: number = 1000 private _object: THREE.Mesh get object(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj} ngOnInit() { let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) texture.wrapS = texture.wrapT = THREE.RepeatWrapping texture.repeat.set( 2, 2 ) let material: THREE.Material if (this.textureUrl)
else { material = new THREE.MeshNormalMaterial() } // Create a plane and giving the geometry a name let geometry = new THREE.PlaneGeometry(this.width, this.height, this.wSegments, this.hSegments) geometry.name = 'Plane' let plane = new THREE.Mesh(geometry, material) plane.position.y = -0.5 //floor.rotation.x = Math.PI / 2 this.object = plane } }
{ material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide } ) }
conditional_block
primitive.components.ts
import { Directive, Input, forwardRef } from '@angular/core' import { AnimationConfig } from './interfaces/animation.interface' import * as THREE from 'three' export abstract class PrimitiveComponent { @Input() textureUrl?: string @Input() wSegments: number = 256 @Input() hSegments: number = 256 @Input() position: THREE.Vector3 = new THREE.Vector3() @Input() animConfig: AnimationConfig abstract get object(): THREE.Mesh } @Directive({ selector: 'three-sphere', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => SphereComponent) }] }) export class SphereComponent extends PrimitiveComponent { @Input() sphereSize: number = 20 private _object: THREE.Mesh get object(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj} ngOnInit()
} @Directive({ selector: 'three-plane', providers: [{provide: PrimitiveComponent, useExisting: forwardRef(() => PlaneComponent) }] }) export class PlaneComponent extends PrimitiveComponent { @Input() width: number = 1000 @Input() height: number = 1000 private _object: THREE.Mesh get object(): THREE.Mesh {return this._object} set object(obj: THREE.Mesh) {this._object = obj} ngOnInit() { let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) texture.wrapS = texture.wrapT = THREE.RepeatWrapping texture.repeat.set( 2, 2 ) let material: THREE.Material if (this.textureUrl) { material = new THREE.MeshBasicMaterial( { map: texture, side: THREE.DoubleSide } ) } else { material = new THREE.MeshNormalMaterial() } // Create a plane and giving the geometry a name let geometry = new THREE.PlaneGeometry(this.width, this.height, this.wSegments, this.hSegments) geometry.name = 'Plane' let plane = new THREE.Mesh(geometry, material) plane.position.y = -0.5 //floor.rotation.x = Math.PI / 2 this.object = plane } }
{ let loader = new THREE.TextureLoader() let texture = loader.load( this.textureUrl ) let material: THREE.Material if (this.textureUrl) { material = new THREE.MeshLambertMaterial( { map: texture } ) } else { material = new THREE.MeshNormalMaterial() } // Creating a sphere and giving the geometry a name let geometry = new THREE.SphereGeometry(this.sphereSize, this.wSegments, this.hSegments) geometry.name = 'Sphere' let sphere = new THREE.Mesh(geometry, material) sphere.position.set(this.position[0], this.position[1], this.position[2]) this.object = sphere }
identifier_body
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ import argparse import io import itertools import json import os import re from collections import Counter from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { r".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 r".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 r".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 r".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 r".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def
(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( r"pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir: if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file) # go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(data, group, sort_by): """ Group and sort data. Return List of tuples. Each tuple has: - Group key - Iterable of warnings that belongs to that group - Count of warnings that belong to that group """ sorted_data = sorted(data, key=lambda x: x[columns.index(group)]) groups_by = itertools.groupby(sorted_data, lambda x: x[columns_index_dict[group]]) temp_list_to_sort = [] for key, generator in groups_by: value = list(generator) temp_list_to_sort.append((key, value, sum([item[columns_index_dict[sort_by]] for item in value]))) # sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def write_html_report(warnings_data, html_path): """ converts from list of lists data to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_data, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for warning in message_group: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning[columns_index_dict["filename"]] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning[columns_index_dict["lineno"]] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning[columns_index_dict["num"]] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section() if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) write_html_report(data_output, args.html_path)
convert_warning_dict_to_list
identifier_name
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ import argparse import io import itertools import json import os import re from collections import Counter from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { r".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 r".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 r".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 r".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 r".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def convert_warning_dict_to_list(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( r"pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir: if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file) # go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(data, group, sort_by): """ Group and sort data. Return List of tuples. Each tuple has: - Group key - Iterable of warnings that belongs to that group - Count of warnings that belong to that group """ sorted_data = sorted(data, key=lambda x: x[columns.index(group)]) groups_by = itertools.groupby(sorted_data, lambda x: x[columns_index_dict[group]])
for key, generator in groups_by: value = list(generator) temp_list_to_sort.append((key, value, sum([item[columns_index_dict[sort_by]] for item in value]))) # sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def write_html_report(warnings_data, html_path): """ converts from list of lists data to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_data, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for warning in message_group: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning[columns_index_dict["filename"]] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning[columns_index_dict["lineno"]] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning[columns_index_dict["num"]] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section() if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) write_html_report(data_output, args.html_path)
temp_list_to_sort = []
random_line_split
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ import argparse import io import itertools import json import os import re from collections import Counter from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { r".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 r".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 r".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 r".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 r".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def convert_warning_dict_to_list(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( r"pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir: if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file) # go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(data, group, sort_by): """ Group and sort data. Return List of tuples. Each tuple has: - Group key - Iterable of warnings that belongs to that group - Count of warnings that belong to that group """ sorted_data = sorted(data, key=lambda x: x[columns.index(group)]) groups_by = itertools.groupby(sorted_data, lambda x: x[columns_index_dict[group]]) temp_list_to_sort = [] for key, generator in groups_by: value = list(generator) temp_list_to_sort.append((key, value, sum([item[columns_index_dict[sort_by]] for item in value]))) # sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def write_html_report(warnings_data, html_path):
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) write_html_report(data_output, args.html_path)
""" converts from list of lists data to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_data, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for warning in message_group: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning[columns_index_dict["filename"]] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning[columns_index_dict["lineno"]] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning[columns_index_dict["num"]] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section()
identifier_body
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ import argparse import io import itertools import json import os import re from collections import Counter from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { r".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 r".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 r".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 r".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 r".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def convert_warning_dict_to_list(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( r"pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir: if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file) # go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(data, group, sort_by): """ Group and sort data. Return List of tuples. Each tuple has: - Group key - Iterable of warnings that belongs to that group - Count of warnings that belong to that group """ sorted_data = sorted(data, key=lambda x: x[columns.index(group)]) groups_by = itertools.groupby(sorted_data, lambda x: x[columns_index_dict[group]]) temp_list_to_sort = [] for key, generator in groups_by:
# sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def write_html_report(warnings_data, html_path): """ converts from list of lists data to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_data, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for warning in message_group: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning[columns_index_dict["filename"]] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning[columns_index_dict["lineno"]] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning[columns_index_dict["num"]] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section() if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) write_html_report(data_output, args.html_path)
value = list(generator) temp_list_to_sort.append((key, value, sum([item[columns_index_dict[sort_by]] for item in value])))
conditional_block
MenuOpenRounded.js
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon';
, 'MenuOpenRounded');
export default createSvgIcon( <path d="M4 18h11c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm0-5h8c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zM3 7c0 .55.45 1 1 1h11c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1zm17.3 7.88L17.42 12l2.88-2.88c.39-.39.39-1.02 0-1.41a.9959.9959 0 00-1.41 0L15.3 11.3c-.39.39-.39 1.02 0 1.41l3.59 3.59c.39.39 1.02.39 1.41 0 .38-.39.39-1.03 0-1.42z" />
random_line_split
serviceworkercontainer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::error::Error; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use dom::bindings::str::USVString;
use dom::client::Client; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom::serviceworker::ServiceWorker; use dom_struct::dom_struct; use script_thread::ScriptThread; use serviceworkerjob::{Job, JobType}; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::default::Default; use std::rc::Rc; #[dom_struct] pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableDom<ServiceWorker>, client: Dom<Client> } impl ServiceWorkerContainer { fn new_inherited(client: &Client) -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Default::default(), client: Dom::from_ref(client), } } #[allow(unrooted_must_root)] pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> { let client = Client::new(&global.as_window()); let container = ServiceWorkerContainer::new_inherited(&*client); reflect_dom_object(Box::new(container), global, Wrap) } } impl ServiceWorkerContainerMethods for ServiceWorkerContainer { // https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute fn GetController(&self) -> Option<DomRoot<ServiceWorker>> { self.client.get_controller() } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A // https://w3c.github.io/ServiceWorker/#start-register-algorithm - B fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> { // A: Step 1 let promise = Promise::new(&*self.global()); let USVString(ref script_url) = script_url; let api_base_url = self.global().api_base_url(); // A: Step 3-5 let script_url = match api_base_url.join(script_url) { Ok(url) => url, Err(_) => { promise.reject_error(Error::Type("Invalid script URL".to_owned())); return promise; } }; // B: Step 2 match script_url.scheme() { "https" | "http" => {}, _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; } } // B: Step 3 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { promise.reject_error(Error::Type("Script URL contains forbidden characters".to_owned())); return promise; } // B: Step 4-5 let scope = match options.scope { Some(ref scope) => { let &USVString(ref inner_scope) = scope; match api_base_url.join(inner_scope) { Ok(url) => url, Err(_) => { promise.reject_error(Error::Type("Invalid scope URL".to_owned())); return promise; } } }, None => script_url.join("./").unwrap() }; // B: Step 6 match scope.scheme() { "https" | "http" => {}, _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; } } // B: Step 7 if scope.path().to_ascii_lowercase().contains("%2f") || scope.path().to_ascii_lowercase().contains("%5c") { promise.reject_error(Error::Type("Scope URL contains forbidden characters".to_owned())); return promise; } // B: Step 8 let job = Job::create_job(JobType::Register, scope, script_url, promise.clone(), &*self.client); ScriptThread::schedule_job(job); promise } }
random_line_split
serviceworkercontainer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::error::Error; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use dom::bindings::str::USVString; use dom::client::Client; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom::serviceworker::ServiceWorker; use dom_struct::dom_struct; use script_thread::ScriptThread; use serviceworkerjob::{Job, JobType}; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::default::Default; use std::rc::Rc; #[dom_struct] pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableDom<ServiceWorker>, client: Dom<Client> } impl ServiceWorkerContainer { fn
(client: &Client) -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Default::default(), client: Dom::from_ref(client), } } #[allow(unrooted_must_root)] pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> { let client = Client::new(&global.as_window()); let container = ServiceWorkerContainer::new_inherited(&*client); reflect_dom_object(Box::new(container), global, Wrap) } } impl ServiceWorkerContainerMethods for ServiceWorkerContainer { // https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute fn GetController(&self) -> Option<DomRoot<ServiceWorker>> { self.client.get_controller() } #[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A // https://w3c.github.io/ServiceWorker/#start-register-algorithm - B fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> { // A: Step 1 let promise = Promise::new(&*self.global()); let USVString(ref script_url) = script_url; let api_base_url = self.global().api_base_url(); // A: Step 3-5 let script_url = match api_base_url.join(script_url) { Ok(url) => url, Err(_) => { promise.reject_error(Error::Type("Invalid script URL".to_owned())); return promise; } }; // B: Step 2 match script_url.scheme() { "https" | "http" => {}, _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; } } // B: Step 3 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { promise.reject_error(Error::Type("Script URL contains forbidden characters".to_owned())); return promise; } // B: Step 4-5 let scope = match options.scope { Some(ref scope) => { let &USVString(ref inner_scope) = scope; match api_base_url.join(inner_scope) { Ok(url) => url, Err(_) => { promise.reject_error(Error::Type("Invalid scope URL".to_owned())); return promise; } } }, None => script_url.join("./").unwrap() }; // B: Step 6 match scope.scheme() { "https" | "http" => {}, _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; } } // B: Step 7 if scope.path().to_ascii_lowercase().contains("%2f") || scope.path().to_ascii_lowercase().contains("%5c") { promise.reject_error(Error::Type("Scope URL contains forbidden characters".to_owned())); return promise; } // B: Step 8 let job = Job::create_job(JobType::Register, scope, script_url, promise.clone(), &*self.client); ScriptThread::schedule_job(job); promise } }
new_inherited
identifier_name
serviceworkercontainer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::error::Error; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use dom::bindings::str::USVString; use dom::client::Client; use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom::serviceworker::ServiceWorker; use dom_struct::dom_struct; use script_thread::ScriptThread; use serviceworkerjob::{Job, JobType}; #[allow(unused_imports)] use std::ascii::AsciiExt; use std::default::Default; use std::rc::Rc; #[dom_struct] pub struct ServiceWorkerContainer { eventtarget: EventTarget, controller: MutNullableDom<ServiceWorker>, client: Dom<Client> } impl ServiceWorkerContainer { fn new_inherited(client: &Client) -> ServiceWorkerContainer { ServiceWorkerContainer { eventtarget: EventTarget::new_inherited(), controller: Default::default(), client: Dom::from_ref(client), } } #[allow(unrooted_must_root)] pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> { let client = Client::new(&global.as_window()); let container = ServiceWorkerContainer::new_inherited(&*client); reflect_dom_object(Box::new(container), global, Wrap) } } impl ServiceWorkerContainerMethods for ServiceWorkerContainer { // https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute fn GetController(&self) -> Option<DomRoot<ServiceWorker>>
#[allow(unrooted_must_root)] // https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A // https://w3c.github.io/ServiceWorker/#start-register-algorithm - B fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> { // A: Step 1 let promise = Promise::new(&*self.global()); let USVString(ref script_url) = script_url; let api_base_url = self.global().api_base_url(); // A: Step 3-5 let script_url = match api_base_url.join(script_url) { Ok(url) => url, Err(_) => { promise.reject_error(Error::Type("Invalid script URL".to_owned())); return promise; } }; // B: Step 2 match script_url.scheme() { "https" | "http" => {}, _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; } } // B: Step 3 if script_url.path().to_ascii_lowercase().contains("%2f") || script_url.path().to_ascii_lowercase().contains("%5c") { promise.reject_error(Error::Type("Script URL contains forbidden characters".to_owned())); return promise; } // B: Step 4-5 let scope = match options.scope { Some(ref scope) => { let &USVString(ref inner_scope) = scope; match api_base_url.join(inner_scope) { Ok(url) => url, Err(_) => { promise.reject_error(Error::Type("Invalid scope URL".to_owned())); return promise; } } }, None => script_url.join("./").unwrap() }; // B: Step 6 match scope.scheme() { "https" | "http" => {}, _ => { promise.reject_error(Error::Type("Only secure origins are allowed".to_owned())); return promise; } } // B: Step 7 if scope.path().to_ascii_lowercase().contains("%2f") || scope.path().to_ascii_lowercase().contains("%5c") { promise.reject_error(Error::Type("Scope URL contains forbidden characters".to_owned())); return promise; } // B: Step 8 let job = Job::create_job(JobType::Register, scope, script_url, promise.clone(), &*self.client); ScriptThread::schedule_job(job); promise } }
{ self.client.get_controller() }
identifier_body
CommentGenerator.py
""" CommentGenerator.py Author: Zefu Lu (zefulu2) Description: This Module generates comments and add it to the database Creation: 2014-11-4 """ #=============================================================================== # import references #=============================================================================== import sys reload(sys) # from DatabaseWrapper import DatabaseWrapper from datetime import datetime from dateutil.parser import parse from pprint import pprint as pp from random import randrange import time import os import django sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) os.environ['DJANGO_SETTINGS_MODULE']='opinion.settings' from django.contrib.auth.models import User from appopinion.models import * users = User.objects.all() django.setup() class CommentGenerator(object): '''Constructor''' def __init__(self, topic_id): self.topic_id = topic_id; #initialize database wrapper #self.db = DatabaseWrapper(db_config_file) def generate(self): counter= 1 while(True): item_dict = {} item_dict['content'] = "Comment " + str(randrange(1000)) + " @ "+datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['parent_id'] = self.topic_id # self.db.insertToTable('newapp_comment', item_dict) topic = Topic.objects.get(pk=item_dict['parent_id']) comment = Comment( content=item_dict['content'], parent=topic, date=item_dict['date'],
counter+=1 def main(): generator = CommentGenerator(5) generator.generate() if __name__ == '__main__': main()
) comment.save() pp(item_dict) time.sleep(2)
random_line_split
CommentGenerator.py
""" CommentGenerator.py Author: Zefu Lu (zefulu2) Description: This Module generates comments and add it to the database Creation: 2014-11-4 """ #=============================================================================== # import references #=============================================================================== import sys reload(sys) # from DatabaseWrapper import DatabaseWrapper from datetime import datetime from dateutil.parser import parse from pprint import pprint as pp from random import randrange import time import os import django sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) os.environ['DJANGO_SETTINGS_MODULE']='opinion.settings' from django.contrib.auth.models import User from appopinion.models import * users = User.objects.all() django.setup() class CommentGenerator(object): '''Constructor''' def __init__(self, topic_id): self.topic_id = topic_id; #initialize database wrapper #self.db = DatabaseWrapper(db_config_file) def generate(self): counter= 1 while(True): item_dict = {} item_dict['content'] = "Comment " + str(randrange(1000)) + " @ "+datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['parent_id'] = self.topic_id # self.db.insertToTable('newapp_comment', item_dict) topic = Topic.objects.get(pk=item_dict['parent_id']) comment = Comment( content=item_dict['content'], parent=topic, date=item_dict['date'], ) comment.save() pp(item_dict) time.sleep(2) counter+=1 def main(): generator = CommentGenerator(5) generator.generate() if __name__ == '__main__':
main()
conditional_block
CommentGenerator.py
""" CommentGenerator.py Author: Zefu Lu (zefulu2) Description: This Module generates comments and add it to the database Creation: 2014-11-4 """ #=============================================================================== # import references #=============================================================================== import sys reload(sys) # from DatabaseWrapper import DatabaseWrapper from datetime import datetime from dateutil.parser import parse from pprint import pprint as pp from random import randrange import time import os import django sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) os.environ['DJANGO_SETTINGS_MODULE']='opinion.settings' from django.contrib.auth.models import User from appopinion.models import * users = User.objects.all() django.setup() class CommentGenerator(object): '''Constructor''' def __init__(self, topic_id): self.topic_id = topic_id; #initialize database wrapper #self.db = DatabaseWrapper(db_config_file) def generate(self): counter= 1 while(True): item_dict = {} item_dict['content'] = "Comment " + str(randrange(1000)) + " @ "+datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['parent_id'] = self.topic_id # self.db.insertToTable('newapp_comment', item_dict) topic = Topic.objects.get(pk=item_dict['parent_id']) comment = Comment( content=item_dict['content'], parent=topic, date=item_dict['date'], ) comment.save() pp(item_dict) time.sleep(2) counter+=1 def main():
if __name__ == '__main__': main()
generator = CommentGenerator(5) generator.generate()
identifier_body
CommentGenerator.py
""" CommentGenerator.py Author: Zefu Lu (zefulu2) Description: This Module generates comments and add it to the database Creation: 2014-11-4 """ #=============================================================================== # import references #=============================================================================== import sys reload(sys) # from DatabaseWrapper import DatabaseWrapper from datetime import datetime from dateutil.parser import parse from pprint import pprint as pp from random import randrange import time import os import django sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) os.environ['DJANGO_SETTINGS_MODULE']='opinion.settings' from django.contrib.auth.models import User from appopinion.models import * users = User.objects.all() django.setup() class CommentGenerator(object): '''Constructor''' def __init__(self, topic_id): self.topic_id = topic_id; #initialize database wrapper #self.db = DatabaseWrapper(db_config_file) def generate(self): counter= 1 while(True): item_dict = {} item_dict['content'] = "Comment " + str(randrange(1000)) + " @ "+datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['date'] = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') item_dict['parent_id'] = self.topic_id # self.db.insertToTable('newapp_comment', item_dict) topic = Topic.objects.get(pk=item_dict['parent_id']) comment = Comment( content=item_dict['content'], parent=topic, date=item_dict['date'], ) comment.save() pp(item_dict) time.sleep(2) counter+=1 def
(): generator = CommentGenerator(5) generator.generate() if __name__ == '__main__': main()
main
identifier_name
testworkletglobalscope.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding; use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding::TestWorkletGlobalScopeMethods; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::worklet::WorkletExecutor; use crate::dom::workletglobalscope::WorkletGlobalScope; use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use dom_struct::dom_struct; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use servo_channel::Sender; use servo_url::ServoUrl; use std::collections::HashMap; // check-tidy: no specs after this line #[dom_struct] pub struct TestWorkletGlobalScope { // The worklet global for this object worklet_global: WorkletGlobalScope, // The key/value pairs lookup_table: DomRefCell<HashMap<String, String>>, } impl TestWorkletGlobalScope { #[allow(unsafe_code)] pub fn new( runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> DomRoot<TestWorkletGlobalScope> { debug!( "Creating test worklet global scope for pipeline {}.", pipeline_id ); let global = Box::new(TestWorkletGlobalScope { worklet_global: WorkletGlobalScope::new_inherited( pipeline_id, base_url, executor, init, ), lookup_table: Default::default(), }); unsafe { TestWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } } pub fn perform_a_worklet_task(&self, task: TestWorkletTask) { match task { TestWorkletTask::Lookup(key, sender) => { debug!("Looking up key {}.", key); let result = self.lookup_table.borrow().get(&key).cloned(); let _ = sender.send(result); }, } } } impl TestWorkletGlobalScopeMethods for TestWorkletGlobalScope { fn RegisterKeyValue(&self, key: DOMString, value: DOMString)
} /// Tasks which can be performed by test worklets. pub enum TestWorkletTask { Lookup(String, Sender<Option<String>>), }
{ debug!("Registering test worklet key/value {}/{}.", key, value); self.lookup_table .borrow_mut() .insert(String::from(key), String::from(value)); }
identifier_body
testworkletglobalscope.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding; use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding::TestWorkletGlobalScopeMethods; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::worklet::WorkletExecutor; use crate::dom::workletglobalscope::WorkletGlobalScope; use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use dom_struct::dom_struct; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use servo_channel::Sender; use servo_url::ServoUrl; use std::collections::HashMap; // check-tidy: no specs after this line #[dom_struct] pub struct TestWorkletGlobalScope { // The worklet global for this object worklet_global: WorkletGlobalScope, // The key/value pairs lookup_table: DomRefCell<HashMap<String, String>>, } impl TestWorkletGlobalScope { #[allow(unsafe_code)] pub fn new( runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> DomRoot<TestWorkletGlobalScope> { debug!( "Creating test worklet global scope for pipeline {}.", pipeline_id ); let global = Box::new(TestWorkletGlobalScope { worklet_global: WorkletGlobalScope::new_inherited( pipeline_id, base_url, executor, init, ), lookup_table: Default::default(), }); unsafe { TestWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } } pub fn perform_a_worklet_task(&self, task: TestWorkletTask) { match task { TestWorkletTask::Lookup(key, sender) => { debug!("Looking up key {}.", key); let result = self.lookup_table.borrow().get(&key).cloned(); let _ = sender.send(result); }, } } } impl TestWorkletGlobalScopeMethods for TestWorkletGlobalScope { fn RegisterKeyValue(&self, key: DOMString, value: DOMString) { debug!("Registering test worklet key/value {}/{}.", key, value); self.lookup_table .borrow_mut() .insert(String::from(key), String::from(value)); } } /// Tasks which can be performed by test worklets. pub enum
{ Lookup(String, Sender<Option<String>>), }
TestWorkletTask
identifier_name
testworkletglobalscope.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding; use crate::dom::bindings::codegen::Bindings::TestWorkletGlobalScopeBinding::TestWorkletGlobalScopeMethods; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::worklet::WorkletExecutor; use crate::dom::workletglobalscope::WorkletGlobalScope; use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use dom_struct::dom_struct; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use servo_channel::Sender; use servo_url::ServoUrl; use std::collections::HashMap; // check-tidy: no specs after this line #[dom_struct] pub struct TestWorkletGlobalScope { // The worklet global for this object worklet_global: WorkletGlobalScope, // The key/value pairs lookup_table: DomRefCell<HashMap<String, String>>, } impl TestWorkletGlobalScope { #[allow(unsafe_code)] pub fn new( runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit, ) -> DomRoot<TestWorkletGlobalScope> { debug!( "Creating test worklet global scope for pipeline {}.", pipeline_id ); let global = Box::new(TestWorkletGlobalScope { worklet_global: WorkletGlobalScope::new_inherited( pipeline_id, base_url, executor, init, ), lookup_table: Default::default(),
}); unsafe { TestWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } } pub fn perform_a_worklet_task(&self, task: TestWorkletTask) { match task { TestWorkletTask::Lookup(key, sender) => { debug!("Looking up key {}.", key); let result = self.lookup_table.borrow().get(&key).cloned(); let _ = sender.send(result); }, } } } impl TestWorkletGlobalScopeMethods for TestWorkletGlobalScope { fn RegisterKeyValue(&self, key: DOMString, value: DOMString) { debug!("Registering test worklet key/value {}/{}.", key, value); self.lookup_table .borrow_mut() .insert(String::from(key), String::from(value)); } } /// Tasks which can be performed by test worklets. pub enum TestWorkletTask { Lookup(String, Sender<Option<String>>), }
random_line_split
_vbscript.py
############################################################################### # Name: vbscript.py # # Purpose: Define VBScript syntax for highlighting and other features # # Author: Cody Precord <cprecord@editra.org> # # Copyright: (c) 2008 Cody Precord <staff@editra.org> # # License: wxWindows License # ############################################################################### """ FILE: vbscript.py AUTHOR: Cody Precord @summary: Lexer configuration module for VBScript. """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: _vbscript.py 63834 2010-04-03 06:04:33Z CJP $" __revision__ = "$Revision: 63834 $" #-----------------------------------------------------------------------------# # Imports import wx.stc as stc # Local Imports import synglob import syndata #-----------------------------------------------------------------------------# #---- Keyword Specifications ----# VBS_KW = ("addressof alias and as attribute base begin binary boolean byref " "byte byval call case cdbl cint clng compare const csng cstr " "currency date decimal declare defbool defbyte defcur defdate defdbl " "defdec defint deflng defobj defsng defstr defvar dim do double each " "else elseif empty end enum eqv erase error event exit explicit " "false for friend function get global gosub goto if imp implements " "in input integer is len let lib like load lock long loop lset me " "mid midb mod new next not nothing null object on option optional " "or paramarray preserve print private property public raiseevent " "randomize redim rem resume return rset seek select set single " "static step stop string sub text then time to true type typeof " "unload until variant wend while with withevents xor") # Syntax specifications SYNTAX_ITEMS = [ (stc.STC_B_ASM, 'asm_style'), (stc.STC_B_BINNUMBER, 'default_style'), # STYLE NEEDED (stc.STC_B_COMMENT, 'comment_style'), (stc.STC_B_CONSTANT, 'const_style'), (stc.STC_B_DATE, 'default_style'), # STYLE NEEDED (stc.STC_B_DEFAULT, 'default_style'), (stc.STC_B_ERROR, 'error_style'), (stc.STC_B_HEXNUMBER, 'number_style'), (stc.STC_B_IDENTIFIER, 'default_style'), (stc.STC_B_KEYWORD, 'keyword_style'), (stc.STC_B_KEYWORD2, 'class_style'), # STYLE NEEDED (stc.STC_B_KEYWORD3, 'funct_style'), # STYLE NEEDED (stc.STC_B_KEYWORD4, 'scalar_style'), # STYLE NEEDED (stc.STC_B_LABEL, 'directive_style'), # STYLE NEEDED (stc.STC_B_NUMBER, 'number_style'), (stc.STC_B_OPERATOR, 'operator_style'), (stc.STC_B_PREPROCESSOR, 'pre_style'), (stc.STC_B_STRING, 'string_style'), (stc.STC_B_STRINGEOL, 'stringeol_style') ] #---- Extra Properties ----# FOLD = ("fold", "1") #-----------------------------------------------------------------------------# class SyntaxData(syndata.SyntaxDataBase): """SyntaxData object for VbScript""" def
(self, langid): syndata.SyntaxDataBase.__init__(self, langid) # Setup self.SetLexer(stc.STC_LEX_VBSCRIPT) def GetKeywords(self): """Returns Specified Keywords List """ return [(0, VBS_KW),] def GetSyntaxSpec(self): """Syntax Specifications """ return SYNTAX_ITEMS def GetProperties(self): """Returns a list of Extra Properties to set """ return [FOLD] def GetCommentPattern(self): """Returns a list of characters used to comment a block of code """ return [u'\'']
__init__
identifier_name
_vbscript.py
############################################################################### # Name: vbscript.py # # Purpose: Define VBScript syntax for highlighting and other features # # Author: Cody Precord <cprecord@editra.org> # # Copyright: (c) 2008 Cody Precord <staff@editra.org> # # License: wxWindows License # ############################################################################### """ FILE: vbscript.py AUTHOR: Cody Precord @summary: Lexer configuration module for VBScript. """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: _vbscript.py 63834 2010-04-03 06:04:33Z CJP $" __revision__ = "$Revision: 63834 $" #-----------------------------------------------------------------------------# # Imports import wx.stc as stc # Local Imports import synglob import syndata #-----------------------------------------------------------------------------# #---- Keyword Specifications ----# VBS_KW = ("addressof alias and as attribute base begin binary boolean byref " "byte byval call case cdbl cint clng compare const csng cstr " "currency date decimal declare defbool defbyte defcur defdate defdbl " "defdec defint deflng defobj defsng defstr defvar dim do double each " "else elseif empty end enum eqv erase error event exit explicit " "false for friend function get global gosub goto if imp implements " "in input integer is len let lib like load lock long loop lset me " "mid midb mod new next not nothing null object on option optional " "or paramarray preserve print private property public raiseevent " "randomize redim rem resume return rset seek select set single " "static step stop string sub text then time to true type typeof " "unload until variant wend while with withevents xor") # Syntax specifications SYNTAX_ITEMS = [ (stc.STC_B_ASM, 'asm_style'), (stc.STC_B_BINNUMBER, 'default_style'), # STYLE NEEDED (stc.STC_B_COMMENT, 'comment_style'), (stc.STC_B_CONSTANT, 'const_style'), (stc.STC_B_DATE, 'default_style'), # STYLE NEEDED (stc.STC_B_DEFAULT, 'default_style'), (stc.STC_B_ERROR, 'error_style'), (stc.STC_B_HEXNUMBER, 'number_style'), (stc.STC_B_IDENTIFIER, 'default_style'), (stc.STC_B_KEYWORD, 'keyword_style'),
(stc.STC_B_KEYWORD4, 'scalar_style'), # STYLE NEEDED (stc.STC_B_LABEL, 'directive_style'), # STYLE NEEDED (stc.STC_B_NUMBER, 'number_style'), (stc.STC_B_OPERATOR, 'operator_style'), (stc.STC_B_PREPROCESSOR, 'pre_style'), (stc.STC_B_STRING, 'string_style'), (stc.STC_B_STRINGEOL, 'stringeol_style') ] #---- Extra Properties ----# FOLD = ("fold", "1") #-----------------------------------------------------------------------------# class SyntaxData(syndata.SyntaxDataBase): """SyntaxData object for VbScript""" def __init__(self, langid): syndata.SyntaxDataBase.__init__(self, langid) # Setup self.SetLexer(stc.STC_LEX_VBSCRIPT) def GetKeywords(self): """Returns Specified Keywords List """ return [(0, VBS_KW),] def GetSyntaxSpec(self): """Syntax Specifications """ return SYNTAX_ITEMS def GetProperties(self): """Returns a list of Extra Properties to set """ return [FOLD] def GetCommentPattern(self): """Returns a list of characters used to comment a block of code """ return [u'\'']
(stc.STC_B_KEYWORD2, 'class_style'), # STYLE NEEDED (stc.STC_B_KEYWORD3, 'funct_style'), # STYLE NEEDED
random_line_split
_vbscript.py
############################################################################### # Name: vbscript.py # # Purpose: Define VBScript syntax for highlighting and other features # # Author: Cody Precord <cprecord@editra.org> # # Copyright: (c) 2008 Cody Precord <staff@editra.org> # # License: wxWindows License # ############################################################################### """ FILE: vbscript.py AUTHOR: Cody Precord @summary: Lexer configuration module for VBScript. """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: _vbscript.py 63834 2010-04-03 06:04:33Z CJP $" __revision__ = "$Revision: 63834 $" #-----------------------------------------------------------------------------# # Imports import wx.stc as stc # Local Imports import synglob import syndata #-----------------------------------------------------------------------------# #---- Keyword Specifications ----# VBS_KW = ("addressof alias and as attribute base begin binary boolean byref " "byte byval call case cdbl cint clng compare const csng cstr " "currency date decimal declare defbool defbyte defcur defdate defdbl " "defdec defint deflng defobj defsng defstr defvar dim do double each " "else elseif empty end enum eqv erase error event exit explicit " "false for friend function get global gosub goto if imp implements " "in input integer is len let lib like load lock long loop lset me " "mid midb mod new next not nothing null object on option optional " "or paramarray preserve print private property public raiseevent " "randomize redim rem resume return rset seek select set single " "static step stop string sub text then time to true type typeof " "unload until variant wend while with withevents xor") # Syntax specifications SYNTAX_ITEMS = [ (stc.STC_B_ASM, 'asm_style'), (stc.STC_B_BINNUMBER, 'default_style'), # STYLE NEEDED (stc.STC_B_COMMENT, 'comment_style'), (stc.STC_B_CONSTANT, 'const_style'), (stc.STC_B_DATE, 'default_style'), # STYLE NEEDED (stc.STC_B_DEFAULT, 'default_style'), (stc.STC_B_ERROR, 'error_style'), (stc.STC_B_HEXNUMBER, 'number_style'), (stc.STC_B_IDENTIFIER, 'default_style'), (stc.STC_B_KEYWORD, 'keyword_style'), (stc.STC_B_KEYWORD2, 'class_style'), # STYLE NEEDED (stc.STC_B_KEYWORD3, 'funct_style'), # STYLE NEEDED (stc.STC_B_KEYWORD4, 'scalar_style'), # STYLE NEEDED (stc.STC_B_LABEL, 'directive_style'), # STYLE NEEDED (stc.STC_B_NUMBER, 'number_style'), (stc.STC_B_OPERATOR, 'operator_style'), (stc.STC_B_PREPROCESSOR, 'pre_style'), (stc.STC_B_STRING, 'string_style'), (stc.STC_B_STRINGEOL, 'stringeol_style') ] #---- Extra Properties ----# FOLD = ("fold", "1") #-----------------------------------------------------------------------------# class SyntaxData(syndata.SyntaxDataBase): """SyntaxData object for VbScript""" def __init__(self, langid):
def GetKeywords(self): """Returns Specified Keywords List """ return [(0, VBS_KW),] def GetSyntaxSpec(self): """Syntax Specifications """ return SYNTAX_ITEMS def GetProperties(self): """Returns a list of Extra Properties to set """ return [FOLD] def GetCommentPattern(self): """Returns a list of characters used to comment a block of code """ return [u'\'']
syndata.SyntaxDataBase.__init__(self, langid) # Setup self.SetLexer(stc.STC_LEX_VBSCRIPT)
identifier_body
tz.js
//MES- We want to automatically detect what timezone a user is in. In a web application, // the timezone of the user is not easily available. However, we do have a clue. // The JavaScript function Date.getTimezoneOffset() returns the offset from UTC for // a given date (in minutes.) If we ask for the offset for a number of different // times, we can guess the timezone that the user is in. This method is not perfect // but should result in a timezone that is a pretty good guess. // For our "probe" times, we get the offset for June 30, 2005 and for December 30, 2005. // June 30 is likely to be affected by Daylight Savings Time for a user that is in a zone // that has a DST offset, and December 30 is unlikely to be affected by DST (or the opposite // in the southern hemisphere.) Probing both of these times gives us a good guess as to // what the "normal" offset and DST offsets are for the timezone. // Choosing recent dates (at the time of this writing) assures that we are up-to-date with // regard to political decisions regarding the definitions of timezones (though this // information may well be out of date in the future. // // To convert the offsets to a timezone, we need a list of "standard" timezones. // It'd be nice to run through a canonical list of timezones (such as // TZInfo::Timezones.all_country_zones), and probe each for the offset for the above stated // dates. This has a couple of problems. First, it could be quite slow, since calculating the // offset for a timezone for a date can take some time. Second, there will be repeat entries // (i.e. multiple timezones that have the same offset for the two dates), and we want // a semi-intelligent way to differentiate between them. Third, it's server-side. // // We deal with these problems by developing a separate canonical list, represented in // get_tz_name below. It simply maps two numbers to a timezone name (well, it's // actually an array of objects, each of which contains the offsets and the name.) // // The get_tz_name list was created via these steps: // 1. Translate all items in TZInfo::Timezone.all into TZOffsetInfo objects (i.e. extract // the name, summer offset, and winter offset for the days mentioned above) // 2. Order the items by offset (summer offset, then winter offset) // 3. Calculate the "popularity" of each timezone. When multiple timezones match // a given pair of offsets, we want to return the most likely match for the // user, which is assumed to be the most popular (i.e. widely used) timezone // that matches. To assess popularity, a Google search is conducted for the // name of each timezone (or, more precisely, for the text 'zone "[timezone name]"'). // The number of Google hits is assumed to roughly correlate to the popularity of // the timezone. // 4. Among all timezones for an offset pair, choose the most popular timezone- this // will be the match for that offset pair. // // All of this logic was performed in Ruby code (see the additions to TZInfo::Timezone in // application_helper.rb), and then converted to JavaScript for use in the client. function get_tz_name()
// MES- set_select is a tiny helper that takes in the name of a select control // and the value of an item to be selected. It looks for an option in the // select with the indicated value. If found, it selects it and returns true. // If the item is not found, returns false. function set_select(ctrl, val) { opts = $(ctrl).options; for (var i = 0; i < opts.length; i++) { if (val == opts[i].value) { opts[i].selected = true; return true; } } return false; }
{ so = -1 * (new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0))).getTimezoneOffset(); wo = -1 * (new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0))).getTimezoneOffset(); if (-660 == so && -660 == wo) return 'Pacific/Midway'; if (-600 == so && -600 == wo) return 'Pacific/Tahiti'; if (-570 == so && -570 == wo) return 'Pacific/Marquesas'; if (-540 == so && -600 == wo) return 'America/Adak'; if (-540 == so && -540 == wo) return 'Pacific/Gambier'; if (-480 == so && -540 == wo) return 'America/Anchorage'; if (-480 == so && -480 == wo) return 'Pacific/Pitcairn'; if (-420 == so && -480 == wo) return 'America/Los_Angeles'; if (-420 == so && -420 == wo) return 'America/Phoenix'; if (-360 == so && -420 == wo) return 'America/Denver'; if (-360 == so && -360 == wo) return 'America/Guatemala'; if (-360 == so && -300 == wo) return 'Pacific/Easter'; if (-300 == so && -360 == wo) return 'America/Chicago'; if (-300 == so && -300 == wo) return 'America/Panama'; if (-240 == so && -300 == wo) return 'America/New_York'; if (-240 == so && -240 == wo) return 'America/Guyana'; if (-240 == so && -180 == wo) return 'America/Santiago'; if (-180 == so && -240 == wo) return 'America/Halifax'; if (-180 == so && -180 == wo) return 'America/Montevideo'; if (-180 == so && -120 == wo) return 'America/Sao_Paulo'; if (-150 == so && -210 == wo) return 'America/St_Johns'; if (-120 == so && -180 == wo) return 'America/Godthab'; if (-120 == so && -120 == wo) return 'America/Noronha'; if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde'; if (0 == so && -60 == wo) return 'Atlantic/Azores'; if (0 == so && 0 == wo) return 'Africa/Bamako'; if (60 == so && 0 == wo) return 'Europe/London'; if (60 == so && 60 == wo) return 'Africa/Algiers'; if (60 == so && 120 == wo) return 'Africa/Windhoek'; if (120 == so && 60 == wo) return 'Europe/Amsterdam'; if (120 == so && 120 == wo) return 'Africa/Johannesburg'; if (180 == so && 120 == wo) return 'Asia/Beirut'; if (180 == so && 180 == wo) return 'Africa/Nairobi'; if (240 == so && 180 == wo) return 'Europe/Moscow'; if (240 == so && 240 == wo) return 'Asia/Dubai'; if (270 == so && 210 == wo) return 'Asia/Tehran'; if (270 == so && 270 == wo) return 'Asia/Kabul'; if (300 == so && 240 == wo) return 'Asia/Yerevan'; if (300 == so && 300 == wo) return 'Asia/Tashkent'; if (330 == so && 330 == wo) return 'Asia/Calcutta'; if (345 == so && 345 == wo) return 'Asia/Katmandu'; if (360 == so && 300 == wo) return 'Asia/Yekaterinburg'; if (360 == so && 360 == wo) return 'Asia/Colombo'; if (390 == so && 390 == wo) return 'Asia/Rangoon'; if (420 == so && 360 == wo) return 'Asia/Novosibirsk'; if (420 == so && 420 == wo) return 'Asia/Bangkok'; if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk'; if (480 == so && 480 == wo) return 'Australia/Perth'; if (540 == so && 480 == wo) return 'Asia/Irkutsk'; if (540 == so && 540 == wo) return 'Asia/Tokyo'; if (570 == so && 570 == wo) return 'Australia/Darwin'; if (570 == so && 630 == wo) return 'Australia/Adelaide'; if (600 == so && 540 == wo) return 'Asia/Yakutsk'; if (600 == so && 600 == wo) return 'Australia/Brisbane'; if (600 == so && 660 == wo) return 'Australia/Sydney'; if (630 == so && 660 == wo) return 'Australia/Lord_Howe'; if (660 == so && 600 == wo) return 'Asia/Vladivostok'; if (660 == so && 660 == wo) return 'Pacific/Guadalcanal'; if (690 == so && 690 == wo) return 'Pacific/Norfolk'; if (720 == so && 660 == wo) return 'Asia/Magadan'; if (720 == so && 720 == wo) return 'Pacific/Fiji'; if (720 == so && 780 == wo) return 'Pacific/Auckland'; if (765 == so && 825 == wo) return 'Pacific/Chatham'; if (780 == so && 720 == wo) return 'Asia/Kamchatka'; if (780 == so && 780 == wo) return 'Pacific/Enderbury'; if (840 == so && 840 == wo) return 'Pacific/Kiritimati'; return 'America/Los_Angeles'; }
identifier_body
tz.js
//MES- We want to automatically detect what timezone a user is in. In a web application, // the timezone of the user is not easily available. However, we do have a clue. // The JavaScript function Date.getTimezoneOffset() returns the offset from UTC for // a given date (in minutes.) If we ask for the offset for a number of different // times, we can guess the timezone that the user is in. This method is not perfect // but should result in a timezone that is a pretty good guess. // For our "probe" times, we get the offset for June 30, 2005 and for December 30, 2005. // June 30 is likely to be affected by Daylight Savings Time for a user that is in a zone // that has a DST offset, and December 30 is unlikely to be affected by DST (or the opposite // in the southern hemisphere.) Probing both of these times gives us a good guess as to // what the "normal" offset and DST offsets are for the timezone. // Choosing recent dates (at the time of this writing) assures that we are up-to-date with // regard to political decisions regarding the definitions of timezones (though this // information may well be out of date in the future. // // To convert the offsets to a timezone, we need a list of "standard" timezones. // It'd be nice to run through a canonical list of timezones (such as // TZInfo::Timezones.all_country_zones), and probe each for the offset for the above stated // dates. This has a couple of problems. First, it could be quite slow, since calculating the // offset for a timezone for a date can take some time. Second, there will be repeat entries // (i.e. multiple timezones that have the same offset for the two dates), and we want // a semi-intelligent way to differentiate between them. Third, it's server-side. // // We deal with these problems by developing a separate canonical list, represented in // get_tz_name below. It simply maps two numbers to a timezone name (well, it's // actually an array of objects, each of which contains the offsets and the name.) // // The get_tz_name list was created via these steps: // 1. Translate all items in TZInfo::Timezone.all into TZOffsetInfo objects (i.e. extract // the name, summer offset, and winter offset for the days mentioned above) // 2. Order the items by offset (summer offset, then winter offset) // 3. Calculate the "popularity" of each timezone. When multiple timezones match // a given pair of offsets, we want to return the most likely match for the // user, which is assumed to be the most popular (i.e. widely used) timezone // that matches. To assess popularity, a Google search is conducted for the // name of each timezone (or, more precisely, for the text 'zone "[timezone name]"'). // The number of Google hits is assumed to roughly correlate to the popularity of // the timezone. // 4. Among all timezones for an offset pair, choose the most popular timezone- this // will be the match for that offset pair. // // All of this logic was performed in Ruby code (see the additions to TZInfo::Timezone in // application_helper.rb), and then converted to JavaScript for use in the client. function get_tz_name() { so = -1 * (new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0))).getTimezoneOffset(); wo = -1 * (new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0))).getTimezoneOffset(); if (-660 == so && -660 == wo) return 'Pacific/Midway'; if (-600 == so && -600 == wo) return 'Pacific/Tahiti'; if (-570 == so && -570 == wo) return 'Pacific/Marquesas'; if (-540 == so && -600 == wo) return 'America/Adak'; if (-540 == so && -540 == wo) return 'Pacific/Gambier'; if (-480 == so && -540 == wo) return 'America/Anchorage'; if (-480 == so && -480 == wo) return 'Pacific/Pitcairn'; if (-420 == so && -480 == wo) return 'America/Los_Angeles'; if (-420 == so && -420 == wo) return 'America/Phoenix'; if (-360 == so && -420 == wo) return 'America/Denver'; if (-360 == so && -360 == wo) return 'America/Guatemala'; if (-360 == so && -300 == wo) return 'Pacific/Easter'; if (-300 == so && -360 == wo) return 'America/Chicago'; if (-300 == so && -300 == wo) return 'America/Panama'; if (-240 == so && -300 == wo) return 'America/New_York'; if (-240 == so && -240 == wo) return 'America/Guyana'; if (-240 == so && -180 == wo) return 'America/Santiago'; if (-180 == so && -240 == wo) return 'America/Halifax'; if (-180 == so && -180 == wo) return 'America/Montevideo'; if (-180 == so && -120 == wo) return 'America/Sao_Paulo'; if (-150 == so && -210 == wo) return 'America/St_Johns'; if (-120 == so && -180 == wo) return 'America/Godthab'; if (-120 == so && -120 == wo) return 'America/Noronha'; if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde'; if (0 == so && -60 == wo) return 'Atlantic/Azores'; if (0 == so && 0 == wo) return 'Africa/Bamako'; if (60 == so && 0 == wo) return 'Europe/London'; if (60 == so && 60 == wo) return 'Africa/Algiers'; if (60 == so && 120 == wo) return 'Africa/Windhoek'; if (120 == so && 60 == wo) return 'Europe/Amsterdam'; if (120 == so && 120 == wo) return 'Africa/Johannesburg'; if (180 == so && 120 == wo) return 'Asia/Beirut'; if (180 == so && 180 == wo) return 'Africa/Nairobi'; if (240 == so && 180 == wo) return 'Europe/Moscow'; if (240 == so && 240 == wo) return 'Asia/Dubai'; if (270 == so && 210 == wo) return 'Asia/Tehran'; if (270 == so && 270 == wo) return 'Asia/Kabul'; if (300 == so && 240 == wo) return 'Asia/Yerevan'; if (300 == so && 300 == wo) return 'Asia/Tashkent'; if (330 == so && 330 == wo) return 'Asia/Calcutta'; if (345 == so && 345 == wo) return 'Asia/Katmandu'; if (360 == so && 300 == wo) return 'Asia/Yekaterinburg'; if (360 == so && 360 == wo) return 'Asia/Colombo'; if (390 == so && 390 == wo) return 'Asia/Rangoon'; if (420 == so && 360 == wo) return 'Asia/Novosibirsk'; if (420 == so && 420 == wo) return 'Asia/Bangkok'; if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk'; if (480 == so && 480 == wo) return 'Australia/Perth'; if (540 == so && 480 == wo) return 'Asia/Irkutsk'; if (540 == so && 540 == wo) return 'Asia/Tokyo'; if (570 == so && 570 == wo) return 'Australia/Darwin'; if (570 == so && 630 == wo) return 'Australia/Adelaide'; if (600 == so && 540 == wo) return 'Asia/Yakutsk'; if (600 == so && 600 == wo) return 'Australia/Brisbane'; if (600 == so && 660 == wo) return 'Australia/Sydney'; if (630 == so && 660 == wo) return 'Australia/Lord_Howe'; if (660 == so && 600 == wo) return 'Asia/Vladivostok'; if (660 == so && 660 == wo) return 'Pacific/Guadalcanal'; if (690 == so && 690 == wo) return 'Pacific/Norfolk'; if (720 == so && 660 == wo) return 'Asia/Magadan'; if (720 == so && 720 == wo) return 'Pacific/Fiji'; if (720 == so && 780 == wo) return 'Pacific/Auckland'; if (765 == so && 825 == wo) return 'Pacific/Chatham'; if (780 == so && 720 == wo) return 'Asia/Kamchatka'; if (780 == so && 780 == wo) return 'Pacific/Enderbury'; if (840 == so && 840 == wo) return 'Pacific/Kiritimati'; return 'America/Los_Angeles'; } // MES- set_select is a tiny helper that takes in the name of a select control // and the value of an item to be selected. It looks for an option in the // select with the indicated value. If found, it selects it and returns true. // If the item is not found, returns false. function set_select(ctrl, val) { opts = $(ctrl).options; for (var i = 0; i < opts.length; i++) { if (val == opts[i].value) {
}
opts[i].selected = true; return true; } } return false;
random_line_split
tz.js
//MES- We want to automatically detect what timezone a user is in. In a web application, // the timezone of the user is not easily available. However, we do have a clue. // The JavaScript function Date.getTimezoneOffset() returns the offset from UTC for // a given date (in minutes.) If we ask for the offset for a number of different // times, we can guess the timezone that the user is in. This method is not perfect // but should result in a timezone that is a pretty good guess. // For our "probe" times, we get the offset for June 30, 2005 and for December 30, 2005. // June 30 is likely to be affected by Daylight Savings Time for a user that is in a zone // that has a DST offset, and December 30 is unlikely to be affected by DST (or the opposite // in the southern hemisphere.) Probing both of these times gives us a good guess as to // what the "normal" offset and DST offsets are for the timezone. // Choosing recent dates (at the time of this writing) assures that we are up-to-date with // regard to political decisions regarding the definitions of timezones (though this // information may well be out of date in the future. // // To convert the offsets to a timezone, we need a list of "standard" timezones. // It'd be nice to run through a canonical list of timezones (such as // TZInfo::Timezones.all_country_zones), and probe each for the offset for the above stated // dates. This has a couple of problems. First, it could be quite slow, since calculating the // offset for a timezone for a date can take some time. Second, there will be repeat entries // (i.e. multiple timezones that have the same offset for the two dates), and we want // a semi-intelligent way to differentiate between them. Third, it's server-side. // // We deal with these problems by developing a separate canonical list, represented in // get_tz_name below. It simply maps two numbers to a timezone name (well, it's // actually an array of objects, each of which contains the offsets and the name.) // // The get_tz_name list was created via these steps: // 1. Translate all items in TZInfo::Timezone.all into TZOffsetInfo objects (i.e. extract // the name, summer offset, and winter offset for the days mentioned above) // 2. Order the items by offset (summer offset, then winter offset) // 3. Calculate the "popularity" of each timezone. When multiple timezones match // a given pair of offsets, we want to return the most likely match for the // user, which is assumed to be the most popular (i.e. widely used) timezone // that matches. To assess popularity, a Google search is conducted for the // name of each timezone (or, more precisely, for the text 'zone "[timezone name]"'). // The number of Google hits is assumed to roughly correlate to the popularity of // the timezone. // 4. Among all timezones for an offset pair, choose the most popular timezone- this // will be the match for that offset pair. // // All of this logic was performed in Ruby code (see the additions to TZInfo::Timezone in // application_helper.rb), and then converted to JavaScript for use in the client. function get_tz_name() { so = -1 * (new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0))).getTimezoneOffset(); wo = -1 * (new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0))).getTimezoneOffset(); if (-660 == so && -660 == wo) return 'Pacific/Midway'; if (-600 == so && -600 == wo) return 'Pacific/Tahiti'; if (-570 == so && -570 == wo) return 'Pacific/Marquesas'; if (-540 == so && -600 == wo) return 'America/Adak'; if (-540 == so && -540 == wo) return 'Pacific/Gambier'; if (-480 == so && -540 == wo) return 'America/Anchorage'; if (-480 == so && -480 == wo) return 'Pacific/Pitcairn'; if (-420 == so && -480 == wo) return 'America/Los_Angeles'; if (-420 == so && -420 == wo) return 'America/Phoenix'; if (-360 == so && -420 == wo) return 'America/Denver'; if (-360 == so && -360 == wo) return 'America/Guatemala'; if (-360 == so && -300 == wo) return 'Pacific/Easter'; if (-300 == so && -360 == wo) return 'America/Chicago'; if (-300 == so && -300 == wo) return 'America/Panama'; if (-240 == so && -300 == wo) return 'America/New_York'; if (-240 == so && -240 == wo) return 'America/Guyana'; if (-240 == so && -180 == wo) return 'America/Santiago'; if (-180 == so && -240 == wo) return 'America/Halifax'; if (-180 == so && -180 == wo) return 'America/Montevideo'; if (-180 == so && -120 == wo) return 'America/Sao_Paulo'; if (-150 == so && -210 == wo) return 'America/St_Johns'; if (-120 == so && -180 == wo) return 'America/Godthab'; if (-120 == so && -120 == wo) return 'America/Noronha'; if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde'; if (0 == so && -60 == wo) return 'Atlantic/Azores'; if (0 == so && 0 == wo) return 'Africa/Bamako'; if (60 == so && 0 == wo) return 'Europe/London'; if (60 == so && 60 == wo) return 'Africa/Algiers'; if (60 == so && 120 == wo) return 'Africa/Windhoek'; if (120 == so && 60 == wo) return 'Europe/Amsterdam'; if (120 == so && 120 == wo) return 'Africa/Johannesburg'; if (180 == so && 120 == wo) return 'Asia/Beirut'; if (180 == so && 180 == wo) return 'Africa/Nairobi'; if (240 == so && 180 == wo) return 'Europe/Moscow'; if (240 == so && 240 == wo) return 'Asia/Dubai'; if (270 == so && 210 == wo) return 'Asia/Tehran'; if (270 == so && 270 == wo) return 'Asia/Kabul'; if (300 == so && 240 == wo) return 'Asia/Yerevan'; if (300 == so && 300 == wo) return 'Asia/Tashkent'; if (330 == so && 330 == wo) return 'Asia/Calcutta'; if (345 == so && 345 == wo) return 'Asia/Katmandu'; if (360 == so && 300 == wo) return 'Asia/Yekaterinburg'; if (360 == so && 360 == wo) return 'Asia/Colombo'; if (390 == so && 390 == wo) return 'Asia/Rangoon'; if (420 == so && 360 == wo) return 'Asia/Novosibirsk'; if (420 == so && 420 == wo) return 'Asia/Bangkok'; if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk'; if (480 == so && 480 == wo) return 'Australia/Perth'; if (540 == so && 480 == wo) return 'Asia/Irkutsk'; if (540 == so && 540 == wo) return 'Asia/Tokyo'; if (570 == so && 570 == wo) return 'Australia/Darwin'; if (570 == so && 630 == wo) return 'Australia/Adelaide'; if (600 == so && 540 == wo) return 'Asia/Yakutsk'; if (600 == so && 600 == wo) return 'Australia/Brisbane'; if (600 == so && 660 == wo) return 'Australia/Sydney'; if (630 == so && 660 == wo) return 'Australia/Lord_Howe'; if (660 == so && 600 == wo) return 'Asia/Vladivostok'; if (660 == so && 660 == wo) return 'Pacific/Guadalcanal'; if (690 == so && 690 == wo) return 'Pacific/Norfolk'; if (720 == so && 660 == wo) return 'Asia/Magadan'; if (720 == so && 720 == wo) return 'Pacific/Fiji'; if (720 == so && 780 == wo) return 'Pacific/Auckland'; if (765 == so && 825 == wo) return 'Pacific/Chatham'; if (780 == so && 720 == wo) return 'Asia/Kamchatka'; if (780 == so && 780 == wo) return 'Pacific/Enderbury'; if (840 == so && 840 == wo) return 'Pacific/Kiritimati'; return 'America/Los_Angeles'; } // MES- set_select is a tiny helper that takes in the name of a select control // and the value of an item to be selected. It looks for an option in the // select with the indicated value. If found, it selects it and returns true. // If the item is not found, returns false. function
(ctrl, val) { opts = $(ctrl).options; for (var i = 0; i < opts.length; i++) { if (val == opts[i].value) { opts[i].selected = true; return true; } } return false; }
set_select
identifier_name
dom_blob.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMObject; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; glib_wrapper! { pub struct DOMBlob(Object<webkit2_webextension_sys::WebKitDOMBlob, webkit2_webextension_sys::WebKitDOMBlobClass, DOMBlobClass>) @extends DOMObject; match fn { get_type => || webkit2_webextension_sys::webkit_dom_blob_get_type(), } } pub const NONE_DOM_BLOB: Option<&DOMBlob> = None; pub trait DOMBlobExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_size(&self) -> u64; fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMBlob>> DOMBlobExt for O { fn get_size(&self) -> u64 { unsafe { webkit2_webextension_sys::webkit_dom_blob_get_size(self.as_ref().to_glib_none().0) } } fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_size_trampoline<P, F: Fn(&P) + 'static>(this: *mut webkit2_webextension_sys::WebKitDOMBlob, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer) where P: IsA<DOMBlob> { let f: &F = &*(f as *const F); f(&DOMBlob::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::size\0".as_ptr() as *const _, Some(transmute(notify_size_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } }
impl fmt::Display for DOMBlob { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMBlob") } }
random_line_split
dom_blob.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMObject; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; glib_wrapper! { pub struct DOMBlob(Object<webkit2_webextension_sys::WebKitDOMBlob, webkit2_webextension_sys::WebKitDOMBlobClass, DOMBlobClass>) @extends DOMObject; match fn { get_type => || webkit2_webextension_sys::webkit_dom_blob_get_type(), } } pub const NONE_DOM_BLOB: Option<&DOMBlob> = None; pub trait DOMBlobExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_size(&self) -> u64; fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMBlob>> DOMBlobExt for O { fn get_size(&self) -> u64 { unsafe { webkit2_webextension_sys::webkit_dom_blob_get_size(self.as_ref().to_glib_none().0) } } fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_size_trampoline<P, F: Fn(&P) + 'static>(this: *mut webkit2_webextension_sys::WebKitDOMBlob, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer) where P: IsA<DOMBlob> { let f: &F = &*(f as *const F); f(&DOMBlob::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::size\0".as_ptr() as *const _, Some(transmute(notify_size_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } } impl fmt::Display for DOMBlob { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
}
{ write!(f, "DOMBlob") }
identifier_body
dom_blob.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMObject; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; glib_wrapper! { pub struct DOMBlob(Object<webkit2_webextension_sys::WebKitDOMBlob, webkit2_webextension_sys::WebKitDOMBlobClass, DOMBlobClass>) @extends DOMObject; match fn { get_type => || webkit2_webextension_sys::webkit_dom_blob_get_type(), } } pub const NONE_DOM_BLOB: Option<&DOMBlob> = None; pub trait DOMBlobExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_size(&self) -> u64; fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMBlob>> DOMBlobExt for O { fn get_size(&self) -> u64 { unsafe { webkit2_webextension_sys::webkit_dom_blob_get_size(self.as_ref().to_glib_none().0) } } fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn
<P, F: Fn(&P) + 'static>(this: *mut webkit2_webextension_sys::WebKitDOMBlob, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer) where P: IsA<DOMBlob> { let f: &F = &*(f as *const F); f(&DOMBlob::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::size\0".as_ptr() as *const _, Some(transmute(notify_size_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } } impl fmt::Display for DOMBlob { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMBlob") } }
notify_size_trampoline
identifier_name
test_overview_example.py
__author__ = 'mpetyx' from unittest import TestCase import unittest import logging import sys from pyapi import API class TestpyAPI(TestCase): def setUp(self): # print "Setting up the coverage unit test for pyapi" self.document = API() self.api = API().parse(location="url", language="raml") def test_swagger_serialise(self):
def test_raml_serialise(self): self.assertEqual(self.api.serialise(language="raml"), {}, "RAML could not be serialised properly") def test_hydra_serialise(self): self.assertEqual(self.api.serialise(language="hydra"), {}, "Hydra could not be serialised properly") def test_blueprint_serialise(self): self.assertEqual(self.api.serialise(language="blueprint"), {}, "API blueprint could not be serialised properly") def test_query(self): # print "sample" self.assertEqual(1, 2, "There are not equal at all!") # ending the test def tearDown(self): """Cleaning up after the test""" self.log.debug("finalising the test") if __name__ == '__main__': logging.basicConfig(stream=sys.stderr) logging.getLogger("SomeTest.testSomething").setLevel(logging.DEBUG) unittest.main()
self.assertEqual(self.api.serialise(language="swagger"), {}, "Swagger could not be serialised properly")
identifier_body
test_overview_example.py
__author__ = 'mpetyx' from unittest import TestCase import unittest import logging import sys from pyapi import API class TestpyAPI(TestCase): def setUp(self): # print "Setting up the coverage unit test for pyapi" self.document = API() self.api = API().parse(location="url", language="raml") def test_swagger_serialise(self): self.assertEqual(self.api.serialise(language="swagger"), {}, "Swagger could not be serialised properly") def test_raml_serialise(self): self.assertEqual(self.api.serialise(language="raml"), {}, "RAML could not be serialised properly") def test_hydra_serialise(self): self.assertEqual(self.api.serialise(language="hydra"), {}, "Hydra could not be serialised properly") def
(self): self.assertEqual(self.api.serialise(language="blueprint"), {}, "API blueprint could not be serialised properly") def test_query(self): # print "sample" self.assertEqual(1, 2, "There are not equal at all!") # ending the test def tearDown(self): """Cleaning up after the test""" self.log.debug("finalising the test") if __name__ == '__main__': logging.basicConfig(stream=sys.stderr) logging.getLogger("SomeTest.testSomething").setLevel(logging.DEBUG) unittest.main()
test_blueprint_serialise
identifier_name
test_overview_example.py
__author__ = 'mpetyx' from unittest import TestCase import unittest import logging import sys from pyapi import API class TestpyAPI(TestCase): def setUp(self): # print "Setting up the coverage unit test for pyapi" self.document = API() self.api = API().parse(location="url", language="raml") def test_swagger_serialise(self): self.assertEqual(self.api.serialise(language="swagger"), {}, "Swagger could not be serialised properly") def test_raml_serialise(self): self.assertEqual(self.api.serialise(language="raml"), {}, "RAML could not be serialised properly") def test_hydra_serialise(self): self.assertEqual(self.api.serialise(language="hydra"), {}, "Hydra could not be serialised properly") def test_blueprint_serialise(self): self.assertEqual(self.api.serialise(language="blueprint"), {}, "API blueprint could not be serialised properly") def test_query(self): # print "sample" self.assertEqual(1, 2, "There are not equal at all!") # ending the test def tearDown(self): """Cleaning up after the test""" self.log.debug("finalising the test") if __name__ == '__main__':
logging.basicConfig(stream=sys.stderr) logging.getLogger("SomeTest.testSomething").setLevel(logging.DEBUG) unittest.main()
conditional_block
test_overview_example.py
__author__ = 'mpetyx' from unittest import TestCase import unittest import logging import sys from pyapi import API class TestpyAPI(TestCase): def setUp(self): # print "Setting up the coverage unit test for pyapi" self.document = API() self.api = API().parse(location="url", language="raml") def test_swagger_serialise(self): self.assertEqual(self.api.serialise(language="swagger"), {}, "Swagger could not be serialised properly") def test_raml_serialise(self): self.assertEqual(self.api.serialise(language="raml"), {}, "RAML could not be serialised properly") def test_hydra_serialise(self): self.assertEqual(self.api.serialise(language="hydra"), {}, "Hydra could not be serialised properly") def test_blueprint_serialise(self): self.assertEqual(self.api.serialise(language="blueprint"), {}, "API blueprint could not be serialised properly") def test_query(self): # print "sample" self.assertEqual(1, 2, "There are not equal at all!") # ending the test def tearDown(self): """Cleaning up after the test""" self.log.debug("finalising the test")
logging.basicConfig(stream=sys.stderr) logging.getLogger("SomeTest.testSomething").setLevel(logging.DEBUG) unittest.main()
if __name__ == '__main__':
random_line_split
models.py
from django.db import models from django.utils import timezone import pytz import datetime def hash(n): n = int(n) return ((0x0000FFFF & n)<<16) + ((0xFFFF0000 & n)>>16) class EventInstance(object): def __init__(self, event, event_time, date): self.date = date.date() self.time = date.time() self.event= event self.event_time = event_time self.attending = Signup.objects.filter(event=event, date=self.date, status=Signup.ATTENDING) self.not_attending = Signup.objects.filter(event=event, date=self.date, status=Signup.NOT_ATTENDING) def get_date_id(self): return "%4d_%02d_%02d" % (self.date.year, self.date.month, self.date.day) class Event(models.Model): name = models.CharField(max_length=100) timezone = models.CharField(max_length=50, choices=[(x,x) for x in pytz.all_timezones ], default="US/Mountain") description = models.TextField() location_lat = models.FloatField() location_lon = models.FloatField() addr = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=5) zip = models.CharField(max_length=20) contact_emails = models.CharField(max_length=500, help_text='Comma separated list of email addresses') def __unicode__(self): return self.name def get_next(self): timezone.activate(pytz.timezone(self.timezone)) now = timezone.now().date() events = [ EventInstance(self, d, d.get_next(now)) for d in self.times.all() ] events.sort(key=lambda x:x.date) return events class EventTime(models.Model): DAY_CHOICES = ( (0, "Monday", ), (1, "Tuesday", ), (2, "Wednesday",), (3, "Thursday", ), (4, "Friday", ), (5, "Saturday", ), (6, "Sunday", ), ) event= models.ForeignKey(Event, related_name="times") day = models.IntegerField(choices=DAY_CHOICES) time = models.TimeField() def get_next(self, now): dow = now.weekday() td = datetime.timedelta(days=(self.day - dow) % 7) next_date = now + td return datetime.datetime.combine(next_date, self.time) class Signup(models.Model): ATTENDING = 0 NOT_ATTENDING = 1 status_choices = ( ( ATTENDING , "I'm In", ), ( NOT_ATTENDING, "I'm Out", ), ) event = models.ForeignKey(Event, related_name="signups") date = models.DateField() name = models.CharField(max_length=100) status= models.IntegerField(choices=status_choices, blank=False, default=ATTENDING) def hash(self): return hash(self.pk) class Comment(models.Model): class Meta:
ordering = ["-timestamp"] event = models.ForeignKey(Event, related_name="comments") name = models.CharField(max_length=100) comment = models.TextField() timestamp = models.DateTimeField(auto_now_add=True)
random_line_split
models.py
from django.db import models from django.utils import timezone import pytz import datetime def hash(n): n = int(n) return ((0x0000FFFF & n)<<16) + ((0xFFFF0000 & n)>>16) class EventInstance(object): def __init__(self, event, event_time, date): self.date = date.date() self.time = date.time() self.event= event self.event_time = event_time self.attending = Signup.objects.filter(event=event, date=self.date, status=Signup.ATTENDING) self.not_attending = Signup.objects.filter(event=event, date=self.date, status=Signup.NOT_ATTENDING) def get_date_id(self): return "%4d_%02d_%02d" % (self.date.year, self.date.month, self.date.day) class Event(models.Model): name = models.CharField(max_length=100) timezone = models.CharField(max_length=50, choices=[(x,x) for x in pytz.all_timezones ], default="US/Mountain") description = models.TextField() location_lat = models.FloatField() location_lon = models.FloatField() addr = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=5) zip = models.CharField(max_length=20) contact_emails = models.CharField(max_length=500, help_text='Comma separated list of email addresses') def __unicode__(self): return self.name def get_next(self): timezone.activate(pytz.timezone(self.timezone)) now = timezone.now().date() events = [ EventInstance(self, d, d.get_next(now)) for d in self.times.all() ] events.sort(key=lambda x:x.date) return events class EventTime(models.Model): DAY_CHOICES = ( (0, "Monday", ), (1, "Tuesday", ), (2, "Wednesday",), (3, "Thursday", ), (4, "Friday", ), (5, "Saturday", ), (6, "Sunday", ), ) event= models.ForeignKey(Event, related_name="times") day = models.IntegerField(choices=DAY_CHOICES) time = models.TimeField() def get_next(self, now): dow = now.weekday() td = datetime.timedelta(days=(self.day - dow) % 7) next_date = now + td return datetime.datetime.combine(next_date, self.time) class Signup(models.Model): ATTENDING = 0 NOT_ATTENDING = 1 status_choices = ( ( ATTENDING , "I'm In", ), ( NOT_ATTENDING, "I'm Out", ), ) event = models.ForeignKey(Event, related_name="signups") date = models.DateField() name = models.CharField(max_length=100) status= models.IntegerField(choices=status_choices, blank=False, default=ATTENDING) def hash(self): return hash(self.pk) class
(models.Model): class Meta: ordering = ["-timestamp"] event = models.ForeignKey(Event, related_name="comments") name = models.CharField(max_length=100) comment = models.TextField() timestamp = models.DateTimeField(auto_now_add=True)
Comment
identifier_name
models.py
from django.db import models from django.utils import timezone import pytz import datetime def hash(n): n = int(n) return ((0x0000FFFF & n)<<16) + ((0xFFFF0000 & n)>>16) class EventInstance(object): def __init__(self, event, event_time, date): self.date = date.date() self.time = date.time() self.event= event self.event_time = event_time self.attending = Signup.objects.filter(event=event, date=self.date, status=Signup.ATTENDING) self.not_attending = Signup.objects.filter(event=event, date=self.date, status=Signup.NOT_ATTENDING) def get_date_id(self): return "%4d_%02d_%02d" % (self.date.year, self.date.month, self.date.day) class Event(models.Model): name = models.CharField(max_length=100) timezone = models.CharField(max_length=50, choices=[(x,x) for x in pytz.all_timezones ], default="US/Mountain") description = models.TextField() location_lat = models.FloatField() location_lon = models.FloatField() addr = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=5) zip = models.CharField(max_length=20) contact_emails = models.CharField(max_length=500, help_text='Comma separated list of email addresses') def __unicode__(self): return self.name def get_next(self): timezone.activate(pytz.timezone(self.timezone)) now = timezone.now().date() events = [ EventInstance(self, d, d.get_next(now)) for d in self.times.all() ] events.sort(key=lambda x:x.date) return events class EventTime(models.Model): DAY_CHOICES = ( (0, "Monday", ), (1, "Tuesday", ), (2, "Wednesday",), (3, "Thursday", ), (4, "Friday", ), (5, "Saturday", ), (6, "Sunday", ), ) event= models.ForeignKey(Event, related_name="times") day = models.IntegerField(choices=DAY_CHOICES) time = models.TimeField() def get_next(self, now): dow = now.weekday() td = datetime.timedelta(days=(self.day - dow) % 7) next_date = now + td return datetime.datetime.combine(next_date, self.time) class Signup(models.Model):
class Comment(models.Model): class Meta: ordering = ["-timestamp"] event = models.ForeignKey(Event, related_name="comments") name = models.CharField(max_length=100) comment = models.TextField() timestamp = models.DateTimeField(auto_now_add=True)
ATTENDING = 0 NOT_ATTENDING = 1 status_choices = ( ( ATTENDING , "I'm In", ), ( NOT_ATTENDING, "I'm Out", ), ) event = models.ForeignKey(Event, related_name="signups") date = models.DateField() name = models.CharField(max_length=100) status= models.IntegerField(choices=status_choices, blank=False, default=ATTENDING) def hash(self): return hash(self.pk)
identifier_body
date_and_time.py
"""Template filters and tags for helping with dates and datetimes""" # pylint: disable=W0702,C0103 from django import template from nav.django.settings import DATETIME_FORMAT, SHORT_TIME_FORMAT from django.template.defaultfilters import date, time from datetime import timedelta register = template.Library() @register.filter def
(value): """Returns the date as represented by the default datetime format""" try: v = date(value, DATETIME_FORMAT) except: return value return v @register.filter def short_time_format(value): """Returns the value formatted as a short time format The SHORT_TIME_FORMAT is a custom format not available in the template """ try: return time(value, SHORT_TIME_FORMAT) except: return value @register.filter def remove_microseconds(delta): """Removes microseconds from timedelta""" try: return delta - timedelta(microseconds=delta.microseconds) except: return delta
default_datetime
identifier_name
date_and_time.py
"""Template filters and tags for helping with dates and datetimes""" # pylint: disable=W0702,C0103 from django import template from nav.django.settings import DATETIME_FORMAT, SHORT_TIME_FORMAT from django.template.defaultfilters import date, time from datetime import timedelta register = template.Library() @register.filter
def default_datetime(value): """Returns the date as represented by the default datetime format""" try: v = date(value, DATETIME_FORMAT) except: return value return v @register.filter def short_time_format(value): """Returns the value formatted as a short time format The SHORT_TIME_FORMAT is a custom format not available in the template """ try: return time(value, SHORT_TIME_FORMAT) except: return value @register.filter def remove_microseconds(delta): """Removes microseconds from timedelta""" try: return delta - timedelta(microseconds=delta.microseconds) except: return delta
random_line_split
date_and_time.py
"""Template filters and tags for helping with dates and datetimes""" # pylint: disable=W0702,C0103 from django import template from nav.django.settings import DATETIME_FORMAT, SHORT_TIME_FORMAT from django.template.defaultfilters import date, time from datetime import timedelta register = template.Library() @register.filter def default_datetime(value): """Returns the date as represented by the default datetime format""" try: v = date(value, DATETIME_FORMAT) except: return value return v @register.filter def short_time_format(value):
@register.filter def remove_microseconds(delta): """Removes microseconds from timedelta""" try: return delta - timedelta(microseconds=delta.microseconds) except: return delta
"""Returns the value formatted as a short time format The SHORT_TIME_FORMAT is a custom format not available in the template """ try: return time(value, SHORT_TIME_FORMAT) except: return value
identifier_body
versions.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import pytest from spack.main import SpackCommand versions = SpackCommand('versions') def test_safe_only_versions(): """Only test the safe versions of a package. (Using the deprecated command line argument) """ versions('--safe-only', 'zlib') def test_safe_versions(): """Only test the safe versions of a package.""" versions('--safe', 'zlib') @pytest.mark.network def test_remote_versions(): """Test a package for which remote versions should be available.""" versions('zlib') @pytest.mark.network def test_remote_versions_only(): """Test a package for which remote versions should be available.""" versions('--remote', 'zlib') @pytest.mark.network @pytest.mark.usefixtures('mock_packages') def test_new_versions_only(): """Test a package for which new versions should be available.""" versions('--new', 'brillig') @pytest.mark.network def
(): """Test a package for which no remote versions are available.""" versions('converge') @pytest.mark.network def test_no_unchecksummed_versions(): """Test a package for which no unchecksummed versions are available.""" versions('bzip2') @pytest.mark.network def test_versions_no_url(): """Test a package with versions but without a ``url`` attribute.""" versions('graphviz') @pytest.mark.network def test_no_versions_no_url(): """Test a package without versions or a ``url`` attribute.""" versions('opengl')
test_no_versions
identifier_name
versions.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import pytest from spack.main import SpackCommand versions = SpackCommand('versions') def test_safe_only_versions(): """Only test the safe versions of a package. (Using the deprecated command line argument) """ versions('--safe-only', 'zlib') def test_safe_versions(): """Only test the safe versions of a package.""" versions('--safe', 'zlib') @pytest.mark.network def test_remote_versions(): """Test a package for which remote versions should be available.""" versions('zlib') @pytest.mark.network def test_remote_versions_only(): """Test a package for which remote versions should be available.""" versions('--remote', 'zlib') @pytest.mark.network @pytest.mark.usefixtures('mock_packages') def test_new_versions_only(): """Test a package for which new versions should be available.""" versions('--new', 'brillig') @pytest.mark.network def test_no_versions(): """Test a package for which no remote versions are available.""" versions('converge') @pytest.mark.network def test_no_unchecksummed_versions(): """Test a package for which no unchecksummed versions are available.""" versions('bzip2') @pytest.mark.network def test_versions_no_url(): """Test a package with versions but without a ``url`` attribute.""" versions('graphviz')
def test_no_versions_no_url(): """Test a package without versions or a ``url`` attribute.""" versions('opengl')
@pytest.mark.network
random_line_split
versions.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import pytest from spack.main import SpackCommand versions = SpackCommand('versions') def test_safe_only_versions(): """Only test the safe versions of a package. (Using the deprecated command line argument) """ versions('--safe-only', 'zlib') def test_safe_versions(): """Only test the safe versions of a package.""" versions('--safe', 'zlib') @pytest.mark.network def test_remote_versions():
@pytest.mark.network def test_remote_versions_only(): """Test a package for which remote versions should be available.""" versions('--remote', 'zlib') @pytest.mark.network @pytest.mark.usefixtures('mock_packages') def test_new_versions_only(): """Test a package for which new versions should be available.""" versions('--new', 'brillig') @pytest.mark.network def test_no_versions(): """Test a package for which no remote versions are available.""" versions('converge') @pytest.mark.network def test_no_unchecksummed_versions(): """Test a package for which no unchecksummed versions are available.""" versions('bzip2') @pytest.mark.network def test_versions_no_url(): """Test a package with versions but without a ``url`` attribute.""" versions('graphviz') @pytest.mark.network def test_no_versions_no_url(): """Test a package without versions or a ``url`` attribute.""" versions('opengl')
"""Test a package for which remote versions should be available.""" versions('zlib')
identifier_body
aria-props.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _ariaQuery = require("aria-query"); var _jsxAstUtils = require("jsx-ast-utils"); var _schemas = require("../util/schemas"); var _getSuggestion = _interopRequireDefault(require("../util/getSuggestion")); /** * @fileoverview Enforce all aria-* properties are valid. * @author Ethan Cohen */ // ---------------------------------------------------------------------------- // Rule Definition // ---------------------------------------------------------------------------- var ariaAttributes = (0, _toConsumableArray2["default"])(_ariaQuery.aria.keys()); var errorMessage = function errorMessage(name) { var suggestions = (0, _getSuggestion["default"])(name, ariaAttributes); var message = "".concat(name, ": This attribute is an invalid ARIA attribute."); if (suggestions.length > 0) { return "".concat(message, " Did you mean to use ").concat(suggestions, "?"); } return message; }; var schema = (0, _schemas.generateObjSchema)(); module.exports = { meta: { docs: { url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/aria-props.md' }, schema: [schema] }, create: function create(context) { return { JSXAttribute: function JSXAttribute(attribute) { var name = (0, _jsxAstUtils.propName)(attribute); // `aria` needs to be prefix of property. if (name.indexOf('aria-') !== 0) { return; } var isValid = ariaAttributes.indexOf(name) > -1; if (isValid === false)
} }; } };
{ context.report({ node: attribute, message: errorMessage(name) }); }
conditional_block
aria-props.js
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _ariaQuery = require("aria-query"); var _jsxAstUtils = require("jsx-ast-utils"); var _schemas = require("../util/schemas"); var _getSuggestion = _interopRequireDefault(require("../util/getSuggestion")); /** * @fileoverview Enforce all aria-* properties are valid. * @author Ethan Cohen */ // ---------------------------------------------------------------------------- // Rule Definition // ---------------------------------------------------------------------------- var ariaAttributes = (0, _toConsumableArray2["default"])(_ariaQuery.aria.keys()); var errorMessage = function errorMessage(name) { var suggestions = (0, _getSuggestion["default"])(name, ariaAttributes); var message = "".concat(name, ": This attribute is an invalid ARIA attribute."); if (suggestions.length > 0) { return "".concat(message, " Did you mean to use ").concat(suggestions, "?"); } return message; }; var schema = (0, _schemas.generateObjSchema)(); module.exports = { meta: { docs: { url: 'https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules/aria-props.md' }, schema: [schema] }, create: function create(context) { return { JSXAttribute: function JSXAttribute(attribute) { var name = (0, _jsxAstUtils.propName)(attribute); // `aria` needs to be prefix of property. if (name.indexOf('aria-') !== 0) { return; } var isValid = ariaAttributes.indexOf(name) > -1; if (isValid === false) { context.report({ node: attribute, message: errorMessage(name) }); } } }; } };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
random_line_split
conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # tritonschedule documentation build configuration file, created by # sphinx-quickstart on Wed Jun 22 11:40:06 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'tritonschedule' copyright = '2016, tritonschedule' author = 'tritonschedule' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '' # The full version, including alpha/beta/rc tags. release = '' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. # # html_title = 'tritonschedule v' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served.
# Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'tritonscheduledoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'tritonschedule.tex', 'tritonschedule Documentation', 'tritonschedule', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'tritonschedule', 'tritonschedule Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'tritonschedule', 'tritonschedule Documentation', author, 'tritonschedule', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = project # The HTML theme for the epub output. Since the default themes are not # optimized for small screen space, using the same theme for HTML and epub # output is usually not wise. This defaults to 'epub', a theme designed to save # visual space. # # epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. # # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. # # epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. # # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. # # epub_tocdepth = 3 # Allow duplicate toc entries. # # epub_tocdup = True # Choose between 'default' and 'includehidden'. # # epub_tocscope = 'default' # Fix unsupported image types using the Pillow. # # epub_fix_images = False # Scale large images. # # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # # epub_show_urls = 'inline' # If false, no index is generated. # # epub_use_index = True
# # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None
random_line_split
tracker.js
(function() { "use strict"; window.GOVUK = window.GOVUK || {}; // For usage and initialisation see: // https://github.com/alphagov/govuk_frontend_toolkit/blob/master/docs/analytics.md#create-an-analytics-tracker var Tracker = function(config) { this.trackers = []; if (typeof config.universalId != 'undefined') { this.trackers.push(new GOVUK.GoogleAnalyticsUniversalTracker(config.universalId, config.cookieDomain)); } if (typeof config.classicId != 'undefined') { this.trackers.push(new GOVUK.GoogleAnalyticsClassicTracker(config.classicId, config.cookieDomain)); } }; Tracker.load = function() { GOVUK.GoogleAnalyticsClassicTracker.load(); GOVUK.GoogleAnalyticsUniversalTracker.load(); }; Tracker.prototype.trackPageview = function(path, title) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].trackPageview(path, title); } }; /* https://developers.google.com/analytics/devguides/collection/analyticsjs/events options.label – Useful for categorizing events (eg nav buttons) options.value – Values must be non-negative. Useful to pass counts options.nonInteraction – Prevent event from impacting bounce rate */ Tracker.prototype.trackEvent = function(category, action, options) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].trackEvent(category, action, options); } };
} }; /* Assumes that the index of the dimension is the same for both classic and universal. Check this for your app before using this */ Tracker.prototype.setDimension = function(index, value, name, scope) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].setDimension(index, value, name, scope); } }; /* Add a beacon to track a page in another GA account on another domain. */ Tracker.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].addLinkedTrackerDomain(trackerId, name, domain); } }; GOVUK.Tracker = Tracker; })();
Tracker.prototype.trackShare = function(network) { var target = location.pathname; for (var i=0; i < this.trackers.length; i++) { this.trackers[i].trackSocial(network, 'share', target);
random_line_split
tracker.js
(function() { "use strict"; window.GOVUK = window.GOVUK || {}; // For usage and initialisation see: // https://github.com/alphagov/govuk_frontend_toolkit/blob/master/docs/analytics.md#create-an-analytics-tracker var Tracker = function(config) { this.trackers = []; if (typeof config.universalId != 'undefined') { this.trackers.push(new GOVUK.GoogleAnalyticsUniversalTracker(config.universalId, config.cookieDomain)); } if (typeof config.classicId != 'undefined') { this.trackers.push(new GOVUK.GoogleAnalyticsClassicTracker(config.classicId, config.cookieDomain)); } }; Tracker.load = function() { GOVUK.GoogleAnalyticsClassicTracker.load(); GOVUK.GoogleAnalyticsUniversalTracker.load(); }; Tracker.prototype.trackPageview = function(path, title) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].trackPageview(path, title); } }; /* https://developers.google.com/analytics/devguides/collection/analyticsjs/events options.label – Useful for categorizing events (eg nav buttons) options.value – Values must be non-negative. Useful to pass counts options.nonInteraction – Prevent event from impacting bounce rate */ Tracker.prototype.trackEvent = function(category, action, options) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].trackEvent(category, action, options); } }; Tracker.prototype.trackShare = function(network) { var target = location.pathname; for (var i=0; i < this.trackers.length; i++) {
/* Assumes that the index of the dimension is the same for both classic and universal. Check this for your app before using this */ Tracker.prototype.setDimension = function(index, value, name, scope) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].setDimension(index, value, name, scope); } }; /* Add a beacon to track a page in another GA account on another domain. */ Tracker.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) { for (var i=0; i < this.trackers.length; i++) { this.trackers[i].addLinkedTrackerDomain(trackerId, name, domain); } }; GOVUK.Tracker = Tracker; })();
this.trackers[i].trackSocial(network, 'share', target); } };
conditional_block
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { Ng2BootstrapModule } from 'ng2-bootstrap'; import { AlertModule } from 'ng2-bootstrap'; import { AppRoutingModule } from './app.routing.module' //import { UPLOAD_DIRECTIVES } from 'ng2-uploader/ng2-uploader'; import { Ng2UploaderModule } from 'ng2-uploader' import { MapIteratorPipe } from './shared'; import '../styles.scss'; import { NavigationComponent } from './navigation/navigation.component'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { CallbackComponent } from './callback/callback.component'; import { UploadComponent } from './upload/upload.component'; import { SettingsComponent } from './settings/settings.component'; import { AdminComponent } from './admin/admin.component'; //services import { USERSERVICE, MockUserService, UserService } from './services'; import { NotEnoughRightsComponent } from './not-enough-rights/not-enough-rights.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, MapIteratorPipe, NavigationComponent, CallbackComponent, UploadComponent, SettingsComponent, AdminComponent, NotEnoughRightsComponent ], imports: [ Ng2UploaderModule, Ng2BootstrapModule, AlertModule, BrowserModule, FormsModule, HttpModule, AppRoutingModule ], providers: [ { provide: USERSERVICE, useClass: UserService } ], bootstrap: [AppComponent] }) export class
{ }
AppModule
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { Ng2BootstrapModule } from 'ng2-bootstrap'; import { AlertModule } from 'ng2-bootstrap'; import { AppRoutingModule } from './app.routing.module' //import { UPLOAD_DIRECTIVES } from 'ng2-uploader/ng2-uploader'; import { Ng2UploaderModule } from 'ng2-uploader' import { MapIteratorPipe } from './shared'; import '../styles.scss'; import { NavigationComponent } from './navigation/navigation.component'; import { AppComponent } from './app.component';
import { AdminComponent } from './admin/admin.component'; //services import { USERSERVICE, MockUserService, UserService } from './services'; import { NotEnoughRightsComponent } from './not-enough-rights/not-enough-rights.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, MapIteratorPipe, NavigationComponent, CallbackComponent, UploadComponent, SettingsComponent, AdminComponent, NotEnoughRightsComponent ], imports: [ Ng2UploaderModule, Ng2BootstrapModule, AlertModule, BrowserModule, FormsModule, HttpModule, AppRoutingModule ], providers: [ { provide: USERSERVICE, useClass: UserService } ], bootstrap: [AppComponent] }) export class AppModule { }
import { HomeComponent } from './home/home.component'; import { CallbackComponent } from './callback/callback.component'; import { UploadComponent } from './upload/upload.component'; import { SettingsComponent } from './settings/settings.component';
random_line_split
ipttProgram.test.js
import IPTTProgram, { forIPTT } from '../models/ipttProgram'; describe("bare iptt program", () => { const Program = forIPTT; it("handles frequencies", () => { let program = Program({frequencies: [3, 4]}); expect(program.validFrequency(3)).toBeTruthy(); expect(program.validFrequency(2)).toBeFalsy(); let program2 = Program({frequencies: []}); expect(program2.validFrequency(3)).toBeFalsy(); }); it("handles disaggregations", () => { let program = Program({disaggregations: [{pk: 4, name: 'Test Disaggregation', labels: [{pk: '10', name: "banana"}]}]}); expect(Array.from(program.disaggregations.values())).toStrictEqual([{pk: 4, name: 'Test Disaggregation', labels: [{pk: 10, name: "banana"}], country: null}]);
let program = Program({disaggregations: [{pk: 4, name: 'Test Disaggregation', labels: []}]}); expect(Array.from(program.disaggregations.values())).toStrictEqual([]); }); });
}); it("doesn't show category-less disaggregations", () => {
random_line_split
vec.rs
#[no_std]; #[no_core]; use zero; pub trait OwnedVector<T> { unsafe fn push_fast(&mut self, t: T); unsafe fn len(&self) -> uint; unsafe fn set_len(&mut self, newlen: uint); unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U; unsafe fn data(&self) -> *u8; } pub struct Vec<T> { fill: uint, alloc: uint, data: T } impl<T> OwnedVector<T> for ~[T] { //FIXME: Does not check to see if we have space // See: https://github.com/mozilla/rust/blob/master/src/libstd/vec.rs#L1317 unsafe fn
(&mut self, t: T) { let repr: **mut Vec<u8> = zero::transmute(self); let fill = (**repr).fill; (**repr).fill += zero::size_of::<T>(); let p = &(**repr).data as *u8 as uint; let mut i = 0; while i < zero::size_of::<T>() { *((p+fill+i) as *mut u8) = *((&t as *T as uint + i) as *mut u8); i += 1; } } unsafe fn len(&self) -> uint { let repr: **Vec<u8> = zero::transmute(self); ((**repr).fill / zero::size_of::<T>()) as uint } unsafe fn set_len(&mut self, newlen: uint) { let repr: **mut Vec<u8> = zero::transmute(self); (**repr).fill = zero::size_of::<T>() * newlen; } unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U { let repr: **mut Vec<T> = zero::transmute(self); f(&mut (**repr).data as *mut T, (**repr).fill / zero::size_of::<T>()) } unsafe fn data(&self) -> *u8 { let repr: **mut Vec<u8> = zero::transmute(self); &(**repr).data as *u8 } }
push_fast
identifier_name
vec.rs
#[no_std]; #[no_core]; use zero; pub trait OwnedVector<T> { unsafe fn push_fast(&mut self, t: T); unsafe fn len(&self) -> uint; unsafe fn set_len(&mut self, newlen: uint); unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U; unsafe fn data(&self) -> *u8; } pub struct Vec<T> { fill: uint, alloc: uint, data: T } impl<T> OwnedVector<T> for ~[T] { //FIXME: Does not check to see if we have space // See: https://github.com/mozilla/rust/blob/master/src/libstd/vec.rs#L1317 unsafe fn push_fast(&mut self, t: T)
unsafe fn len(&self) -> uint { let repr: **Vec<u8> = zero::transmute(self); ((**repr).fill / zero::size_of::<T>()) as uint } unsafe fn set_len(&mut self, newlen: uint) { let repr: **mut Vec<u8> = zero::transmute(self); (**repr).fill = zero::size_of::<T>() * newlen; } unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U { let repr: **mut Vec<T> = zero::transmute(self); f(&mut (**repr).data as *mut T, (**repr).fill / zero::size_of::<T>()) } unsafe fn data(&self) -> *u8 { let repr: **mut Vec<u8> = zero::transmute(self); &(**repr).data as *u8 } }
{ let repr: **mut Vec<u8> = zero::transmute(self); let fill = (**repr).fill; (**repr).fill += zero::size_of::<T>(); let p = &(**repr).data as *u8 as uint; let mut i = 0; while i < zero::size_of::<T>() { *((p+fill+i) as *mut u8) = *((&t as *T as uint + i) as *mut u8); i += 1; } }
identifier_body
vec.rs
#[no_std]; #[no_core]; use zero; pub trait OwnedVector<T> { unsafe fn push_fast(&mut self, t: T); unsafe fn len(&self) -> uint; unsafe fn set_len(&mut self, newlen: uint); unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U; unsafe fn data(&self) -> *u8; } pub struct Vec<T> { fill: uint, alloc: uint, data: T } impl<T> OwnedVector<T> for ~[T] { //FIXME: Does not check to see if we have space // See: https://github.com/mozilla/rust/blob/master/src/libstd/vec.rs#L1317 unsafe fn push_fast(&mut self, t: T) { let repr: **mut Vec<u8> = zero::transmute(self); let fill = (**repr).fill; (**repr).fill += zero::size_of::<T>(); let p = &(**repr).data as *u8 as uint; let mut i = 0; while i < zero::size_of::<T>() { *((p+fill+i) as *mut u8) = *((&t as *T as uint + i) as *mut u8); i += 1; } } unsafe fn len(&self) -> uint { let repr: **Vec<u8> = zero::transmute(self); ((**repr).fill / zero::size_of::<T>()) as uint
} unsafe fn set_len(&mut self, newlen: uint) { let repr: **mut Vec<u8> = zero::transmute(self); (**repr).fill = zero::size_of::<T>() * newlen; } unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U { let repr: **mut Vec<T> = zero::transmute(self); f(&mut (**repr).data as *mut T, (**repr).fill / zero::size_of::<T>()) } unsafe fn data(&self) -> *u8 { let repr: **mut Vec<u8> = zero::transmute(self); &(**repr).data as *u8 } }
random_line_split
plugin_asset_util.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. # ============================================================================== """Load plugin assets from disk.""" import os.path from tensorboard.compat import tf _PLUGINS_DIR = "plugins" def
(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item)) def PluginDirectory(logdir, plugin_name): """Returns the plugin directory for plugin_name.""" return os.path.join(logdir, _PLUGINS_DIR, plugin_name) def ListPlugins(logdir): """List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintains compatibility with old directories that have no plugins written. Args: logdir: A directory that was created by a TensorFlow events writer. Returns: a list of plugin names, as strings """ plugins_dir = os.path.join(logdir, _PLUGINS_DIR) try: entries = tf.io.gfile.listdir(plugins_dir) except tf.errors.NotFoundError: return [] # Strip trailing slashes, which listdir() includes for some filesystems # for subdirectories, after using them to bypass IsDirectory(). return [ x.rstrip("/") for x in entries if x.endswith("/") or _IsDirectory(plugins_dir, x) ] def ListAssets(logdir, plugin_name): """List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: A string name of a plugin to list assets for. Returns: A string list of available plugin assets. If the plugin subdirectory does not exist (either because the logdir doesn't exist, or because the plugin didn't register) an empty list is returned. """ plugin_dir = PluginDirectory(logdir, plugin_name) try: # Strip trailing slashes, which listdir() includes for some filesystems. return [x.rstrip("/") for x in tf.io.gfile.listdir(plugin_dir)] except tf.errors.NotFoundError: return [] def RetrieveAsset(logdir, plugin_name, asset_name): """Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: The plugin we want an asset from. asset_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the asset does not exist. """ asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name) try: with tf.io.gfile.GFile(asset_path, "r") as f: return f.read() except tf.errors.NotFoundError: raise KeyError("Asset path %s not found" % asset_path) except tf.errors.OpError as e: raise KeyError( "Couldn't read asset path: %s, OpError %s" % (asset_path, e) )
_IsDirectory
identifier_name
plugin_asset_util.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. # ============================================================================== """Load plugin assets from disk.""" import os.path from tensorboard.compat import tf _PLUGINS_DIR = "plugins" def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item)) def PluginDirectory(logdir, plugin_name): """Returns the plugin directory for plugin_name.""" return os.path.join(logdir, _PLUGINS_DIR, plugin_name) def ListPlugins(logdir): """List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintains compatibility with old directories that have no plugins written. Args: logdir: A directory that was created by a TensorFlow events writer. Returns: a list of plugin names, as strings """ plugins_dir = os.path.join(logdir, _PLUGINS_DIR) try: entries = tf.io.gfile.listdir(plugins_dir) except tf.errors.NotFoundError: return [] # Strip trailing slashes, which listdir() includes for some filesystems # for subdirectories, after using them to bypass IsDirectory(). return [ x.rstrip("/") for x in entries if x.endswith("/") or _IsDirectory(plugins_dir, x) ] def ListAssets(logdir, plugin_name):
def RetrieveAsset(logdir, plugin_name, asset_name): """Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: The plugin we want an asset from. asset_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the asset does not exist. """ asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name) try: with tf.io.gfile.GFile(asset_path, "r") as f: return f.read() except tf.errors.NotFoundError: raise KeyError("Asset path %s not found" % asset_path) except tf.errors.OpError as e: raise KeyError( "Couldn't read asset path: %s, OpError %s" % (asset_path, e) )
"""List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: A string name of a plugin to list assets for. Returns: A string list of available plugin assets. If the plugin subdirectory does not exist (either because the logdir doesn't exist, or because the plugin didn't register) an empty list is returned. """ plugin_dir = PluginDirectory(logdir, plugin_name) try: # Strip trailing slashes, which listdir() includes for some filesystems. return [x.rstrip("/") for x in tf.io.gfile.listdir(plugin_dir)] except tf.errors.NotFoundError: return []
identifier_body
plugin_asset_util.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. # ============================================================================== """Load plugin assets from disk.""" import os.path from tensorboard.compat import tf _PLUGINS_DIR = "plugins" def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item)) def PluginDirectory(logdir, plugin_name): """Returns the plugin directory for plugin_name.""" return os.path.join(logdir, _PLUGINS_DIR, plugin_name) def ListPlugins(logdir): """List all the plugins that have registered assets in logdir. If the plugins_dir does not exist, it returns an empty list. This maintains compatibility with old directories that have no plugins written. Args: logdir: A directory that was created by a TensorFlow events writer. Returns: a list of plugin names, as strings """ plugins_dir = os.path.join(logdir, _PLUGINS_DIR) try: entries = tf.io.gfile.listdir(plugins_dir) except tf.errors.NotFoundError: return [] # Strip trailing slashes, which listdir() includes for some filesystems # for subdirectories, after using them to bypass IsDirectory(). return [ x.rstrip("/") for x in entries if x.endswith("/") or _IsDirectory(plugins_dir, x) ] def ListAssets(logdir, plugin_name): """List all the assets that are available for given plugin in a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: A string name of a plugin to list assets for. Returns: A string list of available plugin assets. If the plugin subdirectory does not exist (either because the logdir doesn't exist, or because the plugin didn't register) an empty list is returned. """ plugin_dir = PluginDirectory(logdir, plugin_name) try: # Strip trailing slashes, which listdir() includes for some filesystems. return [x.rstrip("/") for x in tf.io.gfile.listdir(plugin_dir)] except tf.errors.NotFoundError: return [] def RetrieveAsset(logdir, plugin_name, asset_name): """Retrieve a particular plugin asset from a logdir. Args: logdir: A directory that was created by a TensorFlow summary.FileWriter. plugin_name: The plugin we want an asset from. asset_name: The name of the requested asset. Returns: string contents of the plugin asset. Raises: KeyError: if the asset does not exist. """
asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name) try: with tf.io.gfile.GFile(asset_path, "r") as f: return f.read() except tf.errors.NotFoundError: raise KeyError("Asset path %s not found" % asset_path) except tf.errors.OpError as e: raise KeyError( "Couldn't read asset path: %s, OpError %s" % (asset_path, e) )
random_line_split
gulpfile.js
var gulp = require('gulp'), plumber = require('gulp-plumber'), browserify = require('gulp-browserify'), concat = require('gulp-concat'), gulpif = require('gulp-if'), uglify = require('gulp-uglify'), jshint = require('gulp-jshint'), stylish = require('jshint-stylish'), sequence = require('run-sequence'), less = require('gulp-less'), zip = require('gulp-zip'), rev = require('gulp-rev-append'), gutil = require('gulp-util'); var production = gutil.env.type === "production"; var game_name = gutil.env.name || 'fp' var paths = { source: { canvas_js: './app/js/' + game_name + '/canvas.js', web_js: './app/js/' + game_name + '/web.js', canvas_css: './app/less/' + game_name + '/canvas.less', web_css: './app/less/' + game_name + '/web.less', baseJsDir: './app/js/**', js: './app/js/**/*.js', css: './app/less/**/*.less', libs: [ './bower_components/phaser/build/phaser.js' ] }, dest: { base: './public/' + game_name + '/', html: './public/' + game_name + '/index.html', js: './public/' + game_name + '/js', css: './public/' + game_name + '/css' } }; gulp.task('rev', function() { gulp.src(paths.dest.html) .pipe(rev()) .pipe(gulp.dest(paths.dest.base)); }); gulp.task('copy_libs', function () { gulp.src(paths.source.libs) .pipe(uglify({outSourceMaps: false})) .pipe(gulp.dest(paths.dest.js)); }); gulp.task('canvas_js', function() { gulp.src(paths.source.canvas_js) .pipe(plumber()) .pipe(browserify()) .pipe(concat('canvas.js')) .pipe(gulpif(production, uglify())) .pipe(gulp.dest(paths.dest.js)); }); gulp.task('web_js', function() { gulp.src(paths.source.web_js) .pipe(plumber()) .pipe(browserify()) .pipe(concat('web.js')) .pipe(gulpif(production, uglify())) .pipe(gulp.dest(paths.dest.js)); }); gulp.task('canvas_css', function() { gulp.src(paths.source.canvas_css) .pipe(plumber()) .pipe(less({ compress: true })) .pipe(gulp.dest(paths.dest.css)); }); gulp.task('web_css', function() { gulp.src(paths.source.web_css) .pipe(plumber()) .pipe(less({ compress: true })) .pipe(gulp.dest(paths.dest.css)); }); gulp.task('lint', function() { gulp.src(paths.source.js) .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('watch', function() { gulp.watch(paths.source.baseJsDir, function() { sequence('canvas_js', 'web_js', 'lint') }); gulp.watch(paths.source.css, function() { sequence('canvas_css', 'web_css') }) }); gulp.task('zip', function () { return gulp.src([ 'public/' + game_name + '/**/*' ]) .pipe(zip(game_name +'_dist.zip')) .pipe(gulp.dest('./dist')) }); gulp.task('build', [ 'canvas_js', 'web_js',
]);
'canvas_css', 'web_css', 'rev'
random_line_split
karma.conf.js
// Karma configuration // Generated on Mon Jul 21 2014 11:48:34 GMT+0200 (CEST) module.exports = function (config) { config.set({ // base path used to resolve all patterns (e.g. files, exclude) basePath: '', // frameworks to use
frameworks: ['mocha', 'chai-sinon'], // list of files / patterns to load in the browser files: [ //start-vendor //end-vendor 'app/bower_components/jassa/jassa.js', 'app/bower_components/Blob.js/Blob.js', 'app/**/angular-mocks.js', //start-app //end-app 'node_modules/chai-string/chai-string.js', 'app/**/*.spec.js' ], // list of files to exclude exclude: [ 'app/bower_components/**/*.spec.js' ], // preprocess matching files before serving them to the browser preprocessors: { 'app/!(bower_components)/**/!(*spec).js': ['coverage'] }, coverageReporter: { type: 'html', dir: '.tmp/coverage/' }, // test results reporter to use reporters: ['progress', 'coverage'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging logLevel: config.LOG_INFO, // enable / disable watching file and executing tests on file changes autoWatch: true, // start these browsers browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
random_line_split
issue-17651.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that moves of unsized values within closures are caught // and rejected. fn main()
{ // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. (|| Box::new(*(&[0][..])))(); //~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[_]` }
identifier_body
issue-17651.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that moves of unsized values within closures are caught // and rejected. fn
() { // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. (|| Box::new(*(&[0][..])))(); //~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[_]` }
main
identifier_name
datastructures.rs
use std::iter; use std::ops::{Index, IndexMut}; pub type Idx = [u32; 2]; #[derive(Debug)] pub struct Matrix<T> { shape: Idx, data: Vec<Vec<T>> } impl<T: Copy> Matrix<T> { pub fn fill(shape: Idx, value: T) -> Matrix<T> { let data = (0..shape[0]).map(|_| { iter::repeat(value).take(shape[1] as usize) .collect::<Vec<_>>() }).collect::<Vec<_>>(); Matrix { shape: shape, data: data } } pub fn iter<'a>(&'a self) -> Box<Iterator<Item=(Idx, T)> + 'a> { Box::new((0..self.height()).flat_map(move |y| { (0..self.width()).map(move |x| ([x, y], self[[x, y]])) })) } } impl<T> Matrix<T> { pub fn width(&self) -> u32 { self.shape[0] } pub fn height(&self) -> u32 { self.shape[1] } } impl<T> Index<Idx> for Matrix<T> { type Output = T; fn index(&self, index: Idx) -> &T {
} } impl<T> IndexMut<Idx> for Matrix<T> { fn index_mut(&mut self, index: Idx) -> &mut T { let (x, y) = (index[0], index[1]); assert!(x < self.width() && y < self.height()); &mut self.data[x as usize][y as usize] } }
let (x, y) = (index[0], index[1]); assert!(x < self.width() && y < self.height()); &self.data[x as usize][y as usize]
random_line_split
datastructures.rs
use std::iter; use std::ops::{Index, IndexMut}; pub type Idx = [u32; 2]; #[derive(Debug)] pub struct
<T> { shape: Idx, data: Vec<Vec<T>> } impl<T: Copy> Matrix<T> { pub fn fill(shape: Idx, value: T) -> Matrix<T> { let data = (0..shape[0]).map(|_| { iter::repeat(value).take(shape[1] as usize) .collect::<Vec<_>>() }).collect::<Vec<_>>(); Matrix { shape: shape, data: data } } pub fn iter<'a>(&'a self) -> Box<Iterator<Item=(Idx, T)> + 'a> { Box::new((0..self.height()).flat_map(move |y| { (0..self.width()).map(move |x| ([x, y], self[[x, y]])) })) } } impl<T> Matrix<T> { pub fn width(&self) -> u32 { self.shape[0] } pub fn height(&self) -> u32 { self.shape[1] } } impl<T> Index<Idx> for Matrix<T> { type Output = T; fn index(&self, index: Idx) -> &T { let (x, y) = (index[0], index[1]); assert!(x < self.width() && y < self.height()); &self.data[x as usize][y as usize] } } impl<T> IndexMut<Idx> for Matrix<T> { fn index_mut(&mut self, index: Idx) -> &mut T { let (x, y) = (index[0], index[1]); assert!(x < self.width() && y < self.height()); &mut self.data[x as usize][y as usize] } }
Matrix
identifier_name