file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
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<Blueprin...
}
{ 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.tr...
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<Blueprin...
}
} }
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<Blueprin...
} }
{ 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<Blueprin...
(): void{ logger.debug("build: "+ this.key); let unresolvedDependencies = this.tryResolveDependencies(); if (unresolvedDependencies.length !== 0){ this.deferDependencyResolution(unresolvedDependencies); } else { this._isReady = true; } ...
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:...
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: ...
, 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; ...
{ 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 HTMLE...
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: ...
}, 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.c...
{ (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: ...
Object.defineProperty(element, '_scrollToCallback', { value: _scrollToCallback }); element.addEventListener('touchstart', _scrollToCallback.callBack); element.addEventListener('click', _scrollToCallback.callBack); }, update(element: HTMLElement, binding: VNodeDirect...
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: AnimationPl...
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: AnimationPl...
(): 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....
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: AnimationPl...
else { this._players.forEach(player => { player.parentPlayer = this; player.onDone(() => { if (++count >= total) { this._onFinish(); } }); }); } } private _onFinish() { if (!this._finished) { this._finished = true; if (!isPres...
{ 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: AnimationPl...
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...
{ 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"...
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_sa...
("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"...
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_...
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"...
(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( ...
_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.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_l...
_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'), envir...
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) { ...
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'), envir...
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) { ...
{ 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'), envir...
} }
{ 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); } ...
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'), envir...
(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)...
errorHandler
identifier_name
integration_tests.py
: 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=...
_load_module_configs
identifier_name
integration_tests.py
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_test...
flags: Optional[list[str]] = typer.Argument(None), editable: Optional[bool] = None, extra_module: Optional[list[str]] = None,
random_line_split
integration_tests.py
_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: serve...
"""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
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] = ser...
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): d...
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 ...
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): d...
(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_o...
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...
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" ], ...
{ 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_pre...
"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" }, "N...
"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_pre...
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": [ ...
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 = {...
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 = {...
{ 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(documen...
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 = {...
(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(local...
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 = {...
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, sessionStorag...
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 i...
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 || {}; //------------------------------------------------------------...
}); 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: '...
{ 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 @Inpu...
(): 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 ma...
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 @Inpu...
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() ...
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 @Inpu...
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)...
{ 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 @Inpu...
} @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(...
{ 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() ...
identifier_body
process_warnings.py
-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"...
(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_ind...
convert_warning_dict_to_list
identifier_name
process_warnings.py
-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"...
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): """ con...
temp_list_to_sort = []
random_line_split
process_warnings.py
-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"...
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="c...
""" 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 fou...
identifier_body
process_warnings.py
-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"...
# 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("/") ...
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 ...
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 do...
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::...
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 do...
(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<S...
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 do...
#[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<Prom...
{ 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 #========================================================================...
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 #=======================================================================...
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 #=======================================================================...
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 #=======================================================================...
(): 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::TestWorkletGlobalScopeBin...
} /// 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::TestWorkletGlobalScopeBin...
{ 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::TestWorkletGlobalScopeBin...
}); 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 = sel...
random_line_split
_vbscript.py
############################################################################### # Name: vbscript.py # # Purpose: Define VBScript syntax for highlighting and other features # # Author: Cody Precord <cprecord@editra.org> # ...
(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 SY...
__init__
identifier_name
_vbscript.py
############################################################################### # Name: vbscript.py # # Purpose: Define VBScript syntax for highlighting and other features # # Author: Cody Precord <cprecord@editra.org> # ...
(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_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> # ...
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 G...
syndata.SyntaxDataBase.__init__(self, langid) # Setup self.SetLexer(stc.STC_LEX_VBSCRIPT)
identifier_body
tz.js
, 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...
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...
{ 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 'Pa...
identifier_body
tz.js
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 arra...
opts[i].selected = true; return true; } } return false;
random_line_split
tz.js
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 di...
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::...
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::...
}
{ 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::...
<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 { ...
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="ram...
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_serial...
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="ram...
(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): ...
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="ram...
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="ram...
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(...
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(...
(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(...
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...
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() @registe...
(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 cu...
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() @registe...
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...
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() @registe...
@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(): ...
(): """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(): """Tes...
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(): ...
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(): ...
@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 availab...
"""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("../...
} }; } };
{ 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")); /** ...
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
random_line_split
conf.py
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 = ...
# 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 ...
# # 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 != 'u...
} }; /* 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(ind...
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 != 'u...
/* 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, ...
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...
{ }
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...
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, MapIteratorPip...
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))....
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:...
(&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...
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:...
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; } ...
{ 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 *...
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:...
} 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 (**re...
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 applica...
(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): ...
_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 applica...
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: ...
"""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...
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 applica...
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 ...
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(...
]);
'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', ...
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 ...
{ // 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 ...
() { // 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...
} } 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 { ...
Matrix
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>
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...
{ let data = (0..shape[0]).map(|_| { iter::repeat(value).take(shape[1] as usize) .collect::<Vec<_>>() }).collect::<Vec<_>>(); Matrix { shape: shape, data: data } }
identifier_body