file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
generate_completion_cache.py
# coding=utf-8 # generate_completion_cache.py - generate cache for dnf bash completion # Copyright © 2013 Elad Alfassa <elad@fedoraproject.org> # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public Lice...
def transaction(self): ''' Generate cache of installed packages ''' try: with open(self.installed_cache_file, 'w') as cache_file: installed_packages = self.base.sack.query().installed() self._out('Generating completion cache...') for packa...
ry: with open(self.available_cache_file, 'w') as cache_file: self._out('Generating completion cache...') available_packages = self.base.sack.query().available() for package in available_packages: cache_file.write(package...
conditional_block
generate_completion_cache.py
# coding=utf-8 # generate_completion_cache.py - generate cache for dnf bash completion # Copyright © 2013 Elad Alfassa <elad@fedoraproject.org> # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public Lice...
def sack(self): ''' Generate cache of available packages ''' # We generate this cache only if the repos were just freshed or if the # cache file doesn't exist fresh = False for repo in self.base.repos.iter_enabled(): if repo.metadata is not None and repo.metadat...
ogger.debug('Completion plugin: %s', msg)
identifier_body
generate_completion_cache.py
# coding=utf-8 # generate_completion_cache.py - generate cache for dnf bash completion # Copyright © 2013 Elad Alfassa <elad@fedoraproject.org> # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public Lice...
self): ''' Generate cache of available packages ''' # We generate this cache only if the repos were just freshed or if the # cache file doesn't exist fresh = False for repo in self.base.repos.iter_enabled(): if repo.metadata is not None and repo.metadata.fresh: ...
ack(
identifier_name
generate_completion_cache.py
# coding=utf-8 # generate_completion_cache.py - generate cache for dnf bash completion # Copyright © 2013 Elad Alfassa <elad@fedoraproject.org> # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public Lice...
for package in installed_packages: cache_file.write(package.name + '\n') except Exception as e: self._out('Can\'t write completion cache: %s' % e)
installed_packages = self.base.sack.query().installed() self._out('Generating completion cache...')
random_line_split
shootout-nbody.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned(), "1000".to_owned()) } else if args.len() <= 1u { vec!("".to_owned(), "1000".to_owned()) } else { args.move_iter().collect() }; let n: i32 = from_str::<i32>(*args.get(1)).unwrap...
identifier_body
shootout-nbody.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
d[k] = bodies[i].x[k] - bodies[j].x[k]; } let dist = (d[0]*d[0] + d[1]*d[1] + d[2]*d[2]).sqrt(); e -= bodies[i].mass * bodies[j].mass / dist; } } e } fn offset_momentum(bodies: &mut [Planet, ..N_BODIES]) { for i in range(0u, N_BODIES) { fo...
random_line_split
shootout-nbody.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(bodies: &mut [Planet, ..N_BODIES]) { for i in range(0u, N_BODIES) { for k in range(0u, 3) { bodies[0].v[k] -= bodies[i].v[k] * bodies[i].mass / SOLAR_MASS; } } } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_owned()...
offset_momentum
identifier_name
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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 your option) any la...
} Ok(()) } pub fn change_key( config: &Config, storage: &dyn Storage, old: &PassphraseConfig, new: &PassphraseConfig, root: &PassphraseConfig, name: Option<&str>, allow_change_via_other_passphrase: bool, ) -> Result<()> { let old_pass = old.read_passphrase("old passphrase", fal...
{ fn format_date(date: Option<&DateTime<Utc>>) -> String { if let Some(date) = date { super::format_date::format_date(date) } else { "never".to_owned() } } let keys = keymgmt::list_keys(storage)?; for key in keys { print!("{}:", key.name); ...
identifier_body
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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 your option) any la...
<IT: Iterator + Clone>( storage: &dyn Storage, key: &PassphraseConfig, root: &PassphraseConfig, names: IT, ) -> Result<()> where IT::Item: AsRef<str>, { let pass = key.read_passphrase("passphrase", false)?; keymgmt::create_group(storage, &pass, names, root_prompt!(root)) } pub fn assoc_gro...
create_group
identifier_name
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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 your option) any la...
will no longer be accessible. This cannot be undone. This means that if you \n\ have a write-protected directory with one of these groups, it will be \n\ impossible to remove it. If you have a read-protected directory with one of \n\ these groups, it and its contents WILL BE RENDERED UNRECOVERABLE FOREVER.\n\ \n\ If yo...
random_line_split
cmd_keymgmt.rs
//- // Copyright (c) 2017, 2021, Jason Lingle // // This file is part of Ensync. // // Ensync 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 your option) any la...
} let keys = keymgmt::list_keys(storage)?; for key in keys { print!("{}:", key.name); for group in &key.groups { print!(" {}", group); } println!(""); println!(" algorithm: {}", key.algorithm); println!(" created: {}", format_date(Some(...
{ "never".to_owned() }
conditional_block
test.js
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 4}, {name: "python", version: 3, singleLineStringErrors: false}); function MT(name)
// Error, because "foobarhello" is neither a known type or property, but // property was expected (after "and"), and it should be in parentheses. MT("decoratorStartOfLine", "[meta @dec]", "[keyword def] [def function]():", " [keyword pass]"); MT("decoratorIndented", "[keyword class] [d...
{ test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
identifier_body
test.js
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 4}, {name: "python", version: 3, singleLineStringErrors: false}); function MT(name) { t...
MT("fValidStringPrefix", "[string f'this is a {formatted} string']"); MT("uValidStringPrefix", "[string u'this is an unicode string']"); })();
MT("matmulWithSpace:", "[variable a] [operator @] [variable b]"); MT("matmulWithoutSpace:", "[variable a][operator @][variable b]"); MT("matmulSpaceBefore:", "[variable a] [operator @][variable b]");
random_line_split
test.js
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 4}, {name: "python", version: 3, singleLineStringErrors: false}); function
(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Error, because "foobarhello" is neither a known type or property, but // property was expected (after "and"), and it should be in parentheses. MT("decoratorStartOfLine", "[meta @dec]", "[keyword def] [def function]():", ...
MT
identifier_name
app.js
'use strict'; (function(){ var camera, scene, renderer; var projector; setup(); function setup(){ setupCanvas(); setupScene(); requestAnimationFrame(function animate(){ renderer.render(scene, camera); requestAnimationFrame(animate); }); } function
(){ camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000); camera.position.y = 10; camera.position.z = 800; scene = new THREE.Scene(); renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight)...
setupCanvas
identifier_name
app.js
'use strict'; (function(){ var camera, scene, renderer; var projector; setup(); function setup(){ setupCanvas(); setupScene(); requestAnimationFrame(function animate(){ renderer.render(scene, camera); requestAnimationFrame(animate); }); } function setupCanvas(){ camera =...
} })();
{ var cube = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({ color: Math.random() * 0xffffff, wireframe: true, wireframeLinewidth: 3 })); cube.position.x = Math.floor(Math.random() * 200 - 100) * 4; cube.position.y = Math.floor(Math.random() * 200 - 100) * 4; ...
conditional_block
app.js
'use strict'; (function(){ var camera, scene, renderer; var projector; setup(); function setup(){ setupCanvas(); setupScene(); requestAnimationFrame(function animate(){ renderer.render(scene, camera); requestAnimationFrame(animate); }); } function setupCanvas(){ camera =...
} })();
random_line_split
app.js
'use strict'; (function(){ var camera, scene, renderer; var projector; setup(); function setup(){ setupCanvas(); setupScene(); requestAnimationFrame(function animate(){ renderer.render(scene, camera); requestAnimationFrame(animate); }); } function setupCanvas()
); projector.unprojectVector(vector, camera); var raycaster = new THREE.Raycaster( camera.position, vector.sub(camera.position).normalize() ); var intersects = raycaster.intersectObjects(scene.children); intersects[0].object.material.color.set(0xff0000); interse...
{ camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000); camera.position.y = 10; camera.position.z = 800; scene = new THREE.Scene(); renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); ...
identifier_body
MLDB-2107-scalar-format.py
# # MLDB-2107-scalar-format.py # Mathieu Marquis Bolduc, 2017-01-10 # This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved. # from mldb import mldb, MldbUnitTest, ResponseException class MLDB2107ScalarFormatTest(MldbUnitTest): # noqa @classmethod def setUpClass(cls): ds = mldb....
(self): n = mldb.get('/v1/query', q="select x from (select false as x)", format='atom').json() self.assertEqual(False, n) def test_error_columns(self): msg = "Query with atom format returned multiple columns" with self.assertRaisesRegex(ResponseException, msg): n = mldb....
test_bool
identifier_name
MLDB-2107-scalar-format.py
# # MLDB-2107-scalar-format.py # Mathieu Marquis Bolduc, 2017-01-10 # This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved. # from mldb import mldb, MldbUnitTest, ResponseException class MLDB2107ScalarFormatTest(MldbUnitTest): # noqa @classmethod def setUpClass(cls): ds = mldb....
def test_bool(self): n = mldb.get('/v1/query', q="select x from (select false as x)", format='atom').json() self.assertEqual(False, n) def test_error_columns(self): msg = "Query with atom format returned multiple columns" with self.assertRaisesRegex(ResponseException, msg): ...
n = mldb.get('/v1/query', q="select x from (select 'blah' as x)", format='atom').json() self.assertEqual('blah', n)
identifier_body
MLDB-2107-scalar-format.py
# # MLDB-2107-scalar-format.py # Mathieu Marquis Bolduc, 2017-01-10 # This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved. # from mldb import mldb, MldbUnitTest, ResponseException class MLDB2107ScalarFormatTest(MldbUnitTest): # noqa @classmethod def setUpClass(cls): ds = mldb....
mldb.run_tests()
conditional_block
MLDB-2107-scalar-format.py
# # MLDB-2107-scalar-format.py # Mathieu Marquis Bolduc, 2017-01-10 # This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved. # from mldb import mldb, MldbUnitTest, ResponseException class MLDB2107ScalarFormatTest(MldbUnitTest): # noqa @classmethod def setUpClass(cls): ds = mldb....
with self.assertRaisesRegex(ResponseException, msg): n = mldb.get('/v1/query', q="select COLUMN EXPR (WHERE columnName() IN ('Z')) from (select 17 as x)", format='atom').json() if __name__ == '__main__': mldb.run_tests()
random_line_split
tutorial6.js
// tutorial6.js /* * Let's create the Comment component, which will depend on data passed in from its parent. * Data passed in from a parent component is available as a 'property' on the child component. * These 'properties' are accessed through this.props. * Using props, we will be able to read the data passed ...
* * That's React protecting you from an XSS attack. */ /* * Now that we have defined the Comment component, we will want to pass it the author name and comment text. * This allows us to reuse the same code for each unique comment. * Now let's add some comments within our CommentList: */ var CommentList = Reac...
* "<p>This is <em>another</em> comment</p>". We want those tags to actually render as HTML.
random_line_split
ComponentRegistry.ts
import { BlueRain } from '../index'; import MapRegistry from './MapRegistry'; import React from 'react'; import flowright from 'lodash.flowright'; import isNil from 'lodash.isnil'; // tslint:disable-next-line // import 'proxy-polyfill'; // // tslint:disable-next-line // import Reflect from 'harmony-reflect'; export t...
throw new Error( 'rawComponent is required to register a component.' + 'Please provide valid component while adding component' ); } super.set(name, { rawComponent, hocs }); } /** * Replace a component with the same name with a new component or * an extension of the raw component and one or mo...
* See https://lodash.com/docs/4.17.4#flowRight */ add(name: string, rawComponent: React.ComponentType<any>, ...hocs: ComponentRegistryHocItem[]) { if (isNil(rawComponent)) {
random_line_split
ComponentRegistry.ts
import { BlueRain } from '../index'; import MapRegistry from './MapRegistry'; import React from 'react'; import flowright from 'lodash.flowright'; import isNil from 'lodash.isnil'; // tslint:disable-next-line // import 'proxy-polyfill'; // // tslint:disable-next-line // import Reflect from 'harmony-reflect'; export t...
/** * Get the **raw** (original) component registered with registerComponent * without the possible HOCs wrapping it. * * @param {String} name The name of the component to get. * @returns {Function|React.ComponentType<any>} An interchangeable/extendable React component */ getRawComponent(name: string): ...
{ let component: ComponentRegistryItem | null = null; for (const componentName of name) { if (this.has(componentName)) { component = this.data.get(componentName); break; } } if (!component) { throw new Error(`None of components ${name.toString()} are registered.`); } const hocs = component...
identifier_body
ComponentRegistry.ts
import { BlueRain } from '../index'; import MapRegistry from './MapRegistry'; import React from 'react'; import flowright from 'lodash.flowright'; import isNil from 'lodash.isnil'; // tslint:disable-next-line // import 'proxy-polyfill'; // // tslint:disable-next-line // import Reflect from 'harmony-reflect'; export t...
if (!this.has(name)) { throw new Error( `Component ${name} not registered.Please register component before adding Hocs` ); } const item: ComponentRegistryItem = super.get(name); item.hocs.push(...hocs); this.data = this.data.set(name, item); } /** * Get a component registered with set(name,...
{ throw new Error( `Component name cannot be ${name}. Please provide valid name while adding Hocs` ); }
conditional_block
ComponentRegistry.ts
import { BlueRain } from '../index'; import MapRegistry from './MapRegistry'; import React from 'react'; import flowright from 'lodash.flowright'; import isNil from 'lodash.isnil'; // tslint:disable-next-line // import 'proxy-polyfill'; // // tslint:disable-next-line // import Reflect from 'harmony-reflect'; export t...
(...name: string[]): React.ComponentType<any> { let component: ComponentRegistryItem | null = null; for (const componentName of name) { if (this.has(componentName)) { component = this.data.get(componentName); break; } } if (!component) { throw new Error(`None of components ${name.toString()} ar...
get
identifier_name
definition.py
""" Fallback to callee definition when definition not found. - https://github.com/davidhalter/jedi/issues/131 - https://github.com/davidhalter/jedi/pull/149 """ """Parenthesis closed at next line.""" # Ignore these definitions for a little while, not sure if we really want them. # python <= 2.5 #? isinstance isinsta...
# Note: len('isinstance(None,') == 16 ##? 16 isinstance isinstance(None,) # Note: len('isinstance(None,') == 16 ##? 16 isinstance isinstance(None, ) # Note: len('isinstance(None, ') == 17 ##? 17 isinstance isinstance(None, ) # Note: len('isinstance( ') == 12 ##? 12 isinstance isinstance( ) """Unclosed parenthesis."...
# Note: len('isinstance(') == 11 #? 11 isinstance isinstance()
random_line_split
polygon.py
import json with open('data/78mm.json', 'r') as _78mm: polygons78 = json.load(_78mm)["features"][0]["geometry"]["geometries"] with open('data/100mm.json', 'r') as _100mm: polygons100 = json.load(_100mm)["features"][0]["geometry"]["geometries"] with open('data/130mm.json', 'r') as _130mm: polygons130 = json...
res = _check(polygons100, 100, x, y) if len(res) > 0: return 0.5 # 0.1 res = _check(polygons130, 130, x, y) if len(res) > 0: return 0.8 # 0.13 return 1.0 # init() # #display() # #x, y = 121.555764, 24.9833 # # x, y = 121.565764, 24.9830 # res = check(x, y) # print res # if (len(r...
return 0.2 # 0.078
conditional_block
polygon.py
import json with open('data/78mm.json', 'r') as _78mm: polygons78 = json.load(_78mm)["features"][0]["geometry"]["geometries"] with open('data/100mm.json', 'r') as _100mm: polygons100 = json.load(_100mm)["features"][0]["geometry"]["geometries"] with open('data/130mm.json', 'r') as _130mm: polygons130 = json...
# #display() # #x, y = 121.555764, 24.9833 # # x, y = 121.565764, 24.9830 # res = check(x, y) # print res # if (len(res) > 0): # if (res[0] == 78): # print_polygon(polygons78[res[1]]["coordinates"][0], 'Red') # if (res[0] == 100): # print_polygon(polygons78[res[1]]["coordinates"][0], 'Orange') #...
return 1.0 # init()
random_line_split
polygon.py
import json with open('data/78mm.json', 'r') as _78mm: polygons78 = json.load(_78mm)["features"][0]["geometry"]["geometries"] with open('data/100mm.json', 'r') as _100mm: polygons100 = json.load(_100mm)["features"][0]["geometry"]["geometries"] with open('data/130mm.json', 'r') as _130mm: polygons130 = json...
def check(x, y): res = _check(polygons78, 78, x, y) if len(res) > 0: return 0.2 # 0.078 res = _check(polygons100, 100, x, y) if len(res) > 0: return 0.5 # 0.1 res = _check(polygons130, 130, x, y) if len(res) > 0: return 0.8 # 0.13 return 1.0 # init() # #display...
for i in range(0, len(p)): if within(p[i]["coordinates"][0], x, y): return [d, i] return []
identifier_body
polygon.py
import json with open('data/78mm.json', 'r') as _78mm: polygons78 = json.load(_78mm)["features"][0]["geometry"]["geometries"] with open('data/100mm.json', 'r') as _100mm: polygons100 = json.load(_100mm)["features"][0]["geometry"]["geometries"] with open('data/130mm.json', 'r') as _130mm: polygons130 = json...
(x, y): res = _check(polygons78, 78, x, y) if len(res) > 0: return 0.2 # 0.078 res = _check(polygons100, 100, x, y) if len(res) > 0: return 0.5 # 0.1 res = _check(polygons130, 130, x, y) if len(res) > 0: return 0.8 # 0.13 return 1.0 # init() # #display() # #x, y =...
check
identifier_name
translationcontext.py
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # T...
""" DEFAULT_DOMAIN = "default" class TranslationContext(object): """Information about the I18N settings of a TAL processor.""" def __init__(self, parent=None, domain=None, target=None, source=None): if parent: if not domain: domain = parent.domain if not target:...
$Id: translationcontext.py 26559 2004-07-15 21:22:32Z srichter $
random_line_split
translationcontext.py
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # T...
if not source: source = parent.source elif domain is None: domain = DEFAULT_DOMAIN self.parent = parent self.domain = domain self.target = target self.source = source
target = parent.target
conditional_block
translationcontext.py
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # T...
(object): """Information about the I18N settings of a TAL processor.""" def __init__(self, parent=None, domain=None, target=None, source=None): if parent: if not domain: domain = parent.domain if not target: target = parent.target if n...
TranslationContext
identifier_name
translationcontext.py
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # T...
if parent: if not domain: domain = parent.domain if not target: target = parent.target if not source: source = parent.source elif domain is None: domain = DEFAULT_DOMAIN self.parent = parent self.dom...
identifier_body
auth.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @first_date 20160129 # @date 20160129 # @version 0.0 """auth for Users API """ from flask import abort from flask.views import MethodView from flask.ext.login import login_required, current_user from sqlalchemy.exc import IntegrityError from webargs...
(RestfulViewMixin, MethodView): decorators = (login_required,) @use_args(ResetPasswordSchema, locations=('json',)) def put(self, args): user = current_user if not user.check_password(args['old_password']): abort(401) user.set_password(args['new_password']) user.u...
ResetPasswordView
identifier_name
auth.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @first_date 20160129 # @date 20160129 # @version 0.0 """auth for Users API """ from flask import abort from flask.views import MethodView from flask.ext.login import login_required, current_user from sqlalchemy.exc import IntegrityError from webargs...
key = user.login() # It will return key return self.get_response({"key": key}, status=200) class LogoutView(RestfulViewMixin, MethodView): decorators = (login_required,) def post(self): user = current_user user.logout() return self.get_response(status=200) class Re...
abort(401)
conditional_block
auth.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @first_date 20160129 # @date 20160129 # @version 0.0 """auth for Users API """ from flask import abort from flask.views import MethodView from flask.ext.login import login_required, current_user from sqlalchemy.exc import IntegrityError from webargs...
def post(self): user = current_user user.logout() return self.get_response(status=200) class ResetPasswordView(RestfulViewMixin, MethodView): decorators = (login_required,) @use_args(ResetPasswordSchema, locations=('json',)) def put(self, args): user = current_user ...
random_line_split
auth.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @first_date 20160129 # @date 20160129 # @version 0.0 """auth for Users API """ from flask import abort from flask.views import MethodView from flask.ext.login import login_required, current_user from sqlalchemy.exc import IntegrityError from webargs...
class LogoutView(RestfulViewMixin, MethodView): decorators = (login_required,) def post(self): user = current_user user.logout() return self.get_response(status=200) class ResetPasswordView(RestfulViewMixin, MethodView): decorators = (login_required,) @use_args(ResetPasswo...
@use_args(LoginSchema, locations=('json',)) def post(self, args): user = User.authenticate(**args) if not user: abort(401) key = user.login() # It will return key return self.get_response({"key": key}, status=200)
identifier_body
method-call-arguments.ts
/** * @license * Copyright Google LLC 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 */ import * as ts from 'typescript'; import {Migration} from '../../update-tool/migration'; import {MethodCallUpgradeDa...
node, `Found call to "${hostTypeName + '.' + methodName}" ` + `with ${failure.count} arguments. Message: ${failure.message}`); } }
random_line_split
method-call-arguments.ts
/** * @license * Copyright Google LLC 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 */ import * as ts from 'typescript'; import {Migration} from '../../update-tool/migration'; import {MethodCallUpgradeDa...
private _checkPropertyAccessMethodCall(node: ts.CallExpression) { const propertyAccess = node.expression as ts.PropertyAccessExpression; if (!ts.isIdentifier(propertyAccess.name)) { return; } const hostType = this.typeChecker.getTypeAtLocation(propertyAccess.expression); const hostTypeNa...
{ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) { this._checkPropertyAccessMethodCall(node); } }
identifier_body
method-call-arguments.ts
/** * @license * Copyright Google LLC 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 */ import * as ts from 'typescript'; import {Migration} from '../../update-tool/migration'; import {MethodCallUpgradeDa...
} private _checkPropertyAccessMethodCall(node: ts.CallExpression) { const propertyAccess = node.expression as ts.PropertyAccessExpression; if (!ts.isIdentifier(propertyAccess.name)) { return; } const hostType = this.typeChecker.getTypeAtLocation(propertyAccess.expression); const hostTy...
{ this._checkPropertyAccessMethodCall(node); }
conditional_block
method-call-arguments.ts
/** * @license * Copyright Google LLC 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 */ import * as ts from 'typescript'; import {Migration} from '../../update-tool/migration'; import {MethodCallUpgradeDa...
(node: ts.CallExpression) { const propertyAccess = node.expression as ts.PropertyAccessExpression; if (!ts.isIdentifier(propertyAccess.name)) { return; } const hostType = this.typeChecker.getTypeAtLocation(propertyAccess.expression); const hostTypeName = hostType.symbol && hostType.symbol.na...
_checkPropertyAccessMethodCall
identifier_name
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
// https://dom.spec.whatwg.org/#dom-attr-ownerelement fn GetOwnerElement(&self) -> Option<DomRoot<Element>> { self.owner() } // https://dom.spec.whatwg.org/#dom-attr-specified fn Specified(&self) -> bool { true // Always returns true } } impl Attr { pub fn set_value(&self...
{ // FIXME(ajeffrey): convert directly from LocalName to DOMString self.prefix().map(|p| DOMString::from(&**p)) }
identifier_body
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
(&self) -> &LocalName { &self.identifier.local_name } /// Sets the owner element. Should be called after the attribute is added /// or removed from its older parent. pub fn set_owner(&self, owner: Option<&Element>) { let ns = self.namespace(); match (self.owner(), owner) { ...
local_name
identifier_name
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
} impl Attr { fn new_inherited( document: &Document, local_name: LocalName, value: AttrValue, name: LocalName, namespace: Namespace, prefix: Option<Prefix>, owner: Option<&Element>, ) -> Attr { Attr { node_: Node::new_inherited(documen...
random_line_split
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::{DomRefCell, Ref}; use crate::dom::bindings::codegen::Bindings::AttrBinding::Attr...
} // https://dom.spec.whatwg.org/#dom-attr-name fn Name(&self) -> DOMString { // FIXME(ajeffrey): convert directly from LocalName to DOMString DOMString::from(&**self.name()) } // https://dom.spec.whatwg.org/#dom-attr-namespaceuri fn GetNamespaceURI(&self) -> Option<DOMString>...
{ *self.value.borrow_mut() = AttrValue::String(value.into()); }
conditional_block
cli_lift.py
#!/usr/bin/env python # # command-line BinaryNinja lifter # # BinaryNinja multiplatform version of Z0MBIE's PE_STAT for opcode frequency # statistics http://z0mbie.dreamhosters.com/opcodes.html # # Copyright (c) 2020-2021 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # o...
if __name__ == '__main__': if not sys.argv[2:]: print('usage: %s <platform> <bytes>' % sys.argv[0]) print('') print('examples:') print(' eg: %s linux-armv7 14 d0 4d e2 01 20 a0 e1 00 30 a0 e1 00 c0 a0 e3' % sys.argv[0]) print('') print('platforms:') print('\t' + '\n\t'.join(map(str, list(binaryninja...
print('\t'*indent + str(il))
conditional_block
cli_lift.py
#!/usr/bin/env python # # command-line BinaryNinja lifter # # BinaryNinja multiplatform version of Z0MBIE's PE_STAT for opcode frequency # statistics http://z0mbie.dreamhosters.com/opcodes.html # # Copyright (c) 2020-2021 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # o...
bv.add_function(0, plat=plat) # print('print all the functions, their basic blocks, and their mc instructions') # for func in bv.functions: # print(repr(func)) # for block in func: # print("\t{0}".format(block)) # for insn in block: # print("\t\t{0}".format(insn)) print(RED) for func in bv.functions: #...
bv.platform = plat
random_line_split
cli_lift.py
#!/usr/bin/env python # # command-line BinaryNinja lifter # # BinaryNinja multiplatform version of Z0MBIE's PE_STAT for opcode frequency # statistics http://z0mbie.dreamhosters.com/opcodes.html # # Copyright (c) 2020-2021 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # o...
(il, indent): if isinstance(il, lowlevelil.LowLevelILInstruction): print('\t'*indent + il.operation.name) for o in il.operands: traverse_IL(o, indent+1) else: print('\t'*indent + str(il)) if __name__ == '__main__': if not sys.argv[2:]: print('usage: %s <platform> <bytes>' % sys.argv[0]) print('') ...
traverse_IL
identifier_name
cli_lift.py
#!/usr/bin/env python # # command-line BinaryNinja lifter # # BinaryNinja multiplatform version of Z0MBIE's PE_STAT for opcode frequency # statistics http://z0mbie.dreamhosters.com/opcodes.html # # Copyright (c) 2020-2021 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # o...
if __name__ == '__main__': if not sys.argv[2:]: print('usage: %s <platform> <bytes>' % sys.argv[0]) print('') print('examples:') print(' eg: %s linux-armv7 14 d0 4d e2 01 20 a0 e1 00 30 a0 e1 00 c0 a0 e3' % sys.argv[0]) print('') print('platforms:') print('\t' + '\n\t'.join(map(str, list(binaryninja...
if isinstance(il, lowlevelil.LowLevelILInstruction): print('\t'*indent + il.operation.name) for o in il.operands: traverse_IL(o, indent+1) else: print('\t'*indent + str(il))
identifier_body
classifier.py
import logging import os import cv2 import numpy as np import pickle from skimage.feature import hog from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG) logg...
return np.concatenate((ch[0][0], ch[1][0], ch[2][0])) def hog_features(img, params): output = [] for ch in range(img.shape[2]): feat = hog(img[:,:,ch], **params) output.append(feat) return output def extract_features(path, params): logger.debug('[extract_features] start...') ...
ch.append(np.histogram(img[:, :, i], bins=bins))
conditional_block
classifier.py
import logging import os import cv2 import numpy as np import pickle from skimage.feature import hog from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG) logg...
def color_histogram(img, bins): ch = [] for i in range(img.shape[2]): ch.append(np.histogram(img[:, :, i], bins=bins)) return np.concatenate((ch[0][0], ch[1][0], ch[2][0])) def hog_features(img, params): output = [] for ch in range(img.shape[2]): feat = hog(img[:,:,ch], **params...
return cv2.resize(img, size).ravel()
identifier_body
classifier.py
import logging import os import cv2 import numpy as np import pickle from skimage.feature import hog from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG) logg...
class Params(object): def __init__(self, color_space, hog_params, size, nbins, heatmap_threshold): self.color_space = color_space self.hog_params = hog_params self.nbins = nbins self.size = size self.heatmap_threshold = heatmap_threshold def spatial(img, size): return ...
MODEL_CHECKPOINT = 'data/model.p'
random_line_split
classifier.py
import logging import os import cv2 import numpy as np import pickle from skimage.feature import hog from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG) logg...
(img, bins): ch = [] for i in range(img.shape[2]): ch.append(np.histogram(img[:, :, i], bins=bins)) return np.concatenate((ch[0][0], ch[1][0], ch[2][0])) def hog_features(img, params): output = [] for ch in range(img.shape[2]): feat = hog(img[:,:,ch], **params) output.appen...
color_histogram
identifier_name
static_virtual_machine.py
, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Class to represent a Static Virtual Machine object. All static VMs provided in a given group will be used before any non-static VMs are provisioned. For example, in a test that uses 4...
(item): """Verify that the decoded JSON object matches the required schema.""" item_keys = frozenset(item) extra_keys = sorted(item_keys - allowed_keys) missing_keys = required_keys - item_keys if extra_keys: raise ValueError('Unexpected keys: {0}'.format(', '.join(extra_keys))) ...
VerifyItemFormat
identifier_name
static_virtual_machine.py
KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Class to represent a Static Virtual Machine object. All static VMs provided in a given group will be used before any non-static VMs are provisioned. For example, in a test that u...
password = item.get('password') if not isinstance(local_disks, list): raise ValueError('Expected a list of local disks, got: {0}'.format( local_disks)) scratch_disk_mountpoints = item.get('scratch_disk_mountpoints', []) if not isinstance(scratch_disk_mountpoints, list): ...
random_line_split
static_virtual_machine.py
, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Class to represent a Static Virtual Machine object. All static VMs provided in a given group will be used before any non-static VMs are provisioned. For example, in a test that uses 4...
ssh_port = item.get('ssh_port', 22) os_type = item.get('os_type') install_packages = item.get('install_packages', True) if ((os_type == WINDOWS and FLAGS.os_type != WINDOWS) or (os_type != WINDOWS and FLAGS.os_type == WINDOWS)): raise ValueError('Please only use Windows VMs w...
raise ValueError( 'Expected a list of disk mount points, got: {0}'.format( scratch_disk_mountpoints))
conditional_block
static_virtual_machine.py
perfkitbenchmarker import virtual_machine from perfkitbenchmarker import windows_virtual_machine WINDOWS = 'windows' DEBIAN = 'debian' RHEL = 'rhel' UBUNTU_CONTAINER = 'ubuntu_container' FLAGS = flags.FLAGS class StaticVmSpec(virtual_machine.BaseVmSpec): """Object containing all info needed to create a Static VM....
pass
identifier_body
CNN.py
import os import sys root_path = os.path.abspath("../../../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np import tensorflow as tf from _Dist.NeuralNetworks.Base import Generator4d from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d from _Dist.NeuralNetworks.NNUtil import Activations...
(self, *args, **kwargs): self.height, self.width = kwargs.pop("height", None), kwargs.pop("width", None) super(CNN, self).__init__(*args, **kwargs) self._name_appendix = "CNN" self._generator_base = Generator4d self.conv_activations = None self.n_filters = self.filter_s...
__init__
identifier_name
CNN.py
import os import sys root_path = os.path.abspath("../../../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np import tensorflow as tf from _Dist.NeuralNetworks.Base import Generator4d from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d from _Dist.NeuralNetworks.NNUtil import Activations...
net = tf.layers.max_pooling2d(net, 2, 2, name="pool") fc_shape = np.prod([net.shape[i].value for i in range(1, 4)]) net = tf.reshape(net, [-1, fc_shape]) super(CNN, self)._build_model(net)
net = getattr(Activations, activation)(net, activation) net = tf.layers.dropout(net, training=self._is_training) if pooling is not None:
random_line_split
CNN.py
import os import sys root_path = os.path.abspath("../../../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np import tensorflow as tf from _Dist.NeuralNetworks.Base import Generator4d from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d from _Dist.NeuralNetworks.NNUtil import Activations...
net = tf.layers.dropout(net, training=self._is_training) if pooling is not None: net = tf.layers.max_pooling2d(net, 2, 2, name="pool") fc_shape = np.prod([net.shape[i].value for i in range(1, 4)]) net = tf.reshape(net, [-1, fc_shape]) super(CNN, self)._b...
net = getattr(Activations, activation)(net, activation)
conditional_block
CNN.py
import os import sys root_path = os.path.abspath("../../../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np import tensorflow as tf from _Dist.NeuralNetworks.Base import Generator4d from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d from _Dist.NeuralNetworks.NNUtil import Activations...
self._model_built = True if net is None: net = self._tfx for i, (filter_size, n_filter, pooling) in enumerate(zip( self.filter_sizes, self.n_filters, self.poolings )): net = tf.layers.conv2d(net, n_filter, filter_size, padding="same") net = tf.laye...
identifier_body
__manifest__.py
# © 2008-2020 Dorin Hongu <dhongu(@)gmail(.)com
"summary": "Localizare Terrabit", "version": "14.0.3.0.3", "author": "Dorin Hongu," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/l10n-romania", "license": "AGPL-3", "category": "Generic Modules", "depends": [ "base", "account", "l10n_ro_confi...
# See README.rst file on addons root folder for license details { "name": "Romania - Invoice Report ",
random_line_split
mlfutil.py
# -*- coding=utf-8 -*- import cPickle import numpy as np import os import sys """Common tools for this project. Utils are defined in this module for sharing. """ PROJ_DIR = os.path.split(os.path.realpath(__file__))[0] def draw_progress(iteration, total, pref='Progress:', suff='', decimals=1, barle...
def save_dict(self, ofname): with open(ofname, 'w') as fo: for key in self.cats: print >> fo, \ '\t'.join([key.encode('utf8'), str(self.cats[key])]) def load_dict(self, dfname): self.cats = {} with open(dfname) as f: data = [l....
"need override ifnames are ',' separated fields are ',' separated, from 0. means from ... to """ self.cats = {} cat_idx = 0 ifnames = ifnames.split(',') cols = columns.split(',') col_st = int(cols[0]) col_ed = int(cols[1]) if len(cols) > 1 else -1 ...
identifier_body
mlfutil.py
# -*- coding=utf-8 -*- import cPickle import numpy as np import os import sys """Common tools for this project. Utils are defined in this module for sharing. """ PROJ_DIR = os.path.split(os.path.realpath(__file__))[0] def draw_progress(iteration, total, pref='Progress:', suff='', decimals=1, barle...
out_str = '\r%s |%s| %s%s %s' % (pref, bar, pcts, '%', suff) out_str = '\x1b[0;34;40m' + out_str + '\x1b[0m' sys.stdout.write(out_str), if iteration == total: sys.stdout.write('\n') sys.stdout.flush() class CatEncoder(object): """Transform category to global uniq index """ def ...
formatStr = "{0:." + str(decimals) + "f}" pcts = formatStr.format(100 * (iteration / float(total))) filledlen = int(round(barlen * iteration / float(total))) bar = '█' * filledlen + '-' * (barlen - filledlen)
random_line_split
mlfutil.py
# -*- coding=utf-8 -*- import cPickle import numpy as np import os import sys """Common tools for this project. Utils are defined in this module for sharing. """ PROJ_DIR = os.path.split(os.path.realpath(__file__))[0] def draw_progress(iteration, total, pref='Progress:', suff='', decimals=1, barle...
def n_cat(self): return len(self.cats) def cat2idx(self, cat): if cat in self.cats: return self.cats[cat] else: return -1 def cat2onehot(self, cat, missing=False): idx = self.cat2idx(cat) if missing: res = [0] * (self.n_cat() + 1)...
lf.cats[fields[0]] = int(fields[1])
conditional_block
mlfutil.py
# -*- coding=utf-8 -*- import cPickle import numpy as np import os import sys """Common tools for this project. Utils are defined in this module for sharing. """ PROJ_DIR = os.path.split(os.path.realpath(__file__))[0] def draw_progress(iteration, total, pref='Progress:', suff='', decimals=1, barle...
elf, ofname): with open(ofname, 'w') as fo: for key in self.cats: print >> fo, \ '\t'.join([key.encode('utf8'), str(self.cats[key])]) def load_dict(self, dfname): self.cats = {} with open(dfname) as f: data = [l.strip('\n').decode(...
ve_dict(s
identifier_name
main.rs
use std::fmt; // Minimal implementation of single precision complex numbers #[repr(C)] #[derive(Clone, Copy)] struct Complex { re: f32, im: f32, } impl fmt::Debug for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self....
} } // Foreign functions must be declared inside an extern block // annotated with a #[link] attribute containing the name // of the foreign library. // // this extern block links to the libm library #[link(name = "m")] extern { fn ccosf(z: Complex) -> Complex; } // safe wrapper for foreign function fn cos...
{ write!(f, "{}+{}i", self.re, self.im) }
conditional_block
main.rs
use std::fmt; // Minimal implementation of single precision complex numbers #[repr(C)] #[derive(Clone, Copy)] struct Complex { re: f32, im: f32, } impl fmt::Debug for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.i...
fn add(lhs: u32, rhs: u32) -> u32; } fn main() { // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({:?}) = {:?}", z, cos(z)); println!("1 + 2 = {:?}", unsafe { add(1, 2) }); }
} // the package's native dependency extern {
random_line_split
main.rs
use std::fmt; // Minimal implementation of single precision complex numbers #[repr(C)] #[derive(Clone, Copy)] struct Complex { re: f32, im: f32, } impl fmt::Debug for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self....
() { // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({:?}) = {:?}", z, cos(z)); println!("1 + 2 = {:?}", unsafe { add(1, 2) }); }
main
identifier_name
setup.js
root.$ = $; beforeEach(() => { // Using these globally-available Sinon features is preferrable, as they're // automatically restored for you in the subsequent `afterEach` root.sandbox = root.sinon.sandbox.create(); root.stub = root.sandbox.stub.bind(root.sandbox); root.spy = root.sandbox.spy.bi...
import $ from 'jquery'; module.exports = function(root) { root = root ? root : global; root.expect = root.chai.expect;
random_line_split
5246a6bd410f_multisite_vim.py
# Copyright 2016 OpenStack 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('auth_url') ) op.add_column(u'devices', sa.Column('placement_attr', sa.PickleType(), nullable=True)) op.add_column(u'devices', sa.Column('vim_id', sa.String(length=36), ...
op.create_table('vims', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('type', sa.String(length=255), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('description'...
identifier_body
5246a6bd410f_multisite_vim.py
# Copyright 2016 OpenStack 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('description', sa.String(length=255), nullable=True), sa.Column('placement_attr', sa.PickleType(), nullable=True), sa.Column('shared', sa.Boolean(), se...
sa.Column('type', sa.String(length=255), nullable=False),
random_line_split
5246a6bd410f_multisite_vim.py
# Copyright 2016 OpenStack 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
(active_plugins=None, options=None): op.create_table('vims', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('type', sa.String(length=255), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('name', sa.String(length=255), nullab...
upgrade
identifier_name
browser-sync.js
// task browserSync const gulp = require('gulp'); const config = require('../gulp.config'); const path = require('path'); const browserSync = require('browser-sync').create(); const browserSyncTask = () => { browserSync.init(config.tasks.browserSync); let watchableTasks = [ 'scripts', 'html', ...
path.join( config.root, config.tasks[taskName].src, `/**/*.{${config.tasks[taskName].extensions}}` ), path.join( config.root, config.tasks.vueify.src, `...
files = [
random_line_split
browser-sync.js
// task browserSync const gulp = require('gulp'); const config = require('../gulp.config'); const path = require('path'); const browserSync = require('browser-sync').create(); const browserSyncTask = () => { browserSync.init(config.tasks.browserSync); let watchableTasks = [ 'scripts', 'html', ...
let watchTaskName = `watch${taskName[0] .toUpperCase() .concat(taskName.slice(1))}`; gulp.task(watchTaskName, [taskName], (done) => { browserSync.reload(); done(); } ); gulp.watch(files, [watchTaskName]); }); }; ...
{ files = [ path.join( config.root, config.tasks[taskName].src, `/**/*.{${config.tasks[taskName].extensions}}` ), path.join( config.root, config.tasks.vueify.sr...
conditional_block
config.ts
import { ConfigurationTarget, WorkspaceConfiguration } from 'vscode'; import { ExplosionConfig } from '../cursor-exploder/cursor-exploder' import { ScreenShakerConfig } from '../screen-shaker/screen-shaker' import { ConfigurationKeys, DeprecatedConfigurationKeys } from './configuration-keys'; export const CSS_LEF...
// Fall back to the package.json default value // as a last resort return vscodeConfig.get<V>(key); } export type InspectConfigData = ConfigurationTarget | false; export function isConfigSet(key: ConfigurationKeys | DeprecatedConfigurationKeys, config: WorkspaceConfiguration): ConfigurationTarget |...
random_line_split
config.ts
import { ConfigurationTarget, WorkspaceConfiguration } from 'vscode'; import { ExplosionConfig } from '../cursor-exploder/cursor-exploder' import { ScreenShakerConfig } from '../screen-shaker/screen-shaker' import { ConfigurationKeys, DeprecatedConfigurationKeys } from './configuration-keys'; export const CSS_LEF...
<V>(key: DeprecatedConfigurationKeys, vscodeConfig: WorkspaceConfiguration, themeConfig: any = {}): V { return getConfigValueCore(key, vscodeConfig, themeConfig); } function getConfigValueCore<V>(key: ConfigurationKeys | DeprecatedConfigurationKeys, vscodeConfig: WorkspaceConfiguration, themeConfig: any = {}):...
getDeprecatedConfigValue
identifier_name
config.ts
import { ConfigurationTarget, WorkspaceConfiguration } from 'vscode'; import { ExplosionConfig } from '../cursor-exploder/cursor-exploder' import { ScreenShakerConfig } from '../screen-shaker/screen-shaker' import { ConfigurationKeys, DeprecatedConfigurationKeys } from './configuration-keys'; export const CSS_LEF...
function isNullOrUndefined(value: any) { return value === null || value === undefined; }
{ const inspectionResults = config.inspect(key); if (!isNullOrUndefined(inspectionResults.workspaceFolderValue)) { return ConfigurationTarget.WorkspaceFolder; } else if (!isNullOrUndefined(inspectionResults.workspaceValue)) { return ConfigurationTarget.Workspace; } else if (!isNull...
identifier_body
asha-workers-details.service_20170224102150.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model'; import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; import { AshaWorkerP...
(private http: Http){} getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{ //return Promise.resolve(AshaWorkersList); return this.http.get(this.url) .toPromise() .then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[]) ...
constructor
identifier_name
asha-workers-details.service_20170224102150.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model'; import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; import { AshaWorkerP...
getDummyAshaWorkerDetails(): Promise<AshaWorkerBasicDetailsModel>{ return Promise.resolve(DummyAshaWorkerDetails); } //update the payment rules for rural, urban and help text updateAshaWorkerPaymentRules(ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<AshaWorkerPaymentRulesMo...
.then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[]) .catch(this.handleError); }
random_line_split
sidenav-graphs.component.ts
import { Component, ElementRef, ViewChild, } from '@angular/core'; import $ = require('jquery'); import 'jquery-sparkline'; /** * Render the graphs tab inside sidenav */ @Component({ selector: 'admin-sidenav-graphs', templateUrl: './sidenav-graphs.component.html', styleUrls: ['./sidenav-graphs.component....
(): void { ($(this.stockTrendEl.nativeElement) as any) .sparkline( [71, 70, 41, 33, 46, 95, 1, 26, 16, 18, 54, 98, 69, 0, 65, 6, 93, 20, 4, 57, 25, 21, 86, 35, 58, 50, 99, 46, 93, 41], { type: 'line', width: '200px', height: '50px', fillColor: ...
initSparklines
identifier_name
sidenav-graphs.component.ts
import { Component, ElementRef, ViewChild, } from '@angular/core'; import $ = require('jquery'); import 'jquery-sparkline'; /** * Render the graphs tab inside sidenav */ @Component({ selector: 'admin-sidenav-graphs', templateUrl: './sidenav-graphs.component.html', styleUrls: ['./sidenav-graphs.component....
@ViewChild('dow') private dowEl: ElementRef; @ViewChild('gender') private genderEl: ElementRef; initSparklines(): void { ($(this.stockTrendEl.nativeElement) as any) .sparkline( [71, 70, 41, 33, 46, 95, 1, 26, 16, 18, 54, 98, 69, 0, 65, 6, 93, 20, 4, 57, 25, 21, 86, 35, 58, 50, 99, 46,...
@ViewChild('stockTrend') private stockTrendEl: ElementRef; @ViewChild('stockBars') private stockBarsEl: ElementRef; @ViewChild('stockBars2') private stockBarsEl2: ElementRef; @ViewChild('nasdaq') private nasdaqEl: ElementRef;
random_line_split
pregyp.ts
import * as fs from 'fs' import * as path from 'path' import * as semver from 'semver' import * as url from 'url' import {fetchBinaryData} from './client' import type {PlatformVariant, VersionMetadata} from './types' export function hasPrebuiltBinaries({binary}: VersionMetadata): boolean { return Boolean(binary && b...
for (const napiVersion of binary.napi_versions) { for (const {abi, arch, platform} of prebuiltBinaryProperties) { await downloadPrebuiltBinary(localFolder, name, version, binary, abi, platform, arch, napiVersion) } } } async function downloadPrebuiltBinary( localFolder: string, name: string, ...
{ for (const {abi, arch, platform} of prebuiltBinaryProperties) { await downloadPrebuiltBinary(localFolder, name, version, binary, abi, platform, arch) } return }
conditional_block
pregyp.ts
import * as fs from 'fs' import * as path from 'path' import * as semver from 'semver' import * as url from 'url' import {fetchBinaryData} from './client' import type {PlatformVariant, VersionMetadata} from './types' export function hasPrebuiltBinaries({binary}: VersionMetadata): boolean { return Boolean(binary && b...
return } for (const napiVersion of binary.napi_versions) { for (const {abi, arch, platform} of prebuiltBinaryProperties) { await downloadPrebuiltBinary(localFolder, name, version, binary, abi, platform, arch, napiVersion) } } } async function downloadPrebuiltBinary( localFolder: string, na...
for (const {abi, arch, platform} of prebuiltBinaryProperties) { await downloadPrebuiltBinary(localFolder, name, version, binary, abi, platform, arch) }
random_line_split
pregyp.ts
import * as fs from 'fs' import * as path from 'path' import * as semver from 'semver' import * as url from 'url' import {fetchBinaryData} from './client' import type {PlatformVariant, VersionMetadata} from './types' export function hasPrebuiltBinaries({binary}: VersionMetadata): boolean { return Boolean(binary && b...
function prebuiltBinaryUrl( name: string, version: string, binary: VersionMetadata['binary'], abi: number, platform: string, arch: string, napiVersion?: number ): string { const remotePath = prebuiltBinaryRemotePath(name, version, binary, abi, platform, arch, napiVersion).replace( /\/$/, '' ...
{ return path.join(localFolder, prebuiltBinaryFileName(name, version, binary, abi, platform, arch, napiVersion)) }
identifier_body
pregyp.ts
import * as fs from 'fs' import * as path from 'path' import * as semver from 'semver' import * as url from 'url' import {fetchBinaryData} from './client' import type {PlatformVariant, VersionMetadata} from './types' export function hasPrebuiltBinaries({binary}: VersionMetadata): boolean { return Boolean(binary && b...
( name: string, version: string, binary: VersionMetadata['binary'], abi: number, platform: string, arch: string, napiVersion?: number ): string { return formatPrebuilt(binary.remote_path, name, version, binary.module_name, abi, platform, arch, napiVersion) } function prebuiltBinaryFileName( name: str...
prebuiltBinaryRemotePath
identifier_name
reader.js
import { equals, stringMaker, valueOf } from './data_structure_util'; /** * @signature * @description d * @namespace Reader * @memberOf dataStructures * @property {function} of * @param {function} run - a * @return {dataStructures.reader} - b */ function Reader(run) { return Object.create(reader, { ...
};
{ return 'Reader'; }
identifier_body
reader.js
import { equals, stringMaker, valueOf } from './data_structure_util'; /** * @signature * @description d * @namespace Reader * @memberOf dataStructures * @property {function} of * @param {function} run - a * @return {dataStructures.reader} - b */ function Reader(run) { return Object.create(reader, { ...
() { return 'Reader'; } };
[Symbol.toStringTag]
identifier_name
reader.js
import { equals, stringMaker, valueOf } from './data_structure_util'; /** * @signature * @description d * @namespace Reader * @memberOf dataStructures * @property {function} of * @param {function} run - a * @return {dataStructures.reader} - b */ function Reader(run) { return Object.create(reader, { ...
Reader.of = function _of(val) { return Reader(constant(val)); }; /** * @description d * @memberOf dataStructures */ var reader = { chain: function _chain(f) { return Reader(e => f(this.run(e)).run(e)); }, map: function _map(f) { return this.chain(a => Reader.of(f(a))); }, app...
* @param {*} val - a * @return {dataStructures.reader} - b */
random_line_split
test_stats.py
# 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/. from atmo.stats.models import Metric def
(now, one_hour_ago): Metric.record("metric-key-1") Metric.record("metric-key-2", 500) Metric.record("metric-key-3", data={"other-value": "test"}) Metric.record("metric-key-4", created_at=one_hour_ago, data={"other-value-2": 100}) m = Metric.objects.get(key="metric-key-1") assert m.value == 1 ...
test_metrics_record
identifier_name
test_stats.py
# 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
Metric.record("metric-key-1") Metric.record("metric-key-2", 500) Metric.record("metric-key-3", data={"other-value": "test"}) Metric.record("metric-key-4", created_at=one_hour_ago, data={"other-value-2": 100}) m = Metric.objects.get(key="metric-key-1") assert m.value == 1 assert m.created_at...
# file, you can obtain one at http://mozilla.org/MPL/2.0/. from atmo.stats.models import Metric def test_metrics_record(now, one_hour_ago):
random_line_split
test_stats.py
# 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/. from atmo.stats.models import Metric def test_metrics_record(now, one_hour_ago):
m = Metric.objects.get(key="metric-key-4") assert m.value == 1 assert m.created_at.replace(microsecond=0) == one_hour_ago assert m.data == {"other-value-2": 100}
Metric.record("metric-key-1") Metric.record("metric-key-2", 500) Metric.record("metric-key-3", data={"other-value": "test"}) Metric.record("metric-key-4", created_at=one_hour_ago, data={"other-value-2": 100}) m = Metric.objects.get(key="metric-key-1") assert m.value == 1 assert m.created_at.rep...
identifier_body
table.rs
use std::collections::HashMap; use rustc_serialize::json::Json; #[derive(Debug)] pub enum TableError { TableDoesNotExist, TableAlreadyExists, KeyAlreadyPresent, KeyDoesNotExist, } pub struct Tables { data: HashMap<String, HashMap<String, Json>> } impl Tables { pub fn new() -> Tables { ...
fn get_mut_table(&mut self, table: &str) -> Result<&mut HashMap<String, Json>, TableError> { match self.data.get_mut(table) { Some(table) => Ok(table), None => Err(TableError::TableDoesNotExist), } } pub fn put(&mut self, table: &str, key: &str, data: Json) -> Result...
random_line_split
table.rs
use std::collections::HashMap; use rustc_serialize::json::Json; #[derive(Debug)] pub enum TableError { TableDoesNotExist, TableAlreadyExists, KeyAlreadyPresent, KeyDoesNotExist, } pub struct Tables { data: HashMap<String, HashMap<String, Json>> } impl Tables { pub fn new() -> Tables { ...
(&mut self, table: &str) -> Result<(), TableError> { match self.data.remove(table) { Some(_) => Ok(()), None => Err(TableError::TableDoesNotExist), } } }
delete_table
identifier_name
table.rs
use std::collections::HashMap; use rustc_serialize::json::Json; #[derive(Debug)] pub enum TableError { TableDoesNotExist, TableAlreadyExists, KeyAlreadyPresent, KeyDoesNotExist, } pub struct Tables { data: HashMap<String, HashMap<String, Json>> } impl Tables { pub fn new() -> Tables { ...
else { self.data.insert(table.to_string(), HashMap::new()); Ok(()) } } fn get_table(&self, table: &str) -> Result<&HashMap<String, Json>, TableError> { match self.data.get(table) { Some(table) => Ok(table), None => Err(TableError::TableDoesNotExi...
{ Err(TableError::TableAlreadyExists) }
conditional_block
query_string_parser.py
################################################################################################### # # query_string_parser.py # Extracts the query string from a URL and prints each parameter and value. # # Plugin Author: Your Name Here (ryan@obsidianforensics.com) # ##################################################...
# Lastly, a count of parsed items with a description of what the plugin did return "{} query strings parsed".format(parsedItems)
import urllib.parse # Setting up our return variable global parsedItems parsedItems = 0 for item in analysis_session.parsed_artifacts: # For each item that Hindsight has parsed, if item.row_type.startswith(artifactTypes): # if the row if of a supported type for this pl...
identifier_body
query_string_parser.py
################################################################################################### # # query_string_parser.py # Extracts the query string from a URL and prints each parameter and value. # # Plugin Author: Your Name Here (ryan@obsidianforensics.com) # ##################################################...
# Lastly, a count of parsed items with a description of what the plugin did return "{} query strings parsed".format(parsedItems)
if item.interpretation is None: # if there isn't already an interpretation, parsed_url = urllib.parse.urlparse(item.url) query_string_dict = urllib.parse.parse_qs(parsed_url.query) if len(query_string_dict) > 0: # Check if we have any...
conditional_block