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
FromEventPatternObservable.ts
import { isFunction } from '../util/isFunction'; import { Observable } from '../Observable'; import { Subscription } from '../Subscription'; import { Subscriber } from '../Subscriber'; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export class FromEventPatternObservable...
(handler: (e: any) => void, errorSubscriber: Subscriber<T>): any | null { try { return this.addHandler(handler) || null; } catch (e) { errorSubscriber.error(e); } } }
_callAddHandler
identifier_name
FromEventPatternObservable.ts
import { isFunction } from '../util/isFunction'; import { Observable } from '../Observable'; import { Subscription } from '../Subscription'; import { Subscriber } from '../Subscriber'; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export class FromEventPatternObservable...
const removeHandler = this.removeHandler; const handler = !!this.selector ? (...args: Array<any>) => { this._callSelector(subscriber, args); } : function(e: any) { subscriber.next(e); }; const retValue = this._callAddHandler(handler, subscriber); if (!isFunction(removeHandler)) { retu...
/** @deprecated internal use only */ _subscribe(subscriber: Subscriber<T>) {
random_line_split
ComboBoxMixin.js
define([ "dojo/_base/declare", // declare "dojo/Deferred", "dojo/_base/kernel", // kernel.deprecated "dojo/_base/lang", // lang.mixin "dojo/store/util/QueryResults", "./_AutoCompleterMixin", "./_ComboBoxMenu", "../_HasDropDown", "dojo/text!./templates/DropDownBox.html" ], function(declare, Deferred, kernel, la...
_showResultList: function(){ // hide the tooltip this.displayMessage(""); this.inherited(arguments); }, _setStoreAttr: function(store){ // For backwards-compatibility, accept dojo.data store in addition to dojo/store/api/Store. Remove in 2.0. if(!store.get){ lang.mixin(store, { _oldAPI: ...
random_line_split
ComboBoxMixin.js
define([ "dojo/_base/declare", // declare "dojo/Deferred", "dojo/_base/kernel", // kernel.deprecated "dojo/_base/lang", // lang.mixin "dojo/store/util/QueryResults", "./_AutoCompleterMixin", "./_ComboBoxMenu", "../_HasDropDown", "dojo/text!./templates/DropDownBox.html" ], function(declare, Deferred, kernel, la...
} }); });
{ var clazz = this.declaredClass; lang.mixin(this.store, { getValue: function(item, attr){ kernel.deprecated(clazz + ".store.getValue(item, attr) is deprecated for builtin store. Use item.attr directly", "", "2.0"); return item[attr]; }, getLabel: function(item){ kernel.depreca...
conditional_block
menu.py
# -*- coding: utf-8 -*- from sdl2 import SDL_Delay,\ SDL_GetTicks,\ SDL_KEYDOWN,\ SDL_KEYUP,\ SDL_QUIT,\ SDL_Rect,\ SDL_RenderCopy,\ SDLK_ESCAPE,\ SDLK_UP,\ SDLK_DOWN,\ SDLK_RETURN,\ SDL_Quit from sdl2.ext import Resources,\ get_events from const import WindowSize, Col...
(self): game = Game(self.world, self.window, self.renderer, self.factory) game.run() self.running = True self.run()
launch_game
identifier_name
menu.py
# -*- coding: utf-8 -*- from sdl2 import SDL_Delay,\ SDL_GetTicks,\ SDL_KEYDOWN,\ SDL_KEYUP,\ SDL_QUIT,\ SDL_Rect,\ SDL_RenderCopy,\ SDLK_ESCAPE,\ SDLK_UP,\ SDLK_DOWN,\ SDLK_RETURN,\ SDL_Quit from sdl2.ext import Resources,\ get_events from const import WindowSize, Col...
self.running = False # Move the cursor elif menu_input.was_key_pressed(SDLK_UP): if self.cursor_position != 0: self.cursor_position -= 1 elif menu_input.was_key_pressed(SDLK_DOWN): if self.cursor_position != 2: ...
if menu_input.was_key_pressed(SDLK_ESCAPE):
random_line_split
menu.py
# -*- coding: utf-8 -*- from sdl2 import SDL_Delay,\ SDL_GetTicks,\ SDL_KEYDOWN,\ SDL_KEYUP,\ SDL_QUIT,\ SDL_Rect,\ SDL_RenderCopy,\ SDLK_ESCAPE,\ SDLK_UP,\ SDLK_DOWN,\ SDLK_RETURN,\ SDL_Quit from sdl2.ext import Resources,\ get_events from const import WindowSize, Col...
def update(self, elapsed_time): self.cursor_sprite.position = self.cursor_start_position[0], self.cursor_start_position[1] \ + self.cursor_position * self.cursor_sprite_size def run(self): menu_input = Input() last_update_time = SDL_GetTicks() #...
SDL_Quit()
identifier_body
menu.py
# -*- coding: utf-8 -*- from sdl2 import SDL_Delay,\ SDL_GetTicks,\ SDL_KEYDOWN,\ SDL_KEYUP,\ SDL_QUIT,\ SDL_Rect,\ SDL_RenderCopy,\ SDLK_ESCAPE,\ SDLK_UP,\ SDLK_DOWN,\ SDLK_RETURN,\ SDL_Quit from sdl2.ext import Resources,\ get_events from const import WindowSize, Col...
def launch_game(self): game = Game(self.world, self.window, self.renderer, self.factory) game.run() self.running = True self.run()
SDL_Delay(ms_per_frame - elapsed_time)
conditional_block
Material.d.ts
import { Plane } from './../math/Plane'; import { EventDispatcher } from './../core/EventDispatcher'; import { BlendingDstFactor, BlendingEquation, Blending, BlendingSrcFactor, DepthModes, Side, Colors, } from '../constants'; // Materials //////////////////////////////////////////////////////////////////...
/** * This disposes the material. Textures of a material don't get disposed. These needs to be disposed by {@link Texture}. */ dispose(): void; /** * Sets the properties based on the values. * @param values A container with parameters. */ setValues(values: MaterialParameters): void; /** * ...
copy(material: Material): this;
random_line_split
Material.d.ts
import { Plane } from './../math/Plane'; import { EventDispatcher } from './../core/EventDispatcher'; import { BlendingDstFactor, BlendingEquation, Blending, BlendingSrcFactor, DepthModes, Side, Colors, } from '../constants'; // Materials //////////////////////////////////////////////////////////////////...
extends EventDispatcher { constructor(); /** * Sets the alpha value to be used when running an alpha test. Default is 0. */ alphaTest: number; /** * Blending destination. It's one of the blending mode constants defined in Three.js. Default is {@link OneMinusSrcAlphaFactor}. */ blendDst: Blendin...
Material
identifier_name
channel_dao_testing.rs
extern crate proton_cli; use proton_cli::dao::ChannelDao; use proton_cli::error::Error; use proton_cli::project_types::Channel; /// Implementation of ChannelDao for testing purposes. Uses given functions to return values. /// Functions are boxed so their sizes are known (pointers). /// The general naming convention ...
( &self, name: &str, primary_num: Option<u32>, secondary_num: Option<u32>, color: &str, channel_internal: u32, channel_dmx: u32, location: (Option<i32>, Option<i32>, Option<i32>), rotation: (Option<i32>, Option<i32>, Option<i32>) ) -> Result<Ch...
new_channel
identifier_name
channel_dao_testing.rs
extern crate proton_cli; use proton_cli::dao::ChannelDao;
/// Implementation of ChannelDao for testing purposes. Uses given functions to return values. /// Functions are boxed so their sizes are known (pointers). /// The general naming convention used is trait_function_name_fn, for all trait functions. /// &str references are converted to Strings so we don't have to deal wit...
use proton_cli::error::Error; use proton_cli::project_types::Channel;
random_line_split
app_options.js
/** * @licstart The following is the entire license notice for the * Javascript code in this page * * Copyright 2021 Mozilla Foundation * * 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...
if (kind === OptionKind.PREFERENCE) { const value = defaultOption.value, valueType = typeof value; if (valueType === "boolean" || valueType === "string" || valueType === "number" && Number.isInteger(value)) { options[name] = value; continue; ...
{ continue; }
conditional_block
app_options.js
/** * @licstart The following is the entire license notice for the * Javascript code in this page * * Copyright 2021 Mozilla Foundation * * 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...
(name) { const userOption = userOptions[name]; if (userOption !== undefined) { return userOption; } const defaultOption = defaultOptions[name]; if (defaultOption !== undefined) { return defaultOption.compatibility ?? defaultOption.value; } return undefined; } static getA...
get
identifier_name
app_options.js
/** * @licstart The following is the entire license notice for the * Javascript code in this page * * Copyright 2021 Mozilla Foundation * * 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...
static setAll(options) { for (const name in options) { userOptions[name] = options[name]; } } static remove(name) { delete userOptions[name]; } } exports.AppOptions = AppOptions;
{ userOptions[name] = value; }
identifier_body
app_options.js
/** * @licstart The following is the entire license notice for the * Javascript code in this page * * Copyright 2021 Mozilla Foundation * * 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...
kind: OptionKind.VIEWER }, externalLinkTarget: { value: 0, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, historyUpdateUrl: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENCE }, ignoreDestinationZoom: { value: false, kind: OptionKind.VIEWER + OptionKind.PREFERENC...
random_line_split
UserController.js
/** * UserController * * @description :: Server-side logic for managing users * @help :: See http://links.sailsjs.org/docs/controllers */ module.exports = { 'login': function (req, res) { User.findOne({username: req.body.username, password: req.body.password}) .exec(function (err, u...
} return res.status(404).json({error: 'Not logged in'}); }, logout: function(req, res) { delete req.session.user; return res.json({}); } };
res.json(user); });
random_line_split
UserController.js
/** * UserController * * @description :: Server-side logic for managing users * @help :: See http://links.sailsjs.org/docs/controllers */ module.exports = { 'login': function (req, res) { User.findOne({username: req.body.username, password: req.body.password}) .exec(function (err, u...
}); }, current: function (req, res) { if (req.session.user) { return User.findOne({id:req.session.user.id}).exec(function(err,user){ res.json(user); }); } return res.status(404).json({error: 'Not logged in'}); }, logout: funct...
{ return res.status(404).json({error: 'Invalid email/password'}); }
conditional_block
ofc_utils.py
from suds.client import Client from nova import exception from nova import db import logging logging.getLogger('suds').setLevel(logging.INFO) def update_for_run_instance(service_url, region_name, server_port1, server_port2, dpid1, dpid2): # check region name client = Client(service_url + "?wsdl") client...
def remove_region(service_url, region_name, vlan_id): client = Client(service_url + "?wsdl") try: switches = db.switch_get_all(None) for switch in switches: client.service.clearOuterPortAssociationSetting(switch["dpid"], switch["outer_port"], vlan_id) client.service.save(...
client = Client(service_url + "?wsdl") try: client.service.createRegion(region_name) client.service.save() except: raise exception.OFCRegionCreationFailed(region_name=region_name) try: switches = db.switch_get_all(None) for switch in switches: client.ser...
identifier_body
ofc_utils.py
from suds.client import Client from nova import exception from nova import db import logging logging.getLogger('suds').setLevel(logging.INFO) def update_for_run_instance(service_url, region_name, server_port1, server_port2, dpid1, dpid2): # check region name client = Client(service_url + "?wsdl") client...
if port.regionName == region_name: return remove_region(service_url, region_name, vlan_id) def create_region(service_url, region_name, vlan_id): client = Client(service_url + "?wsdl") try: client.service.createRegion(region_name) client.service.save() exce...
continue
conditional_block
ofc_utils.py
from suds.client import Client from nova import exception from nova import db import logging logging.getLogger('suds').setLevel(logging.INFO) def update_for_run_instance(service_url, region_name, server_port1, server_port2, dpid1, dpid2): # check region name client = Client(service_url + "?wsdl") client...
def has_region(service_url, region_name): client = Client(service_url + "?wsdl") return region_name in [x.regionName for x in client.service.showRegion()]
client.service.save()
random_line_split
ofc_utils.py
from suds.client import Client from nova import exception from nova import db import logging logging.getLogger('suds').setLevel(logging.INFO) def update_for_run_instance(service_url, region_name, server_port1, server_port2, dpid1, dpid2): # check region name client = Client(service_url + "?wsdl") client...
(service_url, region_name, vlan_id): client = Client(service_url + "?wsdl") try: switches = db.switch_get_all(None) for switch in switches: client.service.clearOuterPortAssociationSetting(switch["dpid"], switch["outer_port"], vlan_id) client.service.save() except: ...
remove_region
identifier_name
test_models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-nupages ------------ Tests for `django-nupages` models module. """ import os import shutil import unittest from django.utils import timezone from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from nupages import mo...
class TestNupages(unittest.TestCase): def create_page( self, title="Test Page", description="yes, this is only a test", content="yes, this is only a test", custom_template="", site=Site.objects.create(domain="127.0.0.1:8000", name="127.0.0.1:8000")): return models.Page.objects.create( title=title...
random_line_split
test_models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-nupages ------------ Tests for `django-nupages` models module. """ import os import shutil import unittest from django.utils import timezone from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from nupages import mo...
p = self.create_page() self.assertTrue(isinstance(p, models.Page)) self.assertEqual(p.__unicode__(), p.title) self.assertEqual(p.get_absolute_url(), reverse("nupages:detail", kwargs={'slug': p.slug}))
identifier_body
test_models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_django-nupages ------------ Tests for `django-nupages` models module. """ import os import shutil import unittest from django.utils import timezone from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from nupages import mo...
(unittest.TestCase): def create_page( self, title="Test Page", description="yes, this is only a test", content="yes, this is only a test", custom_template="", site=Site.objects.create(domain="127.0.0.1:8000", name="127.0.0.1:8000")): return models.Page.objects.create( title=title, description=...
TestNupages
identifier_name
density-server.ts
/** * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author David Sehnal <david.sehnal@gmail.com> */ import { Database, Column } from '../../../../mol-data/db'; import Schema = Column.Schema const str = Schema.str; const int = Schema.int; const float = Schema.float...
volume_data_3d_info: { 'name': str, // zero indexed axis order of the data 'axis_order': Vector(3, int), // Origin in fractional coords 'origin': Vector(3), // Dimension in fractional coords 'dimensions': Vector(3), 'sample_rate': int, // numbe...
} }; export const DensityServer_Data_Schema = {
random_line_split
successive_narrowing.py
import deep_architect.searchers.common as se import numpy as np # NOTE: this searcher does not do any budget adjustment and needs to be # combined with an evaluator that does. class SuccessiveNarrowing(se.Searcher): def __init__(self, search_space_fn, num_initial_samples, reduction_factor, reset...
def update(self, val, searcher_eval_token): assert self.num_remaining > 0 idx = searcher_eval_token["idx"] assert self.vals[idx] is None self.vals[idx] = val self.num_remaining -= 1 # generate the next round of architectures by keeping the best ones. if sel...
assert self.idx < len(self.queue) hyperp_value_lst = self.queue[self.idx] (inputs, outputs) = self.search_space_fn() se.specify(outputs, hyperp_value_lst) idx = self.idx self.idx += 1 return inputs, outputs, hyperp_value_lst, {"idx": idx}
identifier_body
successive_narrowing.py
import deep_architect.searchers.common as se import numpy as np # NOTE: this searcher does not do any budget adjustment and needs to be # combined with an evaluator that does. class SuccessiveNarrowing(se.Searcher): def __init__(self, search_space_fn, num_initial_samples, reduction_factor, reset...
budget = initial_budget * (budget_increase_factor**round_idx) evaluator = get_evaluator(budget) for idx in range(num_samples): (inputs, outputs, hyperp_value_lst, searcher_eval_token) = searcher.sample() results = evaluator.eval(inputs, outputs) val = ext...
conditional_block
successive_narrowing.py
import deep_architect.searchers.common as se import numpy as np # NOTE: this searcher does not do any budget adjustment and needs to be # combined with an evaluator that does. class SuccessiveNarrowing(se.Searcher): def __init__(self, search_space_fn, num_initial_samples, reduction_factor, reset...
# run simple successive narrowing on a single machine. def run_successive_narrowing(search_space_fn, num_initial_samples, initial_budget, get_evaluator, extract_val_fn, num_samples_reduction_factor, budget_increase_factor, num_round...
self.idx = 0
random_line_split
successive_narrowing.py
import deep_architect.searchers.common as se import numpy as np # NOTE: this searcher does not do any budget adjustment and needs to be # combined with an evaluator that does. class SuccessiveNarrowing(se.Searcher): def __init__(self, search_space_fn, num_initial_samples, reduction_factor, reset...
(self, val, searcher_eval_token): assert self.num_remaining > 0 idx = searcher_eval_token["idx"] assert self.vals[idx] is None self.vals[idx] = val self.num_remaining -= 1 # generate the next round of architectures by keeping the best ones. if self.num_remaining ...
update
identifier_name
plot.component.ts
import { Component, Input, OnChanges, ViewChild, AfterViewInit } from '@angular/core'; import { Coordinates } from '../../services/data-services/insert-data' declare var Bokeh: any; @Component({ selector: 'my-plot', templateUrl: './bokeh-plot.html' }) export class PlotComponent implements OnChanges, AfterViewIni...
tempSource: any; jsonValid: boolean = true; jsonErrorMessage: string; @ViewChild('bokehplot') bokehplot: any; plt = Bokeh.Plotting; tools = 'pan,crosshair,wheel_zoom,box_zoom,reset,save'; xrange = Bokeh.Range1d(-6, 6); yrange = Bokeh.Range1d(-6, 6); fig = this.plt.figure({ title: 'Electron I...
@Input() plot_height: number = 300; parsedJSON: any;
random_line_split
plot.component.ts
import { Component, Input, OnChanges, ViewChild, AfterViewInit } from '@angular/core'; import { Coordinates } from '../../services/data-services/insert-data' declare var Bokeh: any; @Component({ selector: 'my-plot', templateUrl: './bokeh-plot.html' }) export class PlotComponent implements OnChanges, AfterViewIni...
if (this.ellipse) { if ('x' in this.ellipse && 'y' in this.ellipse) { this.tempSource.xs[2] = this.ellipse.x this.tempSource.ys[2] = this.ellipse.y xAll = xAll.concat(this.tempSource.xs[2]); yAll = yAll.concat(this.tempSource.ys[2]); } } } le...
{ if ('x' in this.circle && 'y' in this.circle) { this.tempSource.xs[1] = this.circle.x this.tempSource.ys[1] = this.circle.y xAll = xAll.concat(this.tempSource.xs[1]); yAll = yAll.concat(this.tempSource.ys[1]); } }
conditional_block
plot.component.ts
import { Component, Input, OnChanges, ViewChild, AfterViewInit } from '@angular/core'; import { Coordinates } from '../../services/data-services/insert-data' declare var Bokeh: any; @Component({ selector: 'my-plot', templateUrl: './bokeh-plot.html' }) export class PlotComponent implements OnChanges, AfterViewIni...
() { this.jsonValid = false; this.tempSource = { "xs": [[0], [0], [0]], "ys": [[0], [0], [0]], "colour": ["navy", "firebrick", "green"] } let xAll: number[] = []; let yAll: number[] = []; if (this.enabled) { if (this.insert_x != null && this.insert_y != null) { th...
ngOnChanges
identifier_name
tag-align-shape.rs
// Copyright 2012 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 ...
t: a_tag } pub fn main() { let x = t_rec {c8: 22u8, t: a_tag(44u64)}; let y = fmt!("%?", x); info!("y = %s", y); assert_eq!(y, ~"t_rec{c8: 22u8, t: a_tag(44u64)}"); }
struct t_rec { c8: u8,
random_line_split
tag-align-shape.rs
// Copyright 2012 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 ...
() { let x = t_rec {c8: 22u8, t: a_tag(44u64)}; let y = fmt!("%?", x); info!("y = %s", y); assert_eq!(y, ~"t_rec{c8: 22u8, t: a_tag(44u64)}"); }
main
identifier_name
request.ts
import fs from 'fs'; import url from 'url'; import path from 'path'; import querystring from 'querystring'; import fsExtra from 'fs-extra'; import superagent from 'superagent'; import superagentCharset from 'superagent-charset'; import iconv from 'iconv-lite'; import cheerio from 'cheerio'; import PQueue from 'p-queue...
*/ export async function download( source: string, dest: string, options: downloadOptions = {}, ): Promise<{}> { const { headers = {}, timeout = 30000, onProgress = () => {} } = options; return new Promise((resolve, reject) => { superagent(source) .set(headers) .timeout(timeout) .on('p...
* @param src source URL * @param dest destination path * @param options download options * @returns None
random_line_split
request.ts
import fs from 'fs'; import url from 'url'; import path from 'path'; import querystring from 'querystring'; import fsExtra from 'fs-extra'; import superagent from 'superagent'; import superagentCharset from 'superagent-charset'; import iconv from 'iconv-lite'; import cheerio from 'cheerio'; import PQueue from 'p-queue...
return downloadQueue; } export interface destData { index: number; // prettier-ignore 'name': string; suffix: string; autoIndex: string; path: string; } interface batchDownloadOptions extends downloadOptions { onTaskStart?: (dest: string) => void; onTaskFinished?: (err: Error | null, dest: string) ...
{ downloadQueue = new PQueue({ concurrency: 5 }); }
conditional_block
request.ts
import fs from 'fs'; import url from 'url'; import path from 'path'; import querystring from 'querystring'; import fsExtra from 'fs-extra'; import superagent from 'superagent'; import superagentCharset from 'superagent-charset'; import iconv from 'iconv-lite'; import cheerio from 'cheerio'; import PQueue from 'p-queue...
/** * Fetch the original text of url given. * @param source source URL * @param headers extra http headers */ export async function fetchText(source: string, headers: object = {}): Promise<string> { const response = await request(source) .set(headers) .charset(); if (!response.ok) { throw response...
{ return superagentWithCharset(method, requestUrl); }
identifier_body
request.ts
import fs from 'fs'; import url from 'url'; import path from 'path'; import querystring from 'querystring'; import fsExtra from 'fs-extra'; import superagent from 'superagent'; import superagentCharset from 'superagent-charset'; import iconv from 'iconv-lite'; import cheerio from 'cheerio'; import PQueue from 'p-queue...
() { if (!downloadQueue) { downloadQueue = new PQueue({ concurrency: 5 }); } return downloadQueue; } export interface destData { index: number; // prettier-ignore 'name': string; suffix: string; autoIndex: string; path: string; } interface batchDownloadOptions extends downloadOptions { onTaskS...
getDownloadQueue
identifier_name
Digitizers.py
""" For now just Alazar cards but should also support Acquiris. """ from Instrument import Instrument from atom.api import Atom, Str, Int, Float, Bool, Enum, List, Dict, Coerced import itertools, ast import enaml from enaml.qt.qt_application import QtApplication class Digitizer(Instrument): pass class AlazarATS987...
jsonDict['demodKernel'] = base64.b64encode(eval(self.demodKernel)) except: jsonDict['demodKernel'] = [] try: jsonDict['demodKernelBias'] = base64.b64encode(np.array(eval(self.demodKernelBias), dtype=np.complex128)) except: jsonDict['demodKernelBias'] = [] try: jsonDict['rawKernel'] = bas...
if matlabCompatible: import numpy as np import base64 try:
random_line_split
Digitizers.py
""" For now just Alazar cards but should also support Acquiris. """ from Instrument import Instrument from atom.api import Atom, Str, Int, Float, Bool, Enum, List, Dict, Coerced import itertools, ast import enaml from enaml.qt.qt_application import QtApplication class Digitizer(Instrument): pass class AlazarATS987...
(self, matlabCompatible=False): jsonDict = super(X6, self).json_encode(matlabCompatible) if matlabCompatible: # For the Matlab experiment manager we nest averager settings map(lambda x: jsonDict.pop(x), ['recordLength', 'nbrSegments', 'nbrWaveforms', 'nbrRoundRobins']) jsonDict['averager'] = {k:getattr(sel...
json_encode
identifier_name
Digitizers.py
""" For now just Alazar cards but should also support Acquiris. """ from Instrument import Instrument from atom.api import Atom, Str, Int, Float, Bool, Enum, List, Dict, Coerced import itertools, ast import enaml from enaml.qt.qt_application import QtApplication class Digitizer(Instrument): pass class AlazarATS987...
for paramName in chParams.__getstate__().keys(): setattr(self.channels[chName], paramName, getattr(chParams, paramName)) params.pop('channels') super(X6, self).update_from_jsondict(params) if __name__ == "__main__": from Digitizers import X6 digitizer = X6(label='scope') with enaml.imports(): from D...
chParams.pop('x__class__', None) chParams.pop('x__module__', None) chParams = X6VirtualChannel(**chParams)
conditional_block
Digitizers.py
""" For now just Alazar cards but should also support Acquiris. """ from Instrument import Instrument from atom.api import Atom, Str, Int, Float, Bool, Enum, List, Dict, Coerced import itertools, ast import enaml from enaml.qt.qt_application import QtApplication class Digitizer(Instrument): pass class AlazarATS987...
def update_from_jsondict(self, params): for chName, chParams in params['channels'].items(): # if this is still a raw dictionary convert to object if isinstance(chParams, dict): chParams.pop('x__class__', None) chParams.pop('x__module__', None) chParams = X6VirtualChannel(**chParams) for para...
jsonDict = super(X6, self).json_encode(matlabCompatible) if matlabCompatible: # For the Matlab experiment manager we nest averager settings map(lambda x: jsonDict.pop(x), ['recordLength', 'nbrSegments', 'nbrWaveforms', 'nbrRoundRobins']) jsonDict['averager'] = {k:getattr(self,k) for k in ['recordLength', 'nb...
identifier_body
lib.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/. */ //! A simple application that uses glutin to open a window for Servo to display in. #![feature(box_syntax, result...
pub trait NestedEventLoopListener { fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool; } pub fn create_window(parent: WindowID) -> Rc<Window> { // Read command-line options. let opts = opts::get(); let foreground = opts.output_file.is_none(); let scale_factor = ScaleFac...
pub type WindowID = glutin::WindowID;
random_line_split
lib.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/. */ //! A simple application that uses glutin to open a window for Servo to display in. #![feature(box_syntax, result...
(parent: WindowID) -> Rc<Window> { // Read command-line options. let opts = opts::get(); let foreground = opts.output_file.is_none(); let scale_factor = ScaleFactor::new(opts.device_pixels_per_px.unwrap_or(1.0)); let size = opts.initial_window_size.as_f32() * scale_factor; // Open a window. ...
create_window
identifier_name
lib.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/. */ //! A simple application that uses glutin to open a window for Servo to display in. #![feature(box_syntax, result...
{ // Read command-line options. let opts = opts::get(); let foreground = opts.output_file.is_none(); let scale_factor = ScaleFactor::new(opts.device_pixels_per_px.unwrap_or(1.0)); let size = opts.initial_window_size.as_f32() * scale_factor; // Open a window. Window::new(foreground, size.as_...
identifier_body
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use context::QuirksMode; ...
fn parse(name: &str) -> Result<Self, ()> { // From https://drafts.csswg.org/mediaqueries/#mq-syntax: // // The <media-type> production does not include the keywords not, or, and, and only. // // Here we also perform the to-ascii-lowercase part of the serialization /...
/// The `print` media type. pub fn print() -> Self { MediaType(CustomIdent(atom!("print"))) }
random_line_split
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use context::QuirksMode; ...
() -> Self { MediaType(CustomIdent(atom!("screen"))) } /// The `print` media type. pub fn print() -> Self { MediaType(CustomIdent(atom!("print"))) } fn parse(name: &str) -> Result<Self, ()> { // From https://drafts.csswg.org/mediaqueries/#mq-syntax: // // ...
screen
identifier_name
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use context::QuirksMode; ...
fn matches(&self, other: MediaType) -> bool { match *self { MediaQueryType::All => true, MediaQueryType::Concrete(ref known_type) => *known_type == other, } } } /// https://drafts.csswg.org/mediaqueries/#media-types #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(fea...
{ match_ignore_ascii_case! { ident, "all" => return Ok(MediaQueryType::All), _ => (), }; // If parseable, accept this type as a concrete type. MediaType::parse(ident).map(MediaQueryType::Concrete) }
identifier_body
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use context::QuirksMode; ...
else { None }; let media_type = match input.try(|i| i.expect_ident_cloned()) { Ok(ident) => { let result: Result<_, ParseError> = MediaQueryType::parse(&*ident) .map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into()); ...
{ Some(Qualifier::Not) }
conditional_block
error_reporting.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/. */ //! Types used to report parsing errors. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition}; use log...
} }
{ let location = input.source_location(position); info!("Url:\t{}\n{}:{} {}", url.as_str(), location.line, location.column, message) }
conditional_block
error_reporting.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/. */ //! Types used to report parsing errors. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition}; use log...
; impl ParseErrorReporter for StdoutErrorReporter { fn report_error(&self, input: &mut Parser, position: SourcePosition, message: &str, url: &ServoUrl) { if log_enabled!(log::LogLevel::Info) { let location = input.so...
StdoutErrorReporter
identifier_name
error_reporting.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/. */ //! Types used to report parsing errors. #![deny(missing_docs)] use cssparser::{Parser, SourcePosition}; use log...
} }
random_line_split
hoisting_sf.py
#!/usr/bin/env python # calculates safety factor in hoisting lines with various number of parts & rotating sheaves # (c) 2013, D. Djokic # No guaranties, whatsoever - use code on your own risk # Released under GNU General Public License ''' IADC safety factor recommendations: drilling and other routine operations ...
def write_file (file, description, var): #write to file file.write ("\n") file.write (str(description)) file.write ("\t") file.write (str(var)) W = get_float ("Hoisted Weight in tones (1 ton = 2000lb) = ", 40) L = get_float ("Capacity of existing wire rope in tones (1 ton = 2000lb): ", 90) n = get_integer ("Numb...
try: f=input (message) st=type(f) if f==0: f=default return int(f) elif f==" ": f=default return int(f) else: return int(f) except: print("Wrong Input! Try again") return(get_integer(message, default))
identifier_body
hoisting_sf.py
#!/usr/bin/env python # calculates safety factor in hoisting lines with various number of parts & rotating sheaves # (c) 2013, D. Djokic # No guaranties, whatsoever - use code on your own risk # Released under GNU General Public License ''' IADC safety factor recommendations: drilling and other routine operations ...
return int(f) except: print("Wrong Input! Try again") return(get_integer(message, default)) def write_file (file, description, var): #write to file file.write ("\n") file.write (str(description)) file.write ("\t") file.write (str(var)) W = get_float ("Hoisted Weight in tones (1 ton = 2000lb) = ", 40) L = ...
return int(f) else:
random_line_split
hoisting_sf.py
#!/usr/bin/env python # calculates safety factor in hoisting lines with various number of parts & rotating sheaves # (c) 2013, D. Djokic # No guaranties, whatsoever - use code on your own risk # Released under GNU General Public License ''' IADC safety factor recommendations: drilling and other routine operations ...
elif f==" ": f=default return float(f) ##dodo else: return float(f) except: print("Wrong Input! Try again") return(get_float(message, default)) def get_integer(message, default): #get integer number - error check included try: f=input (message) st=type(f) if f==0: f=default return int(...
f=default return float(f) ##dodo
conditional_block
hoisting_sf.py
#!/usr/bin/env python # calculates safety factor in hoisting lines with various number of parts & rotating sheaves # (c) 2013, D. Djokic # No guaranties, whatsoever - use code on your own risk # Released under GNU General Public License ''' IADC safety factor recommendations: drilling and other routine operations ...
(file, description, var): #write to file file.write ("\n") file.write (str(description)) file.write ("\t") file.write (str(var)) W = get_float ("Hoisted Weight in tones (1 ton = 2000lb) = ", 40) L = get_float ("Capacity of existing wire rope in tones (1 ton = 2000lb): ", 90) n = get_integer ("Number of lines or '...
write_file
identifier_name
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) { ans[*idx] = value; vis[value] = true; *idx+=1; } fn
(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &mut[bool]) { if *idx == 2*N { for i in 1..N { if ans[0]+ans[1]+ans[3] != ans[i*2]+ans[i*2+1]+ans[(i*2+3)%(2*N)] { return ; ...
unset_v
identifier_name
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) { ans[*idx] = value; vis[value] = true; *idx+=1; } fn unset_v(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &...
fn main() { let mut arr =[0 as usize;2*N]; let mut idx = 0; let mut vis =[false;2*N+1]; set_v(&mut arr,&mut idx,&mut vis, 10); dfs(&mut arr,&mut idx,&mut vis); }
{ if *idx == 2*N { for i in 1..N { if ans[0]+ans[1]+ans[3] != ans[i*2]+ans[i*2+1]+ans[(i*2+3)%(2*N)] { return ; } } let mut mini = 0; for i in 0..N { if ans[i*2] < ans[mini*2] { mini = i; } } ...
identifier_body
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) {
fn unset_v(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &mut[bool]) { if *idx == 2*N { for i in 1..N { if ans[0]+ans[1]+ans[3] != ans[i*2]+ans[i*2+1]+ans[(i*2+3)%(2*N)] { ret...
ans[*idx] = value; vis[value] = true; *idx+=1; }
random_line_split
p068.rs
const N:usize = 5; fn set_v(ans: &mut[usize],idx: &mut usize, vis: &mut[bool], value: usize) { ans[*idx] = value; vis[value] = true; *idx+=1; } fn unset_v(idx: &mut usize, vis: &mut[bool], value: usize) { *idx -= 1; vis[value] = false; } fn dfs(mut ans: &mut[usize],mut idx: &mut usize, mut vis: &...
} let mut mini = 0; for i in 0..N { if ans[i*2] < ans[mini*2] { mini = i; } } for ii in 0..N { let i = (ii+mini)%N; print!("{}{}{}",ans[i*2],ans[i*2+1],ans[(i*2+3)%(2*N)]); } println!(""); re...
{ return ; }
conditional_block
flowlabel.py
# Copyright 2014 Open Source Robotics Foundation, Inc. # # 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 ...
return (int(result[0][0]), int(result[0][2])) def gen_flowlabel(origin_index, destination_index): """ generate a flowlabel """ return "%d_%d"%(origin_index, destination_index)
raise Exception("Invalid flowlabel %s"%flowlabel)
conditional_block
flowlabel.py
# Copyright 2014 Open Source Robotics Foundation, Inc. # # 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 ...
destination node index Example: flowlabel 1_2 means the flow from the node at index 1 to the node at index 2 """ import re def parse_flowlabel(flowlabel): """ Parses a flowlabel into a tuple """ result = re.findall("(^\d+)(_)(\d+$)", flowlabel) if len(result) == 0: raise Excepti...
not have a single unique attribute, which makes them difficult to identify. flows solve that problem. flowlabels have 2 parts: origin node index
random_line_split
flowlabel.py
# Copyright 2014 Open Source Robotics Foundation, Inc. # # 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 ...
def gen_flowlabel(origin_index, destination_index): """ generate a flowlabel """ return "%d_%d"%(origin_index, destination_index)
""" Parses a flowlabel into a tuple """ result = re.findall("(^\d+)(_)(\d+$)", flowlabel) if len(result) == 0: raise Exception("Invalid flowlabel %s"%flowlabel) return (int(result[0][0]), int(result[0][2]))
identifier_body
flowlabel.py
# Copyright 2014 Open Source Robotics Foundation, Inc. # # 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 ...
(origin_index, destination_index): """ generate a flowlabel """ return "%d_%d"%(origin_index, destination_index)
gen_flowlabel
identifier_name
app.module.ts
import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { Page1 } from '../pages/page1/page1'; import { Page2 } from '../pages/page2/page2'; import { ShowTaskPage } from '../pages/show-task/show-tas...
{}
AppModule
identifier_name
app.module.ts
import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { Page1 } from '../pages/page1/page1'; import { Page2 } from '../pages/page2/page2'; import { ShowTaskPage } from '../pages/show-task/show-tas...
}, 'push': { 'sender_id': '901124139844', 'pluginConfig': { 'ios': { 'badge': true, 'sound': true }, 'android': { 'iconColor': '#343434' } } } }; @NgModule({ declarations: [ MyApp, Page1, Page2, ShowTaskPage, LoginPage, ShowTas...
const cloudSettings: CloudSettings = { 'core': { 'app_id': 'd9067871'
random_line_split
room_id.rs
//! Matrix room identifiers. use super::{matrix_uri::UriAction, EventId, MatrixToUri, MatrixUri, ServerName}; /// A Matrix [room ID]. /// /// A `RoomId` is generated randomly or converted from a string slice, and can be converted back /// into a string as needed. /// /// ``` /// # use std::convert::TryFrom; /// # use...
#[test] fn valid_room_id_with_explicit_standard_port() { assert_eq!( <&RoomId>::try_from("!29fhd83h92h0:example.com:443") .expect("Failed to create RoomId.") .as_ref(), "!29fhd83h92h0:example.com:443" ); } #[test] fn valid_ro...
{ assert_eq!( serde_json::from_str::<Box<RoomId>>(r#""!29fhd83h92h0:example.com""#) .expect("Failed to convert JSON to RoomId"), <&RoomId>::try_from("!29fhd83h92h0:example.com").expect("Failed to create RoomId.") ); }
identifier_body
room_id.rs
//! Matrix room identifiers. use super::{matrix_uri::UriAction, EventId, MatrixToUri, MatrixUri, ServerName}; /// A Matrix [room ID]. /// /// A `RoomId` is generated randomly or converted from a string slice, and can be converted back /// into a string as needed. /// /// ``` /// # use std::convert::TryFrom; /// # use...
() { assert_eq!(<&RoomId>::try_from("!29fhd83h92h0:/").unwrap_err(), Error::InvalidServerName); } #[test] fn invalid_room_id_port() { assert_eq!( <&RoomId>::try_from("!29fhd83h92h0:example.com:notaport").unwrap_err(), Error::InvalidServerName ); } }
invalid_room_id_host
identifier_name
room_id.rs
//! Matrix room identifiers. use super::{matrix_uri::UriAction, EventId, MatrixToUri, MatrixUri, ServerName}; /// A Matrix [room ID]. /// /// A `RoomId` is generated randomly or converted from a string slice, and can be converted back /// into a string as needed. /// /// ``` /// # use std::convert::TryFrom; /// # use...
assert_eq!( <&RoomId>::try_from("!29fhd83h92h0:example.com:5000") .expect("Failed to create RoomId.") .as_ref(), "!29fhd83h92h0:example.com:5000" ); } #[test] fn missing_room_id_sigil() { assert_eq!( <&RoomId>::try_...
#[test] fn valid_room_id_with_non_standard_port() {
random_line_split
master.ts
import {IAutomationConfig} from "../src/configurationManager/IAutomationConfig"; const masterConfig: IAutomationConfig = { externalParams: {}, passwords: { fallbackToPreDecrypted: true, decryptionKeyEnvVariable: 'AUTOMATION_INFRA_PASSWORDS_KEY' }, utils: { email: { ...
testCaseOrder: { beginWithTag: '@setup', endWithTag: '@teardown' } } }; export default masterConfig;
}, logic: { allowDefaultFieldMutator: true,
random_line_split
player.rs
pub const MAX_VELOCITY: f64 = 1.5; pub struct Player { _x: f64, _y: f64, pub width: u32, pub height: u32, x_velocity: f64, y_velocity: f64, } impl Player { pub fn new() -> Player { Player {
_x: 0., _y: 0., width: 32, height: 32, x_velocity: 0., y_velocity: 0., } } pub fn x(&self, lag: f64) -> i32 { (self._x + self.x_velocity*lag) as i32 } pub fn y(&self, lag: f64) -> i32 { // println!("{}", la...
random_line_split
player.rs
pub const MAX_VELOCITY: f64 = 1.5; pub struct Player { _x: f64, _y: f64, pub width: u32, pub height: u32, x_velocity: f64, y_velocity: f64, } impl Player { pub fn new() -> Player { Player { _x: 0., _y: 0., width: 32, height: 32, ...
(&self, lag: f64) -> i32 { (self._x + self.x_velocity*lag) as i32 } pub fn y(&self, lag: f64) -> i32 { // println!("{}", lag); (self._y + self.y_velocity*lag) as i32 } pub fn change_velocity(&mut self, x_velocity: f64, y_velocity: f64) { self.x_velocity = self.x_velocit...
x
identifier_name
player.rs
pub const MAX_VELOCITY: f64 = 1.5; pub struct Player { _x: f64, _y: f64, pub width: u32, pub height: u32, x_velocity: f64, y_velocity: f64, } impl Player { pub fn new() -> Player { Player { _x: 0., _y: 0., width: 32, height: 32, ...
pub fn y(&self, lag: f64) -> i32 { // println!("{}", lag); (self._y + self.y_velocity*lag) as i32 } pub fn change_velocity(&mut self, x_velocity: f64, y_velocity: f64) { self.x_velocity = self.x_velocity + x_velocity; self.y_velocity = self.y_velocity + y_velocity; } ...
{ (self._x + self.x_velocity*lag) as i32 }
identifier_body
timepicker.directive.ts
import { AfterContentInit, ChangeDetectorRef, Directive, ElementRef, HostListener, Input, OnChanges, OnDestroy, OnInit, Renderer2, forwardRef, } from '@angular/core'; import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator, } from '@angular/forms'; imp...
} this.renderer.setProperty( this.elRef.nativeElement, 'value', formattedValue ); } private formatter(time: any) { if (time && typeof time !== 'string' && 'local' in time) { return time; } if (typeof time === 'string') { if (time.length === 0) { retur...
{ formattedValue = output; }
conditional_block
timepicker.directive.ts
import { AfterContentInit, ChangeDetectorRef, Directive, ElementRef, HostListener, Input, OnChanges, OnDestroy, OnInit, Renderer2, forwardRef, } from '@angular/core'; import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator, } from '@angular/forms'; imp...
() { this._onTouched(); } public registerOnChange(fn: (value: any) => any): void { this._onChange = fn; } public registerOnTouched(fn: () => any): void { this._onTouched = fn; } public registerOnValidatorChange(fn: () => void): void { this._validatorChange = fn; } public setDisabledSta...
onBlur
identifier_name
timepicker.directive.ts
import { AfterContentInit, ChangeDetectorRef, Directive, ElementRef, HostListener, Input, OnChanges, OnDestroy, OnInit, Renderer2, forwardRef, } from '@angular/core'; import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator, } from '@angular/forms'; imp...
// tslint:enable @Directive({ selector: '[skyTimepickerInput]', providers: [SKY_TIMEPICKER_VALUE_ACCESSOR, SKY_TIMEPICKER_VALIDATOR], }) export class SkyTimepickerInputDirective implements OnInit, OnDestroy, ControlValueAccessor, Validator, OnChanges, AfterContentInit { public pickerCha...
};
random_line_split
timepicker.directive.ts
import { AfterContentInit, ChangeDetectorRef, Directive, ElementRef, HostListener, Input, OnChanges, OnDestroy, OnInit, Renderer2, forwardRef, } from '@angular/core'; import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator, } from '@angular/forms'; imp...
// eslint-disable-next-line @typescript-eslint/no-empty-function private _onChange = (_: any) => {}; // eslint-disable-next-line @typescript-eslint/no-empty-function private _onTouched = () => {}; // eslint-disable-next-line @typescript-eslint/no-empty-function private _validatorChange = () => {}; }
{ if (this.skyTimepickerInput) { this.skyTimepickerInput.disabled = this.disabled; /* istanbul ignore else */ if (this.skyTimepickerInput.selectedTime !== this.modelValue) { this.skyTimepickerInput.selectedTime = this.modelValue; } } }
identifier_body
profile-user-details.tsx
import * as React from 'react'; import * as PropTypes from 'prop-types'; import UserAvatar from '../shared/user-avatar'; import { followUser, unfollowUser } from '../../actions/user'; import { authenticatedAction } from '../../lib/util'; import './profile-user-details.css'; export default class ProfileUserDetails ext...
} render() { const { user, location } = this.props; let userInfoArray = []; let userCompanyLocation = ""; let joinTime = ""; let followingText = "关注"; if (user.company && user.company.length > 0) { userInfoArray.push(user.company); } if (user.location && user.location.le...
{ authenticatedAction(dispatch, () => { dispatch(followUser(user)); }); }
conditional_block
profile-user-details.tsx
import * as React from 'react'; import * as PropTypes from 'prop-types'; import UserAvatar from '../shared/user-avatar'; import { followUser, unfollowUser } from '../../actions/user'; import { authenticatedAction } from '../../lib/util'; import './profile-user-details.css'; export default class ProfileUserDetails ext...
return ( <div className="profileUserDetailsContainer"> <UserAvatar size={56} radius={6} src={user.avatar_url} username={user.login} /> <div className="profileInfo"> <div className="profileUserDetailsItem"> ...
}
random_line_split
profile-user-details.tsx
import * as React from 'react'; import * as PropTypes from 'prop-types'; import UserAvatar from '../shared/user-avatar'; import { followUser, unfollowUser } from '../../actions/user'; import { authenticatedAction } from '../../lib/util'; import './profile-user-details.css'; export default class ProfileUserDetails ext...
{ const { user, location } = this.props; let userInfoArray = []; let userCompanyLocation = ""; let joinTime = ""; let followingText = "关注"; if (user.company && user.company.length > 0) { userInfoArray.push(user.company); } if (user.location && user.location.length > 0) { ...
identifier_body
profile-user-details.tsx
import * as React from 'react'; import * as PropTypes from 'prop-types'; import UserAvatar from '../shared/user-avatar'; import { followUser, unfollowUser } from '../../actions/user'; import { authenticatedAction } from '../../lib/util'; import './profile-user-details.css'; export default class ProfileUserDetails ext...
() { const { user, location } = this.props; let userInfoArray = []; let userCompanyLocation = ""; let joinTime = ""; let followingText = "关注"; if (user.company && user.company.length > 0) { userInfoArray.push(user.company); } if (user.location && user.location.length > 0) { ...
render
identifier_name
string.rs
// Copyright 2015 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 ...
// succeed. let max_chars = try_opt!(fmt.width.checked_sub(fmt.opener.len() + ender_length + 1)) + 1; // Snip a line at a time from `orig` until it is used up. Push the snippet // onto result. 'outer: loop { // `cur_end` will be where we break the line, as an offset into `orig`. // ...
.unwrap_or(usize::max_value())); result.push_str(fmt.opener); let ender_length = fmt.line_end.len(); // If we cannot put at least a single character per line, the rewrite won't
random_line_split
string.rs
// Copyright 2015 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 ...
<'a> { pub opener: &'a str, pub closer: &'a str, pub line_start: &'a str, pub line_end: &'a str, pub width: usize, pub offset: Indent, pub trim_end: bool, pub config: &'a Config, } // FIXME: simplify this! pub fn rewrite_string<'a>(orig: &str, fmt: &StringFormat<'a>) -> Option<String> {...
StringFormat
identifier_name
string.rs
// Copyright 2015 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 ...
cur_end += 1; } break; } } break; } } // Make sure there is no whitespace to the right of the break. while cur_end < stripped_str.len() && graphemes[cur_en...
{ let line = &graphemes[cur_start..].join(""); result.push_str(line); break 'outer; }
conditional_block
0091_auto_20180727_1844.py
# Generated by Django 1.11.11 on 2018-07-27 18:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
operations = [ migrations.AddField( model_name='degree', name='campus_image_desktop', field=models.ImageField(blank=True, help_text='Provide a campus image to display on desktop displays', null=True, upload_to='media/degree_marketing/campus_images/'), ), m...
('course_metadata', '0090_degree_curriculum_reset'), ]
random_line_split
0091_auto_20180727_1844.py
# Generated by Django 1.11.11 on 2018-07-27 18:44 from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('course_metadata', '0090_degree_curriculum_reset'), ] operations = [ migrations.AddField( model_name='degree', name='campus_image_desktop', field=models.ImageField(blank=True, help_text='Provide a campus image to...
Migration
identifier_name
0091_auto_20180727_1844.py
# Generated by Django 1.11.11 on 2018-07-27 18:44 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('course_metadata', '0090_degree_curriculum_reset'), ] operations = [ migrations.AddField( model_name='degree', name='campus_image_desktop', field=models.ImageField(blank=True, help_text='Provide a campus image to display on desktop displays'...
identifier_body
article.js
import React from "react" import { graphql, Link } from "gatsby" import Img from "gatsby-image" import Layout from "../components/layout_1" const Article = ({ data }) => { return ( <Layout> <Link to="/">Go back to index page</Link> <div> <h2>{data.article.title}</h2> {data.article.ima...
} } `
} }
random_line_split
de-BE.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
root.ng.common.locales['de-be'] = [ 'de-BE', [['AM', 'PM'], u, u], u, [ ['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'], ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr....
{ let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; }
identifier_body
de-BE.js
/** * @license
* * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.commo...
* Copyright Google Inc. All Rights Reserved.
random_line_split
de-BE.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } root.ng.common.locales['de-be'] = [ 'de-BE', [['AM', 'PM'], u, u], u, [ ['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'F...
plural
identifier_name
materialize-css-tests.ts
// Buttons $('.fixed-action-btn').openFAB(); $('.fixed-action-btn').closeFAB(); // Forms - Select $('select').material_select(); $('select').material_select('destroy'); // Forms - Date Picker $('.datepicker').pickadate({ selectMonths: true, // Creates a dropdown to control month selectYears: 15 // Creates a dr...
var scrollSpyHtml = '<div class="row">' + '<div class="col s12 m9 l10">' + '<div id="introduction" class="section scrollspy">' + '<p>Content </p>' + '</div>' + '<div id="structure" class="section scrollspy">' + '<p>Content </p>' + '</div>' + '<div id="initialization" cl...
// ScrollSpy
random_line_split
observeOn.ts
import { Observable } from '../Observable'; import { Scheduler } from '../Scheduler'; import { Operator } from '../Operator'; import { PartialObserver } from '../Observer'; import { Subscriber } from '../Subscriber'; import { Notification } from '../Notification'; import { TeardownLogic } from '../Subscription'; /** ...
notification.observe(destination); } constructor(destination: Subscriber<T>, private scheduler: Scheduler, private delay: number = 0) { super(destination); } private scheduleMessage(notification: Notification<any>): void { this.add(this.scheduler.schedule(ObserveOnSubs...
*/ export class ObserveOnSubscriber<T> extends Subscriber<T> { static dispatch(arg: ObserveOnMessage) { const { notification, destination } = arg;
random_line_split
observeOn.ts
import { Observable } from '../Observable'; import { Scheduler } from '../Scheduler'; import { Operator } from '../Operator'; import { PartialObserver } from '../Observer'; import { Subscriber } from '../Subscriber'; import { Notification } from '../Notification'; import { TeardownLogic } from '../Subscription'; /** ...
<T> implements Operator<T, T> { constructor(private scheduler: Scheduler, private delay: number = 0) { } call(subscriber: Subscriber<T>, source: any): TeardownLogic { return source._subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay)); } } /** * We need this JSDoc comment for affect...
ObserveOnOperator
identifier_name
observeOn.ts
import { Observable } from '../Observable'; import { Scheduler } from '../Scheduler'; import { Operator } from '../Operator'; import { PartialObserver } from '../Observer'; import { Subscriber } from '../Subscriber'; import { Notification } from '../Notification'; import { TeardownLogic } from '../Subscription'; /** ...
protected _complete(): void { this.scheduleMessage(Notification.createComplete()); } } export class ObserveOnMessage { constructor(public notification: Notification<any>, public destination: PartialObserver<any>) { } }
{ this.scheduleMessage(Notification.createError(err)); }
identifier_body
lib.rs
#![cfg_attr(feature = "unstable", feature(const_fn, drop_types_in_const))] #![cfg_attr(feature = "serde_derive", feature(proc_macro))] #![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #![cfg_attr(not(feature = "unstable"), deny(warnings))] extern crat...
{ name: String, protocol_date: String, } impl Service { pub fn new<S>(name: S, protocol_date: S) -> Self where S: Into<String> { Service { name: name.into(), protocol_date: protocol_date.into(), } } } pub fn generate(service: Service, output_path: &...
Service
identifier_name
lib.rs
#![cfg_attr(feature = "unstable", feature(const_fn, drop_types_in_const))] #![cfg_attr(feature = "serde_derive", feature(proc_macro))] #![cfg_attr(feature = "nightly-testing", feature(plugin))] #![cfg_attr(feature = "nightly-testing", plugin(clippy))] #![cfg_attr(not(feature = "unstable"), deny(warnings))] extern crat...
extern crate regex; extern crate serde; extern crate serde_json; #[cfg(feature = "serde_derive")] #[macro_use] extern crate serde_derive; #[cfg(not(feature = "serde_derive"))] extern crate serde_codegen; use std::fs::File; use std::io::{Write, BufReader, BufWriter}; use std::path::Path; use botocore::Service as Boto...
extern crate lazy_static;
random_line_split
mozvisibility.js
;(function() { MozVisibility = { _MAX_TRIES: 10, _date: new Date, _tries: 0, _timer: null, _isVisible: undefined, _proxy: function(fn, context) { context = context || window; return function() { fn.apply(context, arguments); }; }, _getEvent: function() { if (!this._event) { ...
match[2] && parseInt(match[2]) >= 5 && // Firefox 5.0+ !document.visibilityState && !document.MozVisibilityState); // visibility API is not already supported }, emulate: function() { if (!this.canBeEmulated()) { return false; } this._invisibilityCheckTimeout = this._proxy(this._invisi...
return (window.top === window && // not in IFRAME
random_line_split
__main__.py
#!/usr/bin/env python import sys import argparse from .audio import create_tracks from .downloader import YouTube from .parser import parse_tracks_file from .prompt import wizard from .exceptions import WizardError def get_from_youtube(source): yt = YouTube(source) highest_bitrate = yt.audio_available.get('...
def main(): parser = argparse.ArgumentParser( prog='lobster', description='Cut audio files with a single command' ) parser.add_argument('--artist', '-ar', type=str, required=False, help='Name of the artist of the track this will be used '\ ...
""" Generates tracks under dest_dir using the source media file (download|local) """ get_media_file_src = {'youtube': get_from_youtube, 'local': get_from_local} media_file_src = get_media_file_src.get(source)(input) if from_wizard is None: audio_segments = parse_tra...
identifier_body