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
web-app-container.js
/*global require: false, module: false, process: false */ "use strict"; var mod = function( _, Promise, Options, Logger ) { var Log = Logger.create("AppContainer"); var WebAppContainer = function() { this.initialize.apply(this, arguments); }; _.extend(WebAppContainer.prototype, { initialize:...
}); }) }); return WebAppContainer; }; module.exports = mod( require("underscore"), require("bluebird"), require("../core/options"), require("../core/logging/logger") );
{ Log.error("Stopping due to reason:", reason); }
conditional_block
web-app-container.js
/*global require: false, module: false, process: false */ "use strict"; var mod = function( _, Promise, Options, Logger ) { var Log = Logger.create("AppContainer"); var WebAppContainer = function() { this.initialize.apply(this, arguments); }; _.extend(WebAppContainer.prototype, { initialize:...
this._app = opts.getOrError("app"); }, start: Promise.method(function() { return Promise .bind(this) .then(function() { return this._app.start(); }); }), stop: Promise.method(function(reason) { return this._app.stop().then(function() { if (re...
opts = Options.fromObject(opts)
random_line_split
webpack.dev.js
/** * Button Component for tingle * @author fushan * * Copyright 2014-2016, Tingle Team. * All rights reserved. */ var fs = require('fs'); var path = require('path'); var webpack = require('webpack'); module.exports = { cache: false, entry: { demo: './demo/src/index' }, output: { ...
exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-1'].map(function(item) { return require.resolve('babel-preset-' + item); }), plugins: [ ...
// node_modules都不需要经过babel解析
random_line_split
ChemGroup.js
import RCGroup from '../../RCGroup' import TransformGroup from '../../meshes/TransformGroup' function wrapper(Name, args) { const params = [Name].concat(args) return Name.bind(...params) } class ChemGroup extends RCGroup { constructor( geoParams, selection, colorer, mode, transforms, pol...
return this._mesh.getSubset(chunksList) } _changeSubsetOpacity(mask, value, innerOnly) { const chunksList = this._calcChunksList(mask, innerOnly) if (chunksList.length === 0) { return } this._geo.setOpacity(chunksList, value) } enableSubset(mask, innerOnly) { innerOnly = innerOn...
{ return [] }
conditional_block
ChemGroup.js
import RCGroup from '../../RCGroup' import TransformGroup from '../../meshes/TransformGroup' function wrapper(Name, args)
class ChemGroup extends RCGroup { constructor( geoParams, selection, colorer, mode, transforms, polyComplexity, material ) { super() if (this.constructor === ChemGroup) { throw new Error('Can not instantiate abstract class!') } this._selection = selection this...
{ const params = [Name].concat(args) return Name.bind(...params) }
identifier_body
ChemGroup.js
import RCGroup from '../../RCGroup' import TransformGroup from '../../meshes/TransformGroup' function wrapper(Name, args) { const params = [Name].concat(args) return Name.bind(...params) } class ChemGroup extends RCGroup { constructor( geoParams, selection, colorer, mode, transforms, pol...
(mask, innerOnly) { innerOnly = innerOnly !== undefined ? innerOnly : true this._changeSubsetOpacity(mask, 1.0, innerOnly) } disableSubset(mask, innerOnly) { innerOnly = innerOnly !== undefined ? innerOnly : true this._changeSubsetOpacity(mask, 0.0, innerOnly) } } export default ChemGroup
enableSubset
identifier_name
ChemGroup.js
import RCGroup from '../../RCGroup' import TransformGroup from '../../meshes/TransformGroup' function wrapper(Name, args) { const params = [Name].concat(args) return Name.bind(...params) } class ChemGroup extends RCGroup { constructor( geoParams, selection, colorer, mode, transforms, pol...
/** * Builds subset geometry by ATOMS index list * * @param {Number} mask - Representation mask * @param {Boolean} innerOnly - if true returns inner bonds only - without halves * @returns {Array} Subset geometry */ getSubset(mask, innerOnly) { innerOnly = innerOnly !== undefined ? innerOnly :...
throw new Error('ChemGroup subclass must override _makeGeoArgs() method') }
random_line_split
index.ts
import * as coinModules from '..'; import { BaseKeyPair } from '../coin/baseCoin'; import { KeyPairOptions } from '../coin/baseCoin/iface'; import { coins } from '@bitgo/statics'; import { NotSupported } from '../coin/baseCoin/errors'; export function register(coinName: string, source?: KeyPairOptions): BaseKeyPair {
if (key) { return new coinModules[key].KeyPair(source); } throw new NotSupported(`Coin ${coinName} not supported`); }
const sanitizedCoinName = coins.get(coinName.trim().toLowerCase()).family; const key = Object.keys(coinModules) .filter((k) => coinModules[k].KeyPair) // TODO(BG-40990): eth2 BLS keypair init error .find((k) => k.trim().toLowerCase() !== 'eth2' && k.trim().toLowerCase() === sanitizedCoinName);
random_line_split
index.ts
import * as coinModules from '..'; import { BaseKeyPair } from '../coin/baseCoin'; import { KeyPairOptions } from '../coin/baseCoin/iface'; import { coins } from '@bitgo/statics'; import { NotSupported } from '../coin/baseCoin/errors'; export function
(coinName: string, source?: KeyPairOptions): BaseKeyPair { const sanitizedCoinName = coins.get(coinName.trim().toLowerCase()).family; const key = Object.keys(coinModules) .filter((k) => coinModules[k].KeyPair) // TODO(BG-40990): eth2 BLS keypair init error .find((k) => k.trim().toLowerCase() !== 'eth2' ...
register
identifier_name
index.ts
import * as coinModules from '..'; import { BaseKeyPair } from '../coin/baseCoin'; import { KeyPairOptions } from '../coin/baseCoin/iface'; import { coins } from '@bitgo/statics'; import { NotSupported } from '../coin/baseCoin/errors'; export function register(coinName: string, source?: KeyPairOptions): BaseKeyPair
{ const sanitizedCoinName = coins.get(coinName.trim().toLowerCase()).family; const key = Object.keys(coinModules) .filter((k) => coinModules[k].KeyPair) // TODO(BG-40990): eth2 BLS keypair init error .find((k) => k.trim().toLowerCase() !== 'eth2' && k.trim().toLowerCase() === sanitizedCoinName); if (k...
identifier_body
index.ts
import * as coinModules from '..'; import { BaseKeyPair } from '../coin/baseCoin'; import { KeyPairOptions } from '../coin/baseCoin/iface'; import { coins } from '@bitgo/statics'; import { NotSupported } from '../coin/baseCoin/errors'; export function register(coinName: string, source?: KeyPairOptions): BaseKeyPair { ...
throw new NotSupported(`Coin ${coinName} not supported`); }
{ return new coinModules[key].KeyPair(source); }
conditional_block
field-wizard.component.ts
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { AddFieldForm, AppSettingsDto, createProperties, EditFieldForm, FieldDto, fieldTypes, Langu...
return (this.parent && this.parent.isLocalizable) || this.field['isLocalizable']; } constructor( private readonly schemasState: SchemasState, public readonly languagesState: LanguagesState, ) { } public ngOnInit() { if (this.parent) { this.fieldTypes = t...
random_line_split
field-wizard.component.ts
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { AddFieldForm, AppSettingsDto, createProperties, EditFieldForm, FieldDto, fieldTypes, Langu...
) { this.complete.emit(); } public addField(addNew: boolean, edit = false) { const value = this.addFieldForm.submit(); if (value) { this.schemasState.addField(this.schema, value, this.parent) .subscribe({ next: dto => { ...
mitComplete(
identifier_name
field-wizard.component.ts
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { AddFieldForm, AppSettingsDto, createProperties, EditFieldForm, FieldDto, fieldTypes, Langu...
public save(addNew = false) { if (!this.editForm) { return; } const value = this.editForm.submit(); if (value) { const properties = createProperties(this.field.properties.fieldType, value); this.schemasState.updateField(this.schema, this.field ...
const value = this.addFieldForm.submit(); if (value) { this.schemasState.addField(this.schema, value, this.parent) .subscribe({ next: dto => { this.field = dto; this.addFieldForm.submitCompleted({ newValue...
identifier_body
field-wizard.component.ts
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { AddFieldForm, AppSettingsDto, createProperties, EditFieldForm, FieldDto, fieldTypes, Langu...
} }
const properties = createProperties(this.field.properties.fieldType, value); this.schemasState.updateField(this.schema, this.field as RootFieldDto, { properties }) .subscribe({ next: () => { this.editForm!.submitCompleted(); ...
conditional_block
RenderTextureSystem.ts
import { System } from '../System'; import { Rectangle } from '@pixi/math'; import { BUFFER_BITS } from '@pixi/constants'; import type { Renderer } from '../Renderer'; import type { RenderTexture } from './RenderTexture'; import type { BaseRenderTexture } from './BaseRenderTexture'; import type { MaskData } from '../m...
}
{ this.bind(null); }
identifier_body
RenderTextureSystem.ts
import { System } from '../System'; import { Rectangle } from '@pixi/math'; import { BUFFER_BITS } from '@pixi/constants'; import type { Renderer } from '../Renderer'; import type { RenderTexture } from './RenderTexture'; import type { BaseRenderTexture } from './BaseRenderTexture'; import type { MaskData } from '../m...
viewportFrame.x = destinationFrame.x * resolution; viewportFrame.y = destinationFrame.y * resolution; viewportFrame.width = destinationFrame.width * resolution; viewportFrame.height = destinationFrame.height * resolution; this.renderer.framebuffer.bind(framebuffer, viewportFra...
{ resolution = renderer.resolution; if (!sourceFrame) { tempRect.width = renderer.screen.width; tempRect.height = renderer.screen.height; sourceFrame = tempRect; } if (!destinationFrame) { ...
conditional_block
RenderTextureSystem.ts
import { System } from '../System'; import { Rectangle } from '@pixi/math'; import { BUFFER_BITS } from '@pixi/constants'; import type { Renderer } from '../Renderer'; import type { RenderTexture } from './RenderTexture'; import type { BaseRenderTexture } from './BaseRenderTexture'; import type { MaskData } from '../m...
this.defaultMaskStack = []; // empty render texture? /** * Render texture * @member {PIXI.RenderTexture} * @readonly */ this.current = null; /** * Source frame * @member {PIXI.Rectangle} * @readonly */ ...
* List of masks for the StencilSystem * @member {PIXI.Graphics[]} * @readonly */
random_line_split
RenderTextureSystem.ts
import { System } from '../System'; import { Rectangle } from '@pixi/math'; import { BUFFER_BITS } from '@pixi/constants'; import type { Renderer } from '../Renderer'; import type { RenderTexture } from './RenderTexture'; import type { BaseRenderTexture } from './BaseRenderTexture'; import type { MaskData } from '../m...
(): void // screenWidth, screenHeight) { // resize the root only! this.bind(null); } /** * Resets renderTexture state */ reset(): void { this.bind(null); } }
resize
identifier_name
pd.py
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2018 Max Weller ## Copyright (C) 2019 DreamSourceLab <support@dreamsourcelab.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Sof...
('cmdbit', 'Command bit'), ('databit', 'Data bit'), ('cmd', 'Command'), ('data', 'Data byte'), ('warnings', 'Human-readable warnings'), ) annotation_rows = ( ('bits', 'Bits', (ann_cmdbit, ann_databit)), ('commands', 'Commands', (ann_cmd,)), ('data'...
random_line_split
pd.py
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2018 Max Weller ## Copyright (C) 2019 DreamSourceLab <support@dreamsourcelab.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Sof...
def metadata(self, key, value): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putbit(self, ss, es, typ, value): self.put(ss, es, self.out_ann, [typ, ['%s' % (value)]]) def putdata(self...
self.cmdbits = [] self.databits = []
identifier_body
pd.py
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2018 Max Weller ## Copyright (C) 2019 DreamSourceLab <support@dreamsourcelab.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Sof...
(self): self.samplerate = None self.reset() def reset(self): self.cmdbits = [] self.databits = [] def metadata(self, key, value): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value def start(self): self.out_ann = self.register(srd.OUTPUT...
__init__
identifier_name
pd.py
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2018 Max Weller ## Copyright (C) 2019 DreamSourceLab <support@dreamsourcelab.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Sof...
elif (self.matched & (0b1 << 0)) and ce == 0 and clk == 0: # Falling clk edge and data mode. bitstart = self.samplenum (clk, d, ce) = self.wait([{'skip': int(2.5 * (1e6 / self.samplerate))}, {0: 'r'}, {2: 'e'}]) # Wait 25 us for data ready. if...
bitstart = self.samplenum self.wait({0: 'f'}) self.cmdbits = [(d, bitstart, self.samplenum)] + self.cmdbits if len(self.cmdbits) > 24: self.cmdbits = self.cmdbits[0:24] self.putbit(bitstart, self.samplenum, ann_cmdbit, d)
conditional_block
setup.py
import sys from setuptools import setup, find_packages
if sys.version_info.major >= 3: requirements.append('suds-py3') else: requirements.append('suds') setup( name="lather_ui", version=version, author="Adam Clemons", author_email="adam@adamclmns.com", description="A simple SOAP client UI.", packages=find_packages('.', exclude=['docs', 'tes...
version = '0.1.0' requirements = ['lxml']
random_line_split
setup.py
import sys from setuptools import setup, find_packages version = '0.1.0' requirements = ['lxml'] if sys.version_info.major >= 3:
else: requirements.append('suds') setup( name="lather_ui", version=version, author="Adam Clemons", author_email="adam@adamclmns.com", description="A simple SOAP client UI.", packages=find_packages('.', exclude=['docs', 'tests']), entry_points={ 'gui_scripts': [ 'Lat...
requirements.append('suds-py3')
conditional_block
settings.py
# -*- coding: utf-8 -*- # Copyright (c) 2013 - 2018 CoNWeT Lab., Universidad Politécnica de Madrid # This file belongs to the business-charging-backend # of the Business API Ecosystem. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License...
('0 5 * * *', 'django.core.management.call_command', ['pending_charges_daemon']), ('0 6 * * *', 'django.core.management.call_command', ['resend_cdrs']), ('0 4 * * *', 'django.core.management.call_command', ['resend_upgrade']) ] CLIENTS = { 'paypal': 'wstore.charging_engine.payment_client.paypal_client....
CRONJOBS = [
random_line_split
settings.py
# -*- coding: utf-8 -*- # Copyright (c) 2013 - 2018 CoNWeT Lab., Universidad Politécnica de Madrid # This file belongs to the business-charging-backend # of the Business API Ecosystem. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License...
SITE = environ.get('BAE_SERVICE_HOST', SITE) LOCAL_SITE = environ.get('BAE_CB_LOCAL_SITE', LOCAL_SITE) CATALOG = environ.get('BAE_CB_CATALOG', CATALOG) INVENTORY = environ.get('BAE_CB_INVENTORY', INVENTORY) ORDERING = environ.get('BAE_CB_ORDERING', ORDERING) BILLING = environ.get('BAE_CB_BILLING', BILLING) RSS = envi...
ERIFY_REQUESTS = VERIFY_REQUESTS == 'True'
conditional_block
SWMMOpenMINoGlobalsPythonTest.py
from ctypes import* import math lib = cdll.LoadLibrary("Z:\\Documents\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMIComponent\\bin\\Debug\\SWMMComponent.dll") print(lib) print("\n") finp = b"Z:\\Documents\\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMINoGlobalsPythonTest\\test.inp" frpt = b"Z:\\Documents\\Pr...
temp = math.floor(elapsedTime.value) temp = (elapsedTime.value - temp) * 24.0 theHour = int(temp) #print("\b\b\b\b\b\b\b\b\b\b\b\b\b\b") #print("\n") print "Hour " , str(theHour) , " Day " , str(theDay) , ' \r',...
random_line_split
SWMMOpenMINoGlobalsPythonTest.py
from ctypes import* import math lib = cdll.LoadLibrary("Z:\\Documents\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMIComponent\\bin\\Debug\\SWMMComponent.dll") print(lib) print("\n") finp = b"Z:\\Documents\\Projects\\SWMMOpenMIComponent\\Source\\SWMMOpenMINoGlobalsPythonTest\\test.inp" frpt = b"Z:\\Documents\\Pr...
lib.swmm_end(project) lib.swmm_report(project) lib.swmm_close(project)
eak
conditional_block
kn.js
/************************************************************* * * MathJax/localization/kn/kn.js * * Copyright (c) 2009-2017 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License");
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the ...
* 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
random_line_split
closure.rs
// Copyright 2012-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-MI...
let tcx = ccx.tcx(); debug!("get_wrapper_for_bare_fn(closure_ty={})", closure_ty.repr(tcx)); let f = match ty::get(closure_ty).sty { ty::ty_closure(ref f) => f, _ => { ccx.sess().bug(format!("get_wrapper_for_bare_fn: \ expected a closure ty,...
match ccx.closure_bare_wrapper_cache.borrow().find(&fn_ptr) { Some(&llval) => return llval, None => {} }
random_line_split
closure.rs
// Copyright 2012-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-MI...
<'a>(bcx: &'a Block<'a>, closure_ty: ty::t, def: def::Def, fn_ptr: ValueRef) -> DatumBlock<'a, Expr> { let scratch = rvalue_scratch_datum(bcx, closure_ty, "__adjust");...
make_closure_from_bare_fn
identifier_name
closure.rs
// Copyright 2012-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-MI...
pub fn make_closure_from_bare_fn<'a>(bcx: &'a Block<'a>, closure_ty: ty::t, def: def::Def, fn_ptr: ValueRef) -> DatumBlock<'a, Expr> { let scratch = rvalue_scratch_d...
{ let def_id = match def { def::DefFn(did, _) | def::DefStaticMethod(did, _, _) | def::DefVariant(_, did, _) | def::DefStruct(did) => did, _ => { ccx.sess().bug(format!("get_wrapper_for_bare_fn: \ expected a statically resolved fn, got \ ...
identifier_body
Page.tsx
import * as React from "react";
<div className="container"> <h2>About</h2> <p>Arul "Socrates" Aruldas is a wise old sage often given to spouting sayings that convey wisdom and knowledge far beyond his years. It was felt that these gems could not be allowed to slip through the cracks. Here they are preserved for posterity. Noted down by ...
const Page = () => (
random_line_split
pythontest.py
#!/usr/bin/env python import json import unittest import numpy as np from math import pi import sys sys.path.insert(0,'../') from pyfaunus import * # Dictionary defining input d = {} d['geometry'] = { 'type': 'cuboid', 'length': 50 } d['atomlist'] = [ { 'Na': dict( r=2.0, eps=0.05, q=1.0, tfe=1.0 ) }, ...
unittest.main()
conditional_block
pythontest.py
#!/usr/bin/env python import json import unittest import numpy as np from math import pi import sys sys.path.insert(0,'../') from pyfaunus import * # Dictionary defining input d = {} d['geometry'] = { 'type': 'cuboid', 'length': 50 } d['atomlist'] = [ { 'Na': dict( r=2.0, eps=0.05, q=1.0, tfe=1.0 ) }, ...
(unittest.TestCase): def test_pairpot(self): d = { 'default' : [ { 'sasa': { 'molarity': 1.5, 'radius': 1.4, 'shift': False } } ] } pot = FunctorPotential( d ) r = np.linspace(0,10,5) u = np.array( [pot.energy( spc.p[0], spc.p[1], [0,0,i] ) for i in r] ) ...
TestSASA
identifier_name
pythontest.py
#!/usr/bin/env python import json import unittest import numpy as np from math import pi import sys sys.path.insert(0,'../') from pyfaunus import * # Dictionary defining input d = {} d['geometry'] = { 'type': 'cuboid', 'length': 50 } d['atomlist'] = [ { 'Na': dict( r=2.0, eps=0.05, q=1.0, tfe=1.0 ) }, ...
# Geometry class TestGeometry(unittest.TestCase): def test_cuboid(self): geo = Chameleon( dict(type="cuboid", length=[2,3,4]) ) V = geo.getVolume(); self.assertAlmostEqual(V, 2*3*4, msg="volume") a = geo.boundary( [1.1, 1.5, -2.001] ); self.assertAlmostEqual(a[0], -0.9) ...
H = Hamiltonian(spc, [ {'sasa' : {'molarity': 1.5, 'radius': 1.4}} ] ) spc.p[0].pos = [0,0,0] # fix 1st particle in origin c = Change() # change object telling that a full energy calculation c.all = True; # should be performed when calling `energy()` u = [] r =...
identifier_body
pythontest.py
#!/usr/bin/env python import json import unittest import numpy as np from math import pi import sys sys.path.insert(0,'../') from pyfaunus import * # Dictionary defining input d = {} d['geometry'] = { 'type': 'cuboid', 'length': 50 } d['atomlist'] = [ { 'Na': dict( r=2.0, eps=0.05, q=1.0, tfe=1.0 ) }, ...
analysis = Analysis(spc, pot, d['analysis']) # Test temperature class TestGlobals(unittest.TestCase): def test_temperature(self): self.assertAlmostEqual(getTemperature(), 300) # Loop over atom types for i in atoms: print("atom name and diameter:", i.name, i.sigma) # Test Coulomb class TestCoulomb(...
random_line_split
network.py
import matplotlib.pyplot as plt import numpy as np import os import time import yaml from sklearn.learning_curve import learning_curve from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential, model_from_yaml from keras.wrappers.scikit_learn i...
(model, params_string): ''' saves trained model to directory and files depending on settings variables :param model: model to be saved :param params_string: a yaml string of parameters used for the model: crime_type, period, grid_size and seasonality ''' folder = settings.MODEL_DIR archi = ...
save_trained_model
identifier_name
network.py
import matplotlib.pyplot as plt import numpy as np import os import time import yaml from sklearn.learning_curve import learning_curve from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential, model_from_yaml from keras.wrappers.scikit_learn i...
def predict_next(model, **params): ''' predicts next crime hotspots :param model: the model to be used for prediction :param **params: a yaml string of the parameters used by the model ''' vectors = vectorize(**params) print 'Loading Data...' dim = len(vectors[0]) result = np.ar...
''' reconstruct trained model from saved files :rtype: a tuple of the model constructed and a yaml string of parameters used ''' folder = settings.MODEL_DIR archi = folder + settings.MODEL_ARCHITECTURE weights = folder + settings.MODEL_WEIGHTS params = folder + settings.MODEL_PARAMS ...
identifier_body
network.py
import matplotlib.pyplot as plt import numpy as np import os import time import yaml from sklearn.learning_curve import learning_curve from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential, model_from_yaml from keras.wrappers.scikit_learn i...
crime_verbose = crime_type if crime_type is not None else "ALL" output_folder = settings.OUTPUTS_DIR + \ 'Results_{0}_{1}_{2}_{3}/'.format( grid_size, crime_verbose, period, seasonal) if not os.path.exists(output_folder): os.makedirs(output_folder) results_file = output_fo...
print len(data) print len(predicted[x]) correct = 0 total = 0 truepos = 0 falsepos = 0 trueneg = 0 falseneg = 0 for y, node in enumerate(data): total += 1 if predicted[x][y] > 0: norm_predicted[x][y] = 1 ...
conditional_block
network.py
import matplotlib.pyplot as plt import numpy as np import os import time import yaml from sklearn.learning_curve import learning_curve from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential, model_from_yaml from keras.wrappers.scikit_learn i...
results += "Average F1 Score:" + str(np.average(f1scr)) with open(results_file, "w") as output_file: output_file.write(results) params = { 'grid_size': grid_size, 'period': period, 'crime_type': crime_type if crime_type is not None else 'all', 'seasonal': seasonal, ...
np.savetxt(X_test_file, X_test, fmt='%d') np.savetxt(y_test_file, y_test, fmt='%d') np.savetxt(predicted_file, norm_predicted, fmt='%d') results = "Average Accuracy:" + str(np.average(accuracy)) + '\n'
random_line_split
trace.py
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, 2013, 2015 Rocky Bernstein rocky@gnu.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at ...
(Mbase_subcmd.DebuggerSetBoolSubcommand): """**set trace** [ **on** | **off** ] Set event tracing. See also: --------- `set events`, and `show trace`. """ in_list = True min_abbrev = len('trace') # Must use at least "set trace" short_help = "Set event tracing" pass if __name__ == '__main__...
SetTrace
identifier_name
trace.py
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, 2013, 2015 Rocky Bernstein rocky@gnu.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at ...
in_list = True min_abbrev = len('trace') # Must use at least "set trace" short_help = "Set event tracing" pass if __name__ == '__main__': from trepan.processor.command.set_subcmd import __demo_helper__ as Mhelper sub = Mhelper.demo_run(SetTrace) d = sub.proc.debugger for args in ([...
--------- `set events`, and `show trace`. """
random_line_split
trace.py
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, 2013, 2015 Rocky Bernstein rocky@gnu.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at ...
from trepan.processor.command.set_subcmd import __demo_helper__ as Mhelper sub = Mhelper.demo_run(SetTrace) d = sub.proc.debugger for args in (['on'], ['off']): sub.run(args) print(d.settings['trace']) pass pass
conditional_block
trace.py
# -*- coding: utf-8 -*- # Copyright (C) 2009-2010, 2013, 2015 Rocky Bernstein rocky@gnu.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at ...
if __name__ == '__main__': from trepan.processor.command.set_subcmd import __demo_helper__ as Mhelper sub = Mhelper.demo_run(SetTrace) d = sub.proc.debugger for args in (['on'], ['off']): sub.run(args) print(d.settings['trace']) pass pass
"""**set trace** [ **on** | **off** ] Set event tracing. See also: --------- `set events`, and `show trace`. """ in_list = True min_abbrev = len('trace') # Must use at least "set trace" short_help = "Set event tracing" pass
identifier_body
quotasv2.py
# Copyright 2011 OpenStack Foundation. # 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 req...
def update(self, request, id, body=None): self._check_admin(request.context) if self._update_extended_attributes: self._update_attributes() body = base.Controller.prepare_request_body( request.context, body, False, self._resource_name, EXTENDED_ATTRIBUTE...
self._check_admin(request.context) self._driver.delete_tenant_quota(request.context, id)
identifier_body
quotasv2.py
# Copyright 2011 OpenStack Foundation. # 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 req...
@classmethod def get_updated(cls): return "2012-07-29T10:00:00-00:00" @classmethod def get_resources(cls): """Returns Ext Resources.""" controller = resource.Resource( QuotaSetsController(manager.NeutronManager.get_plugin()), faults=base.FAULT_MAP) ...
return description
random_line_split
quotasv2.py
# Copyright 2011 OpenStack Foundation. # 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 req...
(self, plugin): self._resource_name = RESOURCE_NAME self._plugin = plugin self._driver = importutils.import_class( cfg.CONF.QUOTAS.quota_driver ) self._update_extended_attributes = True def _update_attributes(self): for quota_resource in resource_registry...
__init__
identifier_name
quotasv2.py
# Copyright 2011 OpenStack Foundation. # 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 req...
return {self._resource_name: self._get_quotas(request, id)} def _check_admin(self, context, reason=_("Only admin can view or configure quota")): if not context.is_admin: raise n_exc.AdminRequired(reason=reason) def delete(self, request, id): self._chec...
self._check_admin(request.context, reason=_("Only admin is authorized " "to access quotas for another tenant"))
conditional_block
symmetriccipher.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate crypto...
() { let message = "Hello World!"; let mut key: [u8; 32] = [0; 32]; let mut iv: [u8; 16] = [0; 16]; // In a real program, the key and iv may be determined // using some other mechanism. If a password is to be used // as a key, an algorithm like PBKDF2, Bcrypt, or Scrypt (all // supported b...
main
identifier_name
symmetriccipher.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate crypto...
BufferResult::BufferUnderflow => break, BufferResult::BufferOverflow => { } } } Ok(final_result) } // Decrypts a buffer with the given key and iv using // AES-256/CBC/Pkcs encryption. // // This function is very similar to encrypt(), so, please reference // comments in that fun...
match result {
random_line_split
symmetriccipher.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate crypto...
fn main() { let message = "Hello World!"; let mut key: [u8; 32] = [0; 32]; let mut iv: [u8; 16] = [0; 16]; // In a real program, the key and iv may be determined // using some other mechanism. If a password is to be used // as a key, an algorithm like PBKDF2, Bcrypt, or Scrypt (all // su...
{ let mut decryptor = aes::cbc_decryptor( aes::KeySize::KeySize256, key, iv, blockmodes::PkcsPadding); let mut final_result = Vec::<u8>::new(); let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data); let mut buffer = [0; 4096]; let mut write...
identifier_body
secretmanager_v1_generated_secret_manager_service_set_iam_policy_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END secretmanager_v1_generated_SecretManagerService_SetIamPolicy_sync]
client = secretmanager_v1.SecretManagerServiceClient() # Initialize request argument(s) request = secretmanager_v1.SetIamPolicyRequest( resource="resource_value", ) # Make the request response = client.set_iam_policy(request=request) # Handle the response print(response)
identifier_body
secretmanager_v1_generated_secret_manager_service_set_iam_policy_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Initialize request argument(s) request = secretmanager_v1.SetIamPolicyRequest( resource="resource_value", ) # Make the request response = client.set_iam_policy(request=request) # Handle the response print(response) # [END secretmanager_v1_generated_SecretManagerService_SetIamPol...
random_line_split
secretmanager_v1_generated_secret_manager_service_set_iam_policy_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): # Create a client client = secretmanager_v1.SecretManagerServiceClient() # Initialize request argument(s) request = secretmanager_v1.SetIamPolicyRequest( resource="resource_value", ) # Make the request response = client.set_iam_policy(request=request) # Handle the response...
sample_set_iam_policy
identifier_name
ReplicatedMapIsEmptyCodec.ts
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required ...
return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET); } }
static decodeResponse(clientMessage: ClientMessage): boolean { const initialFrame = clientMessage.nextFrame();
random_line_split
ReplicatedMapIsEmptyCodec.ts
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required ...
(clientMessage: ClientMessage): boolean { const initialFrame = clientMessage.nextFrame(); return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET); } }
decodeResponse
identifier_name
package.py
#!/usr/bin/env python import pprint import json import subprocess root_dir = subprocess.check_output([ 'git', 'rev-parse', '--show-toplevel' ]).decode().strip() def path(s): return "{}/{}".format(root_dir, s) # Create the output directory subprocess.call(['mkdir', '-p', path('ec2instances/info')]) # M...
with open(path('www/instances.json'), 'r') as input: ec2 = json.loads(input.read()) output.write("ec2 = {}".format(pprint.pformat(ec2))) output.write("\n") with open(path('www/rds/instances.json'), 'r') as input: rds = json.loads(input.read()) output.write("rds = {}".format...
# Final output will look like the following, though pretty-printed: # # ec2 = [{'instance_type': 't2.micro', ...}, ...] # rds = [{'instance_type': 'db.t2.small', ...}, ...] #
random_line_split
package.py
#!/usr/bin/env python import pprint import json import subprocess root_dir = subprocess.check_output([ 'git', 'rev-parse', '--show-toplevel' ]).decode().strip() def
(s): return "{}/{}".format(root_dir, s) # Create the output directory subprocess.call(['mkdir', '-p', path('ec2instances/info')]) # Make the project a module subprocess.call(['touch', path('ec2instances/__init__.py')]) with open(path('ec2instances/info/__init__.py'), 'w') as output: # Final output will look...
path
identifier_name
package.py
#!/usr/bin/env python import pprint import json import subprocess root_dir = subprocess.check_output([ 'git', 'rev-parse', '--show-toplevel' ]).decode().strip() def path(s):
# Create the output directory subprocess.call(['mkdir', '-p', path('ec2instances/info')]) # Make the project a module subprocess.call(['touch', path('ec2instances/__init__.py')]) with open(path('ec2instances/info/__init__.py'), 'w') as output: # Final output will look like the following, though pretty-printed:...
return "{}/{}".format(root_dir, s)
identifier_body
training_stsbenchmark_continue_training.py
""" This example loads the pre-trained SentenceTransformer model 'nli-distilroberta-base-v2' from the server. It then fine-tunes this model for some epochs on the STS benchmark dataset. Note: In this example, you must specify a SentenceTransformer model. If you want to fine-tune a huggingface/transformers model like b...
# Development set: Measure correlation between cosine score and gold labels logging.info("Read STSbenchmark dev dataset") evaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, name='sts-dev') # Configure the training. We skip evaluation in this example warmup_steps = math.ceil(len(train_dataloade...
train_dataloader = DataLoader(train_samples, shuffle=True, batch_size=train_batch_size) train_loss = losses.CosineSimilarityLoss(model=model)
random_line_split
training_stsbenchmark_continue_training.py
""" This example loads the pre-trained SentenceTransformer model 'nli-distilroberta-base-v2' from the server. It then fine-tunes this model for some epochs on the STS benchmark dataset. Note: In this example, you must specify a SentenceTransformer model. If you want to fine-tune a huggingface/transformers model like b...
# Read the dataset model_name = 'nli-distilroberta-base-v2' train_batch_size = 16 num_epochs = 4 model_save_path = 'output/training_stsbenchmark_continue_training-'+model_name+'-'+datetime.now().strftime("%Y-%m-%d_%H-%M-%S") # Load a pre-trained sentence transformer model model = SentenceTransformer(model_name)...
util.http_get('https://sbert.net/datasets/stsbenchmark.tsv.gz', sts_dataset_path)
conditional_block
EditSourceControls.tsx
import React, { Component } from 'react' import styled from 'styled-components' import { borderedInput } from '@artsy/reaction/dist/Components/Mixins' import Button from "@artsy/reaction/dist/Components/Buttons/Default" interface Props { onApply: (news_source: { title?: string, url?: string } | null) => void sourc...
(props: Props) { super(props) const source = props.source this.state = { title: source ? source.title : "", url: source ? source.url : "" } } render() { return ( <EditSourceContainer> <InputContainer> <Input name={"title"} value={this.stat...
constructor
identifier_name
EditSourceControls.tsx
import React, { Component } from 'react' import styled from 'styled-components' import { borderedInput } from '@artsy/reaction/dist/Components/Mixins' import Button from "@artsy/reaction/dist/Components/Buttons/Default" interface Props { onApply: (news_source: { title?: string, url?: string } | null) => void sourc...
<Input name={"title"} value={this.state.title} placeholder={"Enter source name"} onChange={(event) => this.setState({title: event.target.value})} /> <ApplyInputContainer> <LinkInput name={"url"} value={this.state.url} ...
<InputContainer>
random_line_split
EditSourceControls.tsx
import React, { Component } from 'react' import styled from 'styled-components' import { borderedInput } from '@artsy/reaction/dist/Components/Mixins' import Button from "@artsy/reaction/dist/Components/Buttons/Default" interface Props { onApply: (news_source: { title?: string, url?: string } | null) => void sourc...
render() { return ( <EditSourceContainer> <InputContainer> <Input name={"title"} value={this.state.title} placeholder={"Enter source name"} onChange={(event) => this.setState({title: event.target.value})} /> <ApplyInputContainer> ...
{ super(props) const source = props.source this.state = { title: source ? source.title : "", url: source ? source.url : "" } }
identifier_body
extensionsFileTemplate.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
properties: { recommendations: { type: 'array', description: localize('app.extensions.json.recommendations', "List of extensions recommendations. The identifier of an extension is always '${publisher}.${name}'. For example: 'vscode.csharp'."), items: { type: 'string', pattern: EXTENSION_IDENTIFIER_P...
title: localize('app.extensions.json.title', "Extensions"),
random_line_split
markdown.test.ts
* to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed und...
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file
random_line_split
index.js
'use strict' var Transform = require('stream').Transform , util = require('util') , Segment = require('./segment') , Message = require('./message') , utils = require('./utils') // MLP end frames var FS = String.fromCharCode(0x1c) , CR = String.fromCharCode(0x0d) exports.Message = Message exports.Segment = ...
() { var opts = { objectMode: true } if (!(this instanceof Parser)) return new Parser(opts) Transform.call(this, opts) this._messages = [] this.current = null } util.inherits(Parser, Transform) Parser.prototype._tryParseSegment = function _tryParseSegment(data, delims) { var self = this try { ...
Parser
identifier_name
index.js
'use strict' var Transform = require('stream').Transform , util = require('util') , Segment = require('./segment') , Message = require('./message') , utils = require('./utils') // MLP end frames var FS = String.fromCharCode(0x1c) , CR = String.fromCharCode(0x0d) exports.Message = Message exports.Segment = ...
util.inherits(Parser, Transform) Parser.prototype._tryParseSegment = function _tryParseSegment(data, delims) { var self = this try { return new Segment(data, delims) } catch (err) { self.emit('error', err) return null } } /** * Transform for parser * * **NOTE: The stream should have been pipe...
{ var opts = { objectMode: true } if (!(this instanceof Parser)) return new Parser(opts) Transform.call(this, opts) this._messages = [] this.current = null }
identifier_body
index.js
'use strict' var Transform = require('stream').Transform , util = require('util') , Segment = require('./segment') , Message = require('./message') , utils = require('./utils') // MLP end frames var FS = String.fromCharCode(0x1c) , CR = String.fromCharCode(0x0d) exports.Message = Message exports.Segment = ...
* @param {Function} cb function(err, res) * @api private */ Parser.prototype._transform = function(data, encoding, done) { var delims = this.current ? this.current.delimiters() : null var segment = this._tryParseSegment(data, delims) if (!segment) return if (segment && segment.parsed) { var isH...
* @param {String} encoding The encoding of the buffer
random_line_split
postgres-fill.d.ts
declare module 'postgres-fill' { function PostgresFill( log: (message: string) => any, connection: { host: string, user: string, password: string, database: string, port: number, }, structure: DBStructure[], verbose?: boolean ): Promise<any>; module PostgresFill {...
} }
unique?: string[], index?: string[],
random_line_split
phantom.js
/* * grunt-contrib-qunit * http://gruntjs.com/ * * Copyright (c) 2014 "Cowboy" Ben Alman, contributors * Licensed under the MIT license. */ (function () { 'use strict'; // Don't re-order tests. QUnit.config.reorder = false; // Run tests serially, not in parallel. QUnit.config.autorun = false; // Se...
lse { console.log('\u00D7 ' + obj.failed + ' tests failed in "' + obj.name + '" module') } sendMessage('qunit.moduleDone', obj.name, obj.failed, obj.passed, obj.total) }); QUnit.begin(function () { sendMessage('qunit.begin'); console.log('\n\nStarting test suite'); console.log('==========...
console.log('\r\u221A All tests passed in "' + obj.name + '" module') } e
conditional_block
phantom.js
/* * grunt-contrib-qunit * http://gruntjs.com/ * * Copyright (c) 2014 "Cowboy" Ben Alman, contributors * Licensed under the MIT license. */ (function () { 'use strict'; // Don't re-order tests. QUnit.config.reorder = false; // Run tests serially, not in parallel. QUnit.config.autorun = false; // Se...
() { var args = [].slice.call(arguments); alert(JSON.stringify(args)) } // These methods connect QUnit to PhantomJS. QUnit.log(function (obj) { // What is this I don’t even if (obj.message === '[object Object], undefined:undefined') { return } // Parse some stuff before sending it....
sendMessage
identifier_name
phantom.js
/* * grunt-contrib-qunit * http://gruntjs.com/ * * Copyright (c) 2014 "Cowboy" Ben Alman, contributors * Licensed under the MIT license. */ (function () { 'use strict'; // Don't re-order tests. QUnit.config.reorder = false; // Run tests serially, not in parallel. QUnit.config.autorun = false; // Se...
// These methods connect QUnit to PhantomJS. QUnit.log(function (obj) { // What is this I don’t even if (obj.message === '[object Object], undefined:undefined') { return } // Parse some stuff before sending it. var actual; var expected; if (!obj.result) { // Dumping large ...
{ var args = [].slice.call(arguments); alert(JSON.stringify(args)) }
identifier_body
phantom.js
/* * grunt-contrib-qunit * http://gruntjs.com/ * * Copyright (c) 2014 "Cowboy" Ben Alman, contributors * Licensed under the MIT license. */ (function () { 'use strict'; // Don't re-order tests. QUnit.config.reorder = false; // Run tests serially, not in parallel. QUnit.config.autorun = false; // Se...
console.log('\u00D7 ' + obj.failed + ' tests failed in "' + obj.name + '" module') } sendMessage('qunit.moduleDone', obj.name, obj.failed, obj.passed, obj.total) }); QUnit.begin(function () { sendMessage('qunit.begin'); console.log('\n\nStarting test suite'); console.log('================...
} else {
random_line_split
sketch.js
var x; var y; var d; var speedX; var speedY; function setup() { createCanvas(windowWidth, windowHeight); background(0, 255, 255); d = 100; x = random(d, width-d); y = random(d, height-d); speedX = random(5, 15); speedY = random(5, 15); } function draw() { background(0, 255, 255); ellipse(x, y, d, ...
y = y + speedY; //d = d + 1; if(y > height - d/2) { speedY = -1 * abs(speedY); fill(random(255), random(255), random(255)) } if(y < d/2) { speedY = abs(speedY); } if(x > width - d/2) { speedX = -1 * abs(speedX); } if(x < d/2) { speedX = abs(speedX); } }
x = x + speedX;
random_line_split
sketch.js
var x; var y; var d; var speedX; var speedY; function setup()
function draw() { background(0, 255, 255); ellipse(x, y, d, d); x = x + speedX; y = y + speedY; //d = d + 1; if(y > height - d/2) { speedY = -1 * abs(speedY); fill(random(255), random(255), random(255)) } if(y < d/2) { speedY = abs(speedY); } if(x > width - d/2) { speedX = -1 * ...
{ createCanvas(windowWidth, windowHeight); background(0, 255, 255); d = 100; x = random(d, width-d); y = random(d, height-d); speedX = random(5, 15); speedY = random(5, 15); }
identifier_body
sketch.js
var x; var y; var d; var speedX; var speedY; function setup() { createCanvas(windowWidth, windowHeight); background(0, 255, 255); d = 100; x = random(d, width-d); y = random(d, height-d); speedX = random(5, 15); speedY = random(5, 15); } function
() { background(0, 255, 255); ellipse(x, y, d, d); x = x + speedX; y = y + speedY; //d = d + 1; if(y > height - d/2) { speedY = -1 * abs(speedY); fill(random(255), random(255), random(255)) } if(y < d/2) { speedY = abs(speedY); } if(x > width - d/2) { speedX = -1 * abs(speedX); ...
draw
identifier_name
sketch.js
var x; var y; var d; var speedX; var speedY; function setup() { createCanvas(windowWidth, windowHeight); background(0, 255, 255); d = 100; x = random(d, width-d); y = random(d, height-d); speedX = random(5, 15); speedY = random(5, 15); } function draw() { background(0, 255, 255); ellipse(x, y, d, ...
}
{ speedX = abs(speedX); }
conditional_block
artikel.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-bac...
@Component({ selector: 'page-artikel', templateUrl: 'artikel.html' }) export class ArtikelPage { public posts; public limit = 0; public httpErr = false; constructor(public navCtrl: NavController, public http: Http, public actionSheetCtrl: ActionSheetController, public toastCtrl: ToastController) { this...
*/
random_line_split
artikel.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-bac...
ionViewWillEnter() { this.limit = 0; this.getData(); } notif() { this.navCtrl.push(NotifikasiPage); } doRefresh(refresher) { this.limit =0; setTimeout(() => { this.getData(); refresher.complete(); }, 1500); } getData() { this.http.get('http://cybex.ipb.ac.id/ap...
{ //this.getData(); }
identifier_body
artikel.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-bac...
() { //this.getData(); } ionViewWillEnter() { this.limit = 0; this.getData(); } notif() { this.navCtrl.push(NotifikasiPage); } doRefresh(refresher) { this.limit =0; setTimeout(() => { this.getData(); refresher.complete(); }, 1500); } getData() { this.http....
ionViewDidLoad
identifier_name
artikel.ts
import { Component } from '@angular/core'; import { NavController, ToastController } from 'ionic-angular'; import { Http } from '@angular/http'; import { ActionSheetController } from 'ionic-angular'; import { NotifikasiPage } from '../notifikasi/notifikasi'; import { ArtikelBacaPage } from '../artikel-baca/artikel-bac...
else{ let toast = this.toastCtrl.create({ message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); } this.httpErr = true; } }
{ let toast = this.toastCtrl.create({ message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.', position: 'bottom', showCloseButton: true, closeButtonText: 'X' }); toast.present(); }
conditional_block
clang.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
else: temp_path = temp.relpath("input%d.cc" % i) with open(temp_path, "w") as output_file: output_file.write(code) input_files.append(temp_path) if options: cmd += options cmd += ["-o", output] cmd += input_files proc = subprocess.Pope...
input_files.append(code)
conditional_block
clang.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(inputs, output=None, options=None, cc=None): """Create llvm text ir. Parameters ---------- inputs : list of str List of input files name or code source. output : str, optional Output file, if it is none a temporary file is created options : list The list of ad...
create_llvm
identifier_name
clang.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
"""Create llvm text ir. Parameters ---------- inputs : list of str List of input files name or code source. output : str, optional Output file, if it is none a temporary file is created options : list The list of additional options string. cc : str, optional ...
identifier_body
clang.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
options : list The list of additional options string. cc : str, optional The clang compiler, if not specified, we will try to guess the matched clang version. Returns ------- code : str The generated llvm text IR. """ cc = cc if cc else find_clang()[0] c...
random_line_split
error.spec.ts
/* * Copyright (c) 2018 by Filestack. * Some 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 ...
{}, { status: 404, statusText: 'some error message', headers: '', data: Date(), config: {} }, FsRequestErrorCode.ABORTED ); expect(error).toBeInstanceOf(Error); }); });
describe('Request/Error', () => { it('should return error', () => { const error = new FsRequestError( 'Some error message',
random_line_split
compliance-data.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing' import { TestBed } from '@angular/core/testing' import { EffectsModule } from '@ngrx/effects' import { StoreModule } from '@ngrx/store' import { MockCompliance, MockComplianceExpected
describe('ComplianceDataService', () => { let service let http beforeEach(() => TestBed.configureTestingModule({ imports: [ HttpClientTestingModule, StoreModule.forRoot(reducers), EffectsModule.forRoot([]) ], providers: [ComplianceDataService] }) ) beforeEa...
} from '../../../assets/testing/mocks/mock-compliance' import { reducers } from '../../store' import { ComplianceDataService } from './compliance-data.service'
random_line_split
disk.py
#/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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 re...
# build a hierarchy, using sensible default callbacks def build_hierarchy( root_dir, include_cb, disk_specfile_cbs, max_retries=1, num_threads=2, allow_partial_failure=False ): disk_crawler_cbs = AG_crawl.crawler_callbacks( include_cb=include_cb, listdir_cb=dis...
return os.path.isdir( "/" + os.path.join( root_dir.strip("/"), dirpath.strip("/") ) )
identifier_body
disk.py
#/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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 re...
disk_crawler_cbs = AG_crawl.crawler_callbacks( include_cb=include_cb, listdir_cb=disk_listdir, isdir_cb=disk_isdir ) hierarchy = AG_crawl.build_hierarchy( [root_dir] * num_threads, "/", DRIVER_NAME, disk_crawle...
def build_hierarchy( root_dir, include_cb, disk_specfile_cbs, max_retries=1, num_threads=2, allow_partial_failure=False ):
random_line_split
disk.py
#/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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 re...
( root_dir, dirpath ): return os.path.isdir( "/" + os.path.join( root_dir.strip("/"), dirpath.strip("/") ) ) # build a hierarchy, using sensible default callbacks def build_hierarchy( root_dir, include_cb, disk_specfile_cbs, max_retries=1, num_threads=2, allow_partial_failure=False ): disk_crawler_cbs = AG_c...
disk_isdir
identifier_name
perspective_lab.py
from image_mat_util import * from mat import Mat from vec import Vec import matutil from solver import solve ## Task 1 def
(v): ''' Input: - v: a vector with domain {'y1','y2','y3'}, the coordinate representation of a point q. Output: - A {'y1','y2','y3'}-vector z, the coordinate representation in whiteboard coordinates of the point p such that the line through the origin and q intersects t...
move2board
identifier_name
perspective_lab.py
from image_mat_util import * from mat import Mat from vec import Vec import matutil from solver import solve ## Task 1 def move2board(v): ''' Input: - v: a vector with domain {'y1','y2','y3'}, the coordinate representation of a point q. Output: - A {'y1','y2','y3'}-vector z, the coordina...
# (X_pts, colors) = image_mat_util.file2mat('board.png', ('x1','x2','x3')) # H = Mat(({'y1', 'y3', 'y2'}, {'x2', 'x3', 'x1'}), {('y3', 'x1'): -0.7219356810710031, ('y2', 'x1'): -0.3815213180054361, ('y2', 'x2'): 0.7378180860600992, ('y1', 'x1'): 1.0, ('y2', 'x3'): 110.0231807477826, ('y3', 'x3'): 669.4762699006177, ('y...
# ('y1',2):4, ('y2',2):25, ('y3',2):2, # ('y1',3):5, ('y2',3):10, ('y3',3):4}) # print(Y_in) # print(perspective_lab.mat_move2board(Y_in))
random_line_split
perspective_lab.py
from image_mat_util import * from mat import Mat from vec import Vec import matutil from solver import solve ## Task 1 def move2board(v): ''' Input: - v: a vector with domain {'y1','y2','y3'}, the coordinate representation of a point q. Output: - A {'y1','y2','y3'}-vector z, the coordina...
return matutil.coldict2mat(new_col_dic) # import perspective_lab # from mat import Mat # import vecutil # import matutil # import image_mat_util # from vec import Vec # from GF2 import one # from solver import solve # row_dict = {} # row_dict[0] = perspective_lab.make_equations(358, 36, 0, 0)[0] # row_dict[1] = ...
new_col_dic[key] = Vec(val.D, { k:v/val.f['y3'] for k, v in val.f.items() })
conditional_block
perspective_lab.py
from image_mat_util import * from mat import Mat from vec import Vec import matutil from solver import solve ## Task 1 def move2board(v):
## Task 2 def make_equations(x1, x2, w1, w2): ''' Input: - x1 & x2: photo coordinates of a point on the board - y1 & y2: whiteboard coordinates of a point on the board Output: - List [u,v] where u*h = 0 and v*h = 0 ''' domain = {(a, b) for a in {'y1', 'y2', 'y3'} for b in {...
''' Input: - v: a vector with domain {'y1','y2','y3'}, the coordinate representation of a point q. Output: - A {'y1','y2','y3'}-vector z, the coordinate representation in whiteboard coordinates of the point p such that the line through the origin and q intersects the whitebo...
identifier_body
SpearThrow.js
game.SpearThrow = me.Entity.extend({ init: function (x, y, settings, facing) { this._super(me.Entity, 'init', [x, y, { image: "spear", width: 48, height: 48, spritewidth: "48", spriteheight: "48", getShape: function(){ return (new me.Rect(0, 0, 32, 64)).toPolygon(); } }]); this.alwaysU...
this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response){ if(response.b.type==='EnemyBase' || response.b.type === 'EnemyCreep'){ response.b.loseHealth(this.attack); me.game.world.removeChild(this); } } });
me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta);
random_line_split
SpearThrow.js
game.SpearThrow = me.Entity.extend({ init: function (x, y, settings, facing) { this._super(me.Entity, 'init', [x, y, { image: "spear", width: 48, height: 48, spritewidth: "48", spriteheight: "48", getShape: function(){ return (new me.Rect(0, 0, 32, 64)).toPolygon(); } }]); this.alwaysU...
me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response){ if(response.b.type==='EnemyBase' || response.b.type === 'EnemyCreep'){ response.b.loseHealth(this.attack); ...
{ this.body.vel.x += this.body.accel.x * me.timer.tick; }
conditional_block
graph-edge-popover.js
/* Copyright 2012 Twitter, 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 or agreed to in writing, software distr...
// If the previous selected edge is the same one, hide popover and return. if (self.selectedEdge === edge) { $(self.selectedEdge).popover('hide'); self.selectedEdge = null; return; } // Show the new popover and update the current selected edg...
// Hide all other edge popover. graphContainer.find('path.trigger').not(edge).popover('hide');
random_line_split