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
readonlyadmin.py
from collections import OrderedDict from django.contrib import admin from django.core.exceptions import PermissionDenied class SetOfEverything(list): def __contains__(self, other): return True ## adopted from http://mike.hostetlerhome.com/blog/2012/11/13/add-a-read-only-role-to-django-admin/ class Read...
(self, request, obj=None): return self.__user_is_readonly(request) def has_delete_permission(self, request, obj=None): return self.__user_is_readonly(request) def get_actions(self, request): # readonly users cannot perform any actions return OrderedDict() def change_view(s...
has_add_permission
identifier_name
readonlyadmin.py
from collections import OrderedDict from django.contrib import admin from django.core.exceptions import PermissionDenied class SetOfEverything(list): def __contains__(self, other): return True ## adopted from http://mike.hostetlerhome.com/blog/2012/11/13/add-a-read-only-role-to-django-admin/ class Read...
pass if request.method == 'POST': raise PermissionDenied request.readonly = True return super(ReadOnlyAdmin, self).change_view(request, object_id, extra_context=extra_context) def __user_is_readonly(self, request): groups = [x.name for x in request.user.group...
self.readonly_fields = SetOfEverything() try: return super(ReadOnlyAdmin, self).change_view(request, object_id, extra_context=extra_context) except PermissionDenied:
random_line_split
readonlyadmin.py
from collections import OrderedDict from django.contrib import admin from django.core.exceptions import PermissionDenied class SetOfEverything(list): def __contains__(self, other): return True ## adopted from http://mike.hostetlerhome.com/blog/2012/11/13/add-a-read-only-role-to-django-admin/ class Read...
groups = [x.name for x in request.user.groups.all()] return 'readonly' in groups
identifier_body
plist.js
'use strict'; moduloPrioridad.controller('PrioridadPListController', ['$scope', '$routeParams', '$location', 'serverService', 'prioridadService', '$uibModal', function ($scope, $routeParams, $location, serverService, prioridadService, $uibModal) { $scope.fields = prioridadService.getFields(); $sco...
function getDataFromServer() { serverService.promise_getCount($scope.ob, $scope.filterExpression).then(function (response) { if (response.status == 200) { $scope.registers = response.data.message; $scope.pages = serverService.calculatePages($sc...
$scope.url = $scope.ob + '/' + $scope.op;
random_line_split
plist.js
'use strict'; moduloPrioridad.controller('PrioridadPListController', ['$scope', '$routeParams', '$location', 'serverService', 'prioridadService', '$uibModal', function ($scope, $routeParams, $location, serverService, prioridadService, $uibModal) { $scope.fields = prioridadService.getFields(); $sco...
() { serverService.promise_getCount($scope.ob, $scope.filterExpression).then(function (response) { if (response.status == 200) { $scope.registers = response.data.message; $scope.pages = serverService.calculatePages($scope.rpp, $scope.registers); ...
getDataFromServer
identifier_name
plist.js
'use strict'; moduloPrioridad.controller('PrioridadPListController', ['$scope', '$routeParams', '$location', 'serverService', 'prioridadService', '$uibModal', function ($scope, $routeParams, $location, serverService, prioridadService, $uibModal) { $scope.fields = prioridadService.getFields(); $sco...
$scope.status = "Error en la recepción de datos del servidor3"; }); } $scope.pop = function (id, foreignObjectName, foreignContollerName, foreignViewName) { var modalInstance = $uibModal.open({ templateUrl: 'js/' + foreignObjectName + '/' + foreig...
{ serverService.promise_getCount($scope.ob, $scope.filterExpression).then(function (response) { if (response.status == 200) { $scope.registers = response.data.message; $scope.pages = serverService.calculatePages($scope.rpp, $scope.registers); ...
identifier_body
plist.js
'use strict'; moduloPrioridad.controller('PrioridadPListController', ['$scope', '$routeParams', '$location', 'serverService', 'prioridadService', '$uibModal', function ($scope, $routeParams, $location, serverService, prioridadService, $uibModal) { $scope.fields = prioridadService.getFields(); $sco...
else { $scope.status = "Error en la recepción de datos del servidor1"; } }).then(function (response) { if (response.status == 200) { $scope.page = response.data.message; $scope.status = ""; } else { ...
{ $scope.registers = response.data.message; $scope.pages = serverService.calculatePages($scope.rpp, $scope.registers); if ($scope.numpage > $scope.pages) { $scope.numpage = $scope.pages; } return ...
conditional_block
1379.py
""" The mean of three integers A, B and C is (A + B + C)/3. The median of three integers is the one that would be in the middle if they are sorted in non-decreasing order. Given two integers A and B, return the minimum possible integer C such that the mean and the median of A, B and C are equal. Input Each test case ...
* B - C print(A)
conditional_block
1379.py
""" The mean of three integers A, B and C is (A + B + C)/3. The median of three integers is the one that would be in the middle if they are sorted in non-decreasing order. Given two integers A and B, return the minimum possible integer C such that the mean and the median of A, B and C are equal. Input Each test case ...
if 1 <= B <= C <= 10 ** 9: A = 2 * B - C print(A)
random_line_split
settings.py
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep t...
# Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.Com...
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
conditional_block
settings.py
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep t...
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'attendance', ] MIDDLEWARE = [ 'django.middleware.security...
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['HERTZ_DEBUG'] != 'False' ALLOWED_HOSTS = ['*' if DEBUG else os.environ['HERTZ_HOST']]
random_line_split
OBC_main.py
__author__ = 'Debha' from read_data import read_data, read_map, gene_muts, make_GO_map from cluster import make_cluster_mat, make_sub_mut_map, make_GO_cluster_mat, cluster_main, clean, pairwiseDist, clustered_GOs, sim_matrix import numpy as np data_file = "../inputs/somatic.csv"
#data = read_data(data_file) #gene_map = read_map(map_file) #gene_mut = gene_muts(data, gene_map) #GO_map = make_GO_map(GO_file) #[cluster_mat, cluster_mat_nonbinary, subjects, genes, gene_length_map] = make_cluster_mat(data, list(gene_mut.keys())) cluster_mat = np.load("../intermediates/cluster_mat.npy") subjects = ...
map_file = "../inputs/mart_export.csv" GO_file = "../inputs/c5.all.v5.0.symbols.gmt"
random_line_split
OBC_main.py
__author__ = 'Debha' from read_data import read_data, read_map, gene_muts, make_GO_map from cluster import make_cluster_mat, make_sub_mut_map, make_GO_cluster_mat, cluster_main, clean, pairwiseDist, clustered_GOs, sim_matrix import numpy as np data_file = "../inputs/somatic.csv" map_file = "../inputs/mart_export.csv"...
#for key in clusters: # print key, len(clusters[key]), len(subject_clusters[key]) #clustered_GOs(clusters, c_GO_terms, mu) #pairwiseDist(c_GO_cluster_mat) #sim_matrix(c_GO_cluster_mat)
print "Run " + str(i+1) + " out of " + str(runs) [mu, clusters, distortion, subject_clusters] = cluster_main(c_GO_cluster_mat.tolist(), k, iterations, subjects) agg_sub_clusters.append(subject_clusters)
conditional_block
test_MetaData.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 本测试模块用于测试与 :class:`sqlite4dummy.schema.MetaData` 有关的方法 class, method, func, exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from sqlite4dummy import * from sqlite4dummy.tests.basetest import * from datetime import dateti...
mory:", autocommit=False) self.metadata = MetaData() self.int_ = 1 self.float_ = 3.14 self.str_ = r"""\/!@#$%^&*()_+-=~`|[]{}><,.'"?""" self.bytes_ = "abc".encode("utf-8") self.date_ = date(2000, 1, 1) self.datetime_ = datetime(2015, 10, 1, 18, 30, 0, 123...
(":me
identifier_name
test_MetaData.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 本测试模块用于测试与 :class:`sqlite4dummy.schema.MetaData` 有关的方法 class, method, func, exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from sqlite4dummy import * from sqlite4dummy.tests.basetest import * from datetime import dateti...
def test_get_index(self): """测试MetaData.get_index(index)方法是否能正确获得Index。 """ self.assertEqual(self.metadata.get_index("test_index"), self.index) self.assertRaises(KeyError, self.metadata.get_index, "not_existing_index") def test_reflect(self...
self.assertRaises(KeyError, self.metadata.get_table, "not_existing_table")
random_line_split
test_MetaData.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 本测试模块用于测试与 :class:`sqlite4dummy.schema.MetaData` 有关的方法 class, method, func, exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from sqlite4dummy import * from sqlite4dummy.tests.basetest import * from datetime import dateti...
self.assertEqual(second_metadata.get_index("test_index").\ index_name, "test_index") self.assertEqual(second_metadata.get_index("test_index").\ table_name, "test") self.assertEqual(second_metadata.get_index("test_index").\ ...
d_metadata = MetaData() second_metadata.reflect(self.engine, pickletype_columns=[ "test._pickle_with_default", "test._pickle", ]) self.assertEqual(second_metadata.get_table("test").\ c._int_with_default.default, self.i...
identifier_body
test_MetaData.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 本测试模块用于测试与 :class:`sqlite4dummy.schema.MetaData` 有关的方法 class, method, func, exception ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from sqlite4dummy import * from sqlite4dummy.tests.basetest import * from datetime import dateti...
conditional_block
issue13507.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 type_ids() -> Vec<TypeId> { let mut ids = vec!(); ids.push(TypeId::of::<FooNil>()); ids.push(TypeId::of::<FooBool>()); ids.push(TypeId::of::<FooInt>()); ids.push(TypeId::of::<FooUint>()); ids.push(TypeId::of::<FooFloat>()); ids.push(TypeId::of::<FooEnu...
pub mod testtypes { use std::any::TypeId;
random_line_split
issue13507.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...
{ VarA(usize), VarB(usize, usize) } // Tests TyBox (of u8) pub type FooUniq = Box<u8>; // As with TyStr, what type should be used for TyArray? // Tests TyRawPtr pub type FooPtr = *const u8; // Skipping TyRef // Skipping TyBareFn (how do you get a bare function type,...
FooEnum
identifier_name
issue13507.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...
// Tests ty_nil pub type FooNil = (); // Skipping ty_bot // Tests TyBool pub type FooBool = bool; // Tests TyChar pub type FooChar = char; // Tests TyInt (does not test all variants of IntTy) pub type FooInt = isize; // Tests TyUint (does not test all variants of UintTy) ...
{ let mut ids = vec!(); ids.push(TypeId::of::<FooNil>()); ids.push(TypeId::of::<FooBool>()); ids.push(TypeId::of::<FooInt>()); ids.push(TypeId::of::<FooUint>()); ids.push(TypeId::of::<FooFloat>()); ids.push(TypeId::of::<FooEnum>()); ids.push(TypeId::of::<F...
identifier_body
lib.rs
#[macro_use] #[cfg(test)] extern crate lazy_static; #[cfg(test)] extern crate itertools; extern crate r68k_common; #[cfg(test)] extern crate r68k_tools; pub mod cpu; pub mod ram; pub mod interrupts; pub mod musashi; #[cfg(test)] mod tests { use cpu::TestCore; use r68k_tools::memory::MemoryVec; use r68k_t...
under += 1; println!("{:04x}: {} disasm under", opcode, op); } , //println!("{:04x}:\t\tover", opcode), Ok((new_pc, dis_inst)) => if op == "???" || op == "unimplemented_1111" || op == "unimplemented_1010" || op == "illegal" { ...
{ let mut over = 0; let mut under = 0; let mut wrong = 0; let gen = InstructionSetGenerator::<TestCore>::new(); let optable: Vec<&str> = gen.generate_with("???", |ref op| op.name); let d = Disassembler::new(); for opcode in 0x0000..0xffff { let op = op...
identifier_body
lib.rs
#[macro_use] #[cfg(test)] extern crate lazy_static; #[cfg(test)] extern crate itertools; extern crate r68k_common; #[cfg(test)] extern crate r68k_tools; pub mod cpu; pub mod ram; pub mod interrupts; pub mod musashi; #[cfg(test)] mod tests { use cpu::TestCore; use r68k_tools::memory::MemoryVec; use r68k_t...
() { let mut over = 0; let mut under = 0; let mut wrong = 0; let gen = InstructionSetGenerator::<TestCore>::new(); let optable: Vec<&str> = gen.generate_with("???", |ref op| op.name); let d = Disassembler::new(); for opcode in 0x0000..0xffff { let op =...
roundtrips
identifier_name
lib.rs
#[macro_use] #[cfg(test)] extern crate lazy_static; #[cfg(test)] extern crate itertools; extern crate r68k_common; #[cfg(test)] extern crate r68k_tools; pub mod cpu; pub mod ram; pub mod interrupts; pub mod musashi; #[cfg(test)] mod tests { use cpu::TestCore; use r68k_tools::memory::MemoryVec; use r68k_t...
fn roundtrips() { let mut over = 0; let mut under = 0; let mut wrong = 0; let gen = InstructionSetGenerator::<TestCore>::new(); let optable: Vec<&str> = gen.generate_with("???", |ref op| op.name); let d = Disassembler::new(); for opcode in 0x0000..0xffff { ...
random_line_split
HomeHero.tsx
import { tappedPromoSpace } from "@artsy/cohesion" import { HomeHero_homePage } from "__generated__/HomeHero_homePage.graphql" import { HeroUnit } from "app/Components/Home/HeroUnit" import { navigate } from "app/navigation/navigate" import React from "react" import { createFragmentContainer, graphql } from "react-rela...
const handlePromoSpaceTap = () => { const path = unit.href! tracking.trackEvent(tappedPromoSpace({ path, subject: unit.title! })) navigate(path) } return <HeroUnit unit={unit} onPress={handlePromoSpaceTap} /> } export const HomeHeroContainer = createFragmentContainer(HomeHero, { homePage: graphq...
{ return null }
conditional_block
HomeHero.tsx
import { tappedPromoSpace } from "@artsy/cohesion" import { HomeHero_homePage } from "__generated__/HomeHero_homePage.graphql" import { HeroUnit } from "app/Components/Home/HeroUnit" import { navigate } from "app/navigation/navigate" import React from "react" import { createFragmentContainer, graphql } from "react-rela...
const unit = homePage?.heroUnits?.[0] if (!unit || !unit.backgroundImageURL || !unit.href) { return null } const handlePromoSpaceTap = () => { const path = unit.href! tracking.trackEvent(tappedPromoSpace({ path, subject: unit.title! })) navigate(path) } return <HeroUnit unit={unit} onPress...
const HomeHero: React.FC<{ homePage: HomeHero_homePage }> = ({ homePage }) => { const tracking = useTracking()
random_line_split
S163_L641_MissingRange.py
''' Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. Have you met this question in a real interview? Example Example 1 Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99 Output: ["2", "4->49", "51->74", "76->99"] Explanation: in ra...
""" @param: nums: a sorted integer array @param: lower: An integer @param: upper: An integer @return: a list of its missing ranges """ def findMissingRanges(self, nums, lower, upper): # write your code here r=[] prev = lower nums+=[upper+1] for cur in nums...
identifier_body
S163_L641_MissingRange.py
''' Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. Have you met this question in a real interview? Example Example 1 Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99 Output: ["2", "4->49", "51->74", "76->99"] Explanation: in ra...
elif cur - prev == 1: r += [str(cur-1)] prev = cur + 1 return r
r += [str(prev) + '->' + str(cur-1)]
conditional_block
S163_L641_MissingRange.py
''' Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. Have you met this question in a real interview? Example Example 1 Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99 Output: ["2", "4->49", "51->74", "76->99"] Explanation: in ra...
(self, nums, lower, upper): # write your code here r=[] prev = lower nums+=[upper+1] for cur in nums: if cur - prev >= 2: r += [str(prev) + '->' + str(cur-1)] elif cur - prev == 1: r += [str(cur-1)] prev = cur + ...
findMissingRanges
identifier_name
S163_L641_MissingRange.py
''' Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. Have you met this question in a real interview? Example Example 1 Input: nums = [0, 1, 3, 50, 75], lower = 0 and upper = 99 Output: ["2", "4->49", "51->74", "76->99"] Explanation: in ra...
r += [str(cur-1)] prev = cur + 1 return r
elif cur - prev == 1:
random_line_split
magic.py
skipinitialspace=True) manifest.fieldnames = ['filename', 'spritesheet'] spritesheets = {} for line in progress.bar(manifest, label='Reading Manifest: ', expected_size=lineCount): sheet = line['spritesheet'] image = line['filename']...
data = data[1:] css.write(data) css.close() return self.name + '.svg' class Variant(object): def __init__(self, variantDir, args): self.variantDir = variantDir self.baseDir = args.baseDir self.png = args.png
ale = float(self.scales[suffix]) if suffix: suffix = '-' + suffix top = 0 right = (image.offset + image.width) * scale bottom = image.height * scale left = image.offset * scale ...
conditional_block
magic.py
ifest.line_num), bold=True)), (imagePath, manifestPath, manifest.line_num)) spritesheets.setdefault(sheet, Spritesheet(sheet)).addImage(image) return spritesheets.values() class Image(object): def __init__(self, name, path): self.name = name.replace('.svg', '') ...
lePath = os.path.join(self.baseDir, self.variantDir, filename) if os.path.exists(filePath): return filePath baseFilePath = os.path.join(self.baseDir, filename) if not os.path.exists(baseFilePath): return filePath return baseFilePath
identifier_body
magic.py
skipinitialspace=True) manifest.fieldnames = ['filename', 'spritesheet'] spritesheets = {} for line in progress.bar(manifest, label='Reading Manifest: ', expected_size=lineCount): sheet = line['spritesheet'] image = line['filename']...
(self, uses): scales = {'': '1'} for use in uses: for element in use: if (element.tag == EXTRA_SCALE): # <extra-scale name="Retina" value="2"/> scales[element.attrib['name']] = element.attrib['value'] return scales def getV...
getScales
identifier_name
magic.py
skipinitialspace=True) manifest.fieldnames = ['filename', 'spritesheet'] spritesheets = {} for line in progress.bar(manifest, label='Reading Manifest: ', expected_size=lineCount): sheet = line['spritesheet'] image = line['filename']...
alternate.child.attrib['class'] = classname alternate.child.attrib['id'] += '-' + classname alternate.name += '-' + classname alternate.hasClass = True alternates.append(alternate)...
classes = element.attrib['value'].split() for classname in classes: if classname not in seenClasses: seenClasses.add(classname) alternate = copy.deepcopy(image)
random_line_split
test_file.py
# -*- encoding: utf-8 -*- # # Copyright © 2013 IBM Corp # # Author: Tong Li <litong01@us.ibm.com> # # 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/LICEN...
# Create a temporaryFile to get a file name tf = tempfile.NamedTemporaryFile('r') filename = tf.name tf.close() self.CONF.dispatcher_file.file_path = filename self.CONF.dispatcher_file.max_bytes = 50 self.CONF.dispatcher_file.backup_count = 5 dispatcher =...
self.CONF = self.useFixture(config.Config()).conf def test_file_dispatcher_with_all_config(self):
random_line_split
test_file.py
# -*- encoding: utf-8 -*- # # Copyright © 2013 IBM Corp # # Author: Tong Li <litong01@us.ibm.com> # # 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/LICEN...
test.BaseTestCase): def setUp(self): super(TestDispatcherFile, self).setUp() self.CONF = self.useFixture(config.Config()).conf def test_file_dispatcher_with_all_config(self): # Create a temporaryFile to get a file name tf = tempfile.NamedTemporaryFile('r') filename = tf...
estDispatcherFile(
identifier_name
test_file.py
# -*- encoding: utf-8 -*- # # Copyright © 2013 IBM Corp # # Author: Tong Li <litong01@us.ibm.com> # # 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/LICEN...
def test_file_dispatcher_with_all_config(self): # Create a temporaryFile to get a file name tf = tempfile.NamedTemporaryFile('r') filename = tf.name tf.close() self.CONF.dispatcher_file.file_path = filename self.CONF.dispatcher_file.max_bytes = 50 self.CONF....
uper(TestDispatcherFile, self).setUp() self.CONF = self.useFixture(config.Config()).conf
identifier_body
bandsharing_tests.py
#!/usr/bin/env python #::::::::::::::::::::::::::::::::::::::::::::::::::::: #Author: Damiano Barboni <damianobarboni@gmail.com> #Version: 0.1 #Description: Script used to test bandsharing.py #Changelog: Wed Jun 11 12:07:33 CEST 2014 # First test version # #::::::::...
unittest.TextTestRunner(verbosity=3).run(makeSuite())
conditional_block
bandsharing_tests.py
#!/usr/bin/env python #::::::::::::::::::::::::::::::::::::::::::::::::::::: #Author: Damiano Barboni <damianobarboni@gmail.com> #Version: 0.1 #Description: Script used to test bandsharing.py #Changelog: Wed Jun 11 12:07:33 CEST 2014 # First test version # #::::::::...
if __name__ == "__main__": unittest.TextTestRunner(verbosity=3).run(makeSuite())
suite = unittest.TestSuite() suite.addTest( TestBandSharing( 'test_bs' ) ) suite.addTest( TestBandSharing( 'test_csv' ) ) return suite
identifier_body
bandsharing_tests.py
#!/usr/bin/env python #::::::::::::::::::::::::::::::::::::::::::::::::::::: #Author: Damiano Barboni <damianobarboni@gmail.com> #Version: 0.1 #Description: Script used to test bandsharing.py #Changelog: Wed Jun 11 12:07:33 CEST 2014 # First test version # #::::::::...
( self ): pass def makeSuite(): suite = unittest.TestSuite() suite.addTest( TestBandSharing( 'test_bs' ) ) suite.addTest( TestBandSharing( 'test_csv' ) ) return suite if __name__ == "__main__": unittest.TextTestRunner(verbosity=3).run(makeSuite())
test_csv
identifier_name
bandsharing_tests.py
#!/usr/bin/env python #::::::::::::::::::::::::::::::::::::::::::::::::::::: #Author: Damiano Barboni <damianobarboni@gmail.com> #Version: 0.1 #Description: Script used to test bandsharing.py #Changelog: Wed Jun 11 12:07:33 CEST 2014 # First test version # #::::::::...
def setUp(self): pass def test_bs( self ): pass def test_csv( self ): pass def makeSuite(): suite = unittest.TestSuite() suite.addTest( TestBandSharing( 'test_bs' ) ) suite.addTest( TestBandSharing( 'test_csv' ) ) return suite if...
bandsharing_path = os.path.abspath(os.path.join( current_path, os.pardir)) sys.path.insert(1, bandsharing_path) class TestBandSharing( unittest.TestCase ):
random_line_split
generators.js
function DateGenerator(start) { this.current = start; this.next = function() { var format = d3.time.format("%Y%m%d"); this.current.setDate(this.current.getDate() + 1); return format(this.current); } } function IntGenerator(start, f) { this.current = start; this.f = f; this.next = function() { this.curren...
if (col.name === x) { var g = getGenerator(col); generators.push(g); continue; } // Y if (typeof y === 'string') { if (col.name === y) { var g = getGenerator(col); generators.push(g); continue; } } else { // Arrays if ($.inArray(col.name, y) != -1) { var g = getGenerator(col...
{ var visId = vis.name; var type = vis.type; var x = vis.x; var y = vis.y; var generators = []; var testData = []; for (c in vis.datatable.cols) { var col = vis.datatable.cols[c]; // Special case if (col.field === "$__date") { var dg = new DateGenerator(new Date(2012, 01, 01)); generators.push(dg)...
identifier_body
generators.js
function DateGenerator(start) { this.current = start; this.next = function() { var format = d3.time.format("%Y%m%d"); this.current.setDate(this.current.getDate() + 1);
} function IntGenerator(start, f) { this.current = start; this.f = f; this.next = function() { this.current = f(this.current); return this.current; } } function OrdinalGenerator() { this.currCat = -1; this.cats = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"]; this.next =...
return format(this.current); }
random_line_split
generators.js
function DateGenerator(start) { this.current = start; this.next = function() { var format = d3.time.format("%Y%m%d"); this.current.setDate(this.current.getDate() + 1); return format(this.current); } } function IntGenerator(start, f) { this.current = start; this.f = f; this.next = function() { this.curren...
() { this.currCat = -1; this.cats = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"]; this.next = function() { if (this.currCat > this.cats.length) return null; return this.cats[this.currCat++]; } } function NullGenerator() { this.next = function() { } } RandomIntFunction = fu...
OrdinalGenerator
identifier_name
threat.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import CustomAttributable, BusinessObject, Timeboxed from ggrc.models.object_document import Documentable from ggrc.models.object_person import Personable from ggr...
( HasObjectState, CustomAttributable, Documentable, Personable, Relatable, Timeboxed, Ownable, BusinessObject, db.Model): __tablename__ = 'threats' _aliases = { "contact": { "display_name": "Contact", "filter_by": "_filter_by_contact", }, "secondary_contact": None, ...
Threat
identifier_name
threat.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import CustomAttributable, BusinessObject, Timeboxed from ggrc.models.object_document import Documentable from ggrc.models.object_person import Personable from ggr...
__tablename__ = 'threats' _aliases = { "contact": { "display_name": "Contact", "filter_by": "_filter_by_contact", }, "secondary_contact": None, "url": "Threat URL", }
identifier_body
threat.py
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.mixins import CustomAttributable, BusinessObject, Timeboxed from ggrc.models.object_document import Documentable from ggrc.models.object_person import Personable from ggr...
"contact": { "display_name": "Contact", "filter_by": "_filter_by_contact", }, "secondary_contact": None, "url": "Threat URL", }
_aliases = {
random_line_split
gjoneska_pfenning.py
", # BP 301 L03 D04 CJ viral process "GO:0050792", # BP 119 L03 D04 AB regulation of viral process "GO:0098542", # BP 37 L03 D05 GJ defense response to other organism "GO:0009617", # BP 12 L03 D05 GJ response to bacterium ]), ("neuro", [ # 25 GO-headers ...
"GO:0007155", # BP 165 L02 D02 P cell adhesion ]), ("cell cycle", [ # 9 GO-headers "GO:0022402", # BP 463 L02 D02 C cell cycle process "GO:0022403", # BP 46 L02 D02 S cell cycle phase "GO:0051726", # BP 411 L03 D03 AB regulation of cell cycle "...
random_line_split
purchase_order_line.py
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, fields, api, _ from odoo.exceptions import UserE...
return res
If we came from invoice, we send in context 'force_line_edit' and we change tree view to make editable and also field qty """ res = super().fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) if self._context.get('force_line...
identifier_body
purchase_order_line.py
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, fields, api, _ from odoo.exceptions import UserE...
@api.onchange('product_qty') def _onchange_product_qty(self): if ( self.state == 'purchase' and self.product_id.type in ['product', 'consu'] and self.product_qty < self._origin.product_qty): warning_mess = { 'title': _('Ordered quan...
e.state not in ('purchase', 'done'): line.delivery_status = 'no' continue if line.order_id.force_delivered_status: line.delivery_status = line.order_id.force_delivered_status continue if float_compare( (line.qty_...
conditional_block
purchase_order_line.py
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, fields, api, _ from odoo.exceptions import UserE...
qty += move.product_uom._compute_quantity( move.product_uom_qty, line.product_uom) line.qty_returned = qty # Overwrite the origin method to introduce the qty_on_voucher def action_add_all_to_invoice(self): for rec in self: ...
for move in line.move_ids.filtered( lambda m: m.state == 'done' and m.location_id.usage != 'supplier' and m.to_refund):
random_line_split
purchase_order_line.py
############################################################################## # For copyright and license notices, see __manifest__.py file in module root # directory ############################################################################## from odoo import models, fields, api, _ from odoo.exceptions import UserE...
: for rec in self: rec.vouchers = ', '.join(rec.mapped( 'move_ids.picking_id.voucher_ids.display_name')) @api.depends( 'order_id.state', 'qty_received', 'qty_returned', 'product_qty', 'order_id.force_delivered_status') def _compute_delivery_status(self): ...
te_vouchers(self)
identifier_name
test_deprecations.py
This used to mean that when an error occurred during element-wise comparison (i.e. broadcasting) NotImplemented was returned, but also in the comparison itself, False was given instead of the error. Also test FutureWarning for the None comparison. """ message = "elementwise.* comparison failed; ....
class TestDatetime64Timezone(_DeprecationTestCase): """Parsing of datetime64 with timezones deprecated in 1.11.0, because datetime64 is now timezone naive rather than UTC only. It will be quite a while before we can remove this, because, at the very least, a lot of existing code uses the 'Z' modifie...
assert_warns(DeprecationWarning, f, arg1, arg2)
conditional_block
test_deprecations.py
from __future__ import division, absolute_import, print_function import datetime import sys import operator import warnings import pytest import shutil import tempfile import numpy as np from numpy.testing import ( assert_raises, assert_warns, assert_, assert_array_equal ) from numpy.core._multiarray_tests i...
"""
random_line_split
test_deprecations.py
class TestComparisonDeprecations(_DeprecationTestCase): """This tests the deprecation, for non-element-wise comparison logic. This used to mean that when an error occurred during element-wise comparison (i.e. broadcasting) NotImplemented was returned, but also in the comparison itself, False was give...
a = np.zeros((5, 5)) with warnings.catch_warnings(): warnings.filterwarnings('always') assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]]) assert_warns(FutureWarning, a.__getitem__, [slice(None)]) warnings.filterwarnings('error') assert_raise...
identifier_body
test_deprecations.py
This used to mean that when an error occurred during element-wise comparison (i.e. broadcasting) NotImplemented was returned, but also in the comparison itself, False was given instead of the error. Also test FutureWarning for the None comparison. """ message = "elementwise.* comparison failed; ....
(self): class NotArray(object): def __array__(self): raise TypeError # Needed so Python 3 does not raise DeprecationWarning twice. def __ne__(self, other): return NotImplemented self.assert_deprecated(lambda: np.arange(2) == NotArray(...
test_void_dtype_equality_failures
identifier_name
login.ts
import { Component, View } from 'angular2/core'; import { Router, RouterLink } from 'angular2/router'; import { CORE_DIRECTIVES, FORM_DIRECTIVES } from 'angular2/common'; import { Http, Headers } from 'angular2/http'; import { contentHeaders } from '../common/headers'; let styles = require('./login.css'); let templa...
console.log(error.text()); } ); } signup(event) { event.preventDefault(); this.router.parent.navigateByUrl('/signup'); } }
random_line_split
login.ts
import { Component, View } from 'angular2/core'; import { Router, RouterLink } from 'angular2/router'; import { CORE_DIRECTIVES, FORM_DIRECTIVES } from 'angular2/common'; import { Http, Headers } from 'angular2/http'; import { contentHeaders } from '../common/headers'; let styles = require('./login.css'); let templa...
(event, username, password) { let body = JSON.stringify({ username, password }); this.http.post('http://localhost:8080/kouponify/users/authenticate', body, { headers: contentHeaders }) .subscribe( response => { localStorage.setItem('jwt', response.json().token); this.router.par...
login
identifier_name
field_multi_text.js
/* global redux_change */ (function( $ ) { "use strict"; $.reduxMultiText = $.reduxMultiText || {};
} ); $.reduxMultiText.init = function() { $( '.redux-multi-text-remove' ).live( 'click', function() { redux_change( $( this ) ); $( this ).prev( 'input[type="text"]' ).val( '' ); $( this ).parent().slideUp( 'medium'...
$( document ).ready( function() { $.reduxMultiText.init();
random_line_split
field_multi_text.js
/* global redux_change */ (function( $ ) { "use strict"; $.reduxMultiText = $.reduxMultiText || {}; $( document ).ready( function() { $.reduxMultiText.init(); } ); $.reduxMultiText.init = function() { $( '.redux-multi-text-remove' ).live( 'click', ...
} ); }; })( jQuery );
{ var new_input = $( '#' + id + ' li:last-child' ).clone(); $( '#' + id ).append( new_input ); $( '#' + id + ' li:last-child' ).removeAttr( 'style' ); $( '#' + id + ' li:last-child input[type="text"]' ).val( '' ); $( '#'...
conditional_block
account.js
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser') var chip = require('../../chip.js'); var Syndicate = require('../../model/syndicate'); var Account = require('../../model/account'); var Group = require('../../model/group'); var Engine = ...
passport.use(new LocalStrategy( function(key, password, done) { //chip.db.queryAsync( /* connection.query("SELECT * FROM player p WHERE sid IS NOT NULL AND name='"+username+"'", function(err, result) { if (err) throw err; if (result.length > 0 && password == 'oredic37') { var player = User.c...
{ return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); if (g) chip.removeGroup(g.groupme_id); else g = group; g.groupme_id = req.body.groupme_id; g.bot_key = req.body.bot_key; g.bot_id = null; g.output = req.body.output == 'true'; g.scout = req.body.sco...
identifier_body
account.js
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser') var chip = require('../../chip.js'); var Syndicate = require('../../model/syndicate'); var Account = require('../../model/account'); var Group = require('../../model/group'); var Engine = ...
(req, res, next) { return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); if (g) chip.removeGroup(g.groupme_id); else g = group; g.groupme_id = req.body.groupme_id; g.bot_key = req.body.bot_key; g.bot_id = null; g.output = req.body.output == 'true'; g.sco...
updateGroup
identifier_name
account.js
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser') var chip = require('../../chip.js'); var Syndicate = require('../../model/syndicate'); var Account = require('../../model/account'); var Group = require('../../model/group'); var Engine = ...
bot_key: req.body.bot_key, output: req.body.output == 'true', scout: req.body.scout == 'true', debug: req.body.debug == 'true' }); return g.save().then(function() { req.params.gid = g.gid; chip.addGroup(g); res.json(g); }); } function updateGroup(req, res, next) { return Group.get(req.params.gid).t...
var g = Group.create({ sid: req.body.sid, groupme_id: req.body.groupme_id,
random_line_split
account.js
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser') var chip = require('../../chip.js'); var Syndicate = require('../../model/syndicate'); var Account = require('../../model/account'); var Group = require('../../model/group'); var Engine = ...
}
{ req.session.loginRedirect = req.url; res.redirect('/'); }
conditional_block
region-bounds-on-objects-and-type-parameters.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 ...
// Bounds on object types: struct Foo<'a,'b,'c> { // All of these are ok, because we can derive exactly one bound: a: Box<IsStatic>, b: Box<Is<'static>>, c: Box<Is<'a>>, d: Box<IsSend>, e: Box<Is<'a>+Send>, // we can derive two bounds, but one is 'static, so ok f: Box<SomeTrait>, // OK, d...
random_line_split
region-bounds-on-objects-and-type-parameters.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 ...
<'a,'b,'c> { // All of these are ok, because we can derive exactly one bound: a: Box<IsStatic>, b: Box<Is<'static>>, c: Box<Is<'a>>, d: Box<IsSend>, e: Box<Is<'a>+Send>, // we can derive two bounds, but one is 'static, so ok f: Box<SomeTrait>, // OK, defaults to 'static due to RFC 599. ...
Foo
identifier_name
region-bounds-on-objects-and-type-parameters.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 ...
fn main() { }
{ }
identifier_body
status.test.js
import { factory } from '../helpers' let hero = factory.hero() describe('status', () => { test('should return an object with characteristic name as key', () => { let status = hero.status.get() expect(Object.keys(status)).toContain('life') expect(Object.keys(status)).toContain('defense') expect(statu...
symbol: 'G', value: 1000 }).then(() => { expect(hero.status.get('gold')).toBe(1000) }) }) })
return hero.bank.earn({ name: 'Gold',
random_line_split
storm_cluster_test.py
import os import pytest from pyleus.cli.storm_cluster import _get_storm_cmd_env from pyleus.cli.storm_cluster import STORM_JAR_JVM_OPTS from pyleus.cli.storm_cluster import StormCluster from pyleus.cli.storm_cluster import TOPOLOGY_BUILDER_CLASS from pyleus.testing import mock class TestGetStormCmdEnd(object): ...
"nimbus.host=test-host"] def test__build_storm_cmd_with_port(self, cluster): cluster.nimbus_host = "test-host" cluster.nimbus_port = 4321 storm_cmd = cluster._build_storm_cmd(["another", "cmd"]) assert storm_cmd == [mock.sentinel.storm_cmd_path, "another...
cluster.nimbus_port = None storm_cmd = cluster._build_storm_cmd(["a", "cmd"]) assert storm_cmd == [mock.sentinel.storm_cmd_path, "a", "cmd", "-c",
random_line_split
storm_cluster_test.py
import os import pytest from pyleus.cli.storm_cluster import _get_storm_cmd_env from pyleus.cli.storm_cluster import STORM_JAR_JVM_OPTS from pyleus.cli.storm_cluster import StormCluster from pyleus.cli.storm_cluster import TOPOLOGY_BUILDER_CLASS from pyleus.testing import mock class TestGetStormCmdEnd(object): ...
(self): jvm_opts = "-Dfoo=bar" env = _get_storm_cmd_env(jvm_opts) assert env[STORM_JAR_JVM_OPTS] == jvm_opts class TestStormCluster(object): @pytest.fixture def cluster(self): return StormCluster( mock.sentinel.storm_cmd_path, mock.sentinel.nimbus_host,...
test_jvm_opts_set
identifier_name
storm_cluster_test.py
import os import pytest from pyleus.cli.storm_cluster import _get_storm_cmd_env from pyleus.cli.storm_cluster import STORM_JAR_JVM_OPTS from pyleus.cli.storm_cluster import StormCluster from pyleus.cli.storm_cluster import TOPOLOGY_BUILDER_CLASS from pyleus.testing import mock class TestGetStormCmdEnd(object): ...
with mock.patch.object(cluster, '_exec_storm_cmd', autospec=True) as mock_exec: cluster.submit(mock.sentinel.jar_path) mock_exec.assert_called_once_with(["jar", mock.sentinel.jar_path, TOPOLOGY_BUILDER_CLASS])
identifier_body
ElseStartCommand.ts
import { LineResults } from "../LineResults"; import { CommandNames } from "../Names/CommandNames"; import { Command } from "./Command"; import { CommandResult } from "./CommandResult"; import { CommandMetadata } from "./Metadata/CommandMetadata"; import { addLineEnder } from "./Utilities"; /** * Starts an else state...
(): CommandMetadata { return ElseStartCommand.metadata; } /** * Renders the command for a language with the given parameters. * * @param parameters The command's name, followed by any parameters. * @returns Line(s) of code in the language. */ public render(parameters: str...
getMetadata
identifier_name
ElseStartCommand.ts
import { LineResults } from "../LineResults"; import { CommandNames } from "../Names/CommandNames"; import { Command } from "./Command"; import { CommandResult } from "./CommandResult"; import { CommandMetadata } from "./Metadata/CommandMetadata"; import { addLineEnder } from "./Utilities";
/** * Starts an else statement. */ export class ElseStartCommand extends Command { /** * Metadata on the command. */ private static metadata: CommandMetadata = new CommandMetadata(CommandNames.ElseStart) .withDescription("Starts an else statement") .withIndentation([-1, 1]); /**...
random_line_split
ElseStartCommand.ts
import { LineResults } from "../LineResults"; import { CommandNames } from "../Names/CommandNames"; import { Command } from "./Command"; import { CommandResult } from "./CommandResult"; import { CommandMetadata } from "./Metadata/CommandMetadata"; import { addLineEnder } from "./Utilities"; /** * Starts an else state...
else { lines[lines.length - 1].indentation = 1; } lines[lines.length - 1].text += this.language.syntax.conditionals.continueRight; return new LineResults(lines); } }
{ lines.push(new CommandResult("", 1)); }
conditional_block
ElseStartCommand.ts
import { LineResults } from "../LineResults"; import { CommandNames } from "../Names/CommandNames"; import { Command } from "./Command"; import { CommandResult } from "./CommandResult"; import { CommandMetadata } from "./Metadata/CommandMetadata"; import { addLineEnder } from "./Utilities"; /** * Starts an else state...
/** * Renders the command for a language with the given parameters. * * @param parameters The command's name, followed by any parameters. * @returns Line(s) of code in the language. */ public render(parameters: string[]): LineResults { const lines = [new CommandResult("", -1...
{ return ElseStartCommand.metadata; }
identifier_body
header.js
/** * math.js * https://github.com/josdejong/mathjs * * Math.js is an extensive math library for JavaScript and Node.js, * It features real and complex numbers, units, matrices, a large set of * mathematical functions, and a flexible expression parser. * * @version @@version * @date @@date * * @license *...
* License for the specific language governing permissions and limitations under * 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
random_line_split
run-command.ts
import { exec } from 'child_process'; import { promisify } from 'util'; export interface RunCommandOptions { cwd?: string; showLog?: boolean; } const DEFAULT_OPTIONS: RunCommandOptions = { cwd: process.cwd(), showLog: false }; export async function runCommand(command: string, options?: RunCommandOptions) { let...
}
}
random_line_split
run-command.ts
import { exec } from 'child_process'; import { promisify } from 'util'; export interface RunCommandOptions { cwd?: string; showLog?: boolean; } const DEFAULT_OPTIONS: RunCommandOptions = { cwd: process.cwd(), showLog: false }; export async function runCommand(command: string, options?: RunCommandOptions)
} if (stderr) { errorMessage += `\nstderr: ${stderr}`; } throw new Error(errorMessage); } }
{ let { cwd, showLog } = Object.assign({}, DEFAULT_OPTIONS, options); try { console.log(`Running "${command}" in "${cwd}"`); const { stdout, stderr } = await promisify(exec)(command, { cwd }); if (showLog && stdout) { console.log(stdout); } if (stderr) { console.log(`stderr from "...
identifier_body
run-command.ts
import { exec } from 'child_process'; import { promisify } from 'util'; export interface RunCommandOptions { cwd?: string; showLog?: boolean; } const DEFAULT_OPTIONS: RunCommandOptions = { cwd: process.cwd(), showLog: false }; export async function
(command: string, options?: RunCommandOptions) { let { cwd, showLog } = Object.assign({}, DEFAULT_OPTIONS, options); try { console.log(`Running "${command}" in "${cwd}"`); const { stdout, stderr } = await promisify(exec)(command, { cwd }); if (showLog && stdout) { console.log(stdout); } ...
runCommand
identifier_name
run-command.ts
import { exec } from 'child_process'; import { promisify } from 'util'; export interface RunCommandOptions { cwd?: string; showLog?: boolean; } const DEFAULT_OPTIONS: RunCommandOptions = { cwd: process.cwd(), showLog: false }; export async function runCommand(command: string, options?: RunCommandOptions) { let...
} catch ({ message, stdout, stderr }) { let errorMessage = `Error running "${command}" in "${cwd}": ${message}.`; if (stdout) { errorMessage += `\nstdout: ${stdout}`; console.error(stdout); } if (stderr) { errorMessage += `\nstderr: ${stderr}`; } throw new Error(errorMessage...
{ console.log(`stderr from "${command}" in "${cwd}"`); console.warn(stderr); }
conditional_block
validate_examples.py
import os import sys import yaml import re from subprocess import Popen, PIPE, call from random import randrange from threading import Thread import SocketServer import struct import pdb sys.path.insert(0, '/usr/local/lib/python2.6/dist-packages/rethinkdb') import ql2_pb2 as p # tree of YAML documents defining docume...
(): # Setup void server port = randrange(1025, 65535) server = SocketServer.TCPServer(('localhost', port), BlackHoleRDBHandler) t = Thread(target=server.serve_forever) t.start() try: #validate_for('py', port) #validate_for('js', port) #validate_for('rb', port) v...
validate
identifier_name
validate_examples.py
import os import sys import yaml import re from subprocess import Popen, PIPE, call from random import randrange from threading import Thread import SocketServer import struct import pdb sys.path.insert(0, '/usr/local/lib/python2.6/dist-packages/rethinkdb') import ql2_pb2 as p # tree of YAML documents defining docume...
out.write(""" $LOAD_PATH.unshift('../../../drivers/ruby/lib') require 'rethinkdb.rb' include RethinkDB::Shortcuts conn = r.connect('localhost', %d) puts 'Running Ruby validation.' """ % port) elif lang == 'ph': out.write(""" <?php error_reporting(-1); set_include_path("../src"); require_...
test_file_name = 'build/test.%s' % lang with open(test_file_name, 'w') as out: if lang == 'py': out.write(""" from sys import path path.insert(0, '../../../drivers/python') import rethinkdb as r conn = r.connect(port=%d) print 'Running python validation.' """ % port) elif lang == 'js': ...
identifier_body
validate_examples.py
import os import sys import yaml import re from subprocess import Popen, PIPE, call from random import randrange from threading import Thread import SocketServer import struct import pdb sys.path.insert(0, '/usr/local/lib/python2.6/dist-packages/rethinkdb') import ql2_pb2 as p # tree of YAML documents defining docume...
if lang == 'js': out.write("console.log('Javascript validation complete.');\n"); out.write("conn.close()})") if lang == 'py': out.write("print 'Python validation complete.'"); if lang == 'rb': out.write("puts 'Ruby validation complete.'"); ...
test_case = re.sub("\n", " %s %s\n" % (comment, test_tag), test_case) out.write("%s %s %s\n" % (test_case, comment, test_tag))
conditional_block
validate_examples.py
import os import sys import yaml import re from subprocess import Popen, PIPE, call from random import randrange from threading import Thread import SocketServer import struct import pdb sys.path.insert(0, '/usr/local/lib/python2.6/dist-packages/rethinkdb') import ql2_pb2 as p # tree of YAML documents defining docume...
out.write(""" var r = require("../../../../drivers/javascript/build/rethinkdb"); var callback = (function() { }); var cur = {next:(function(){}), hasNext:(function(){}), each:(function(){}), toArray:(function(){})}; r.connect({port:%d}, function(err, conn) { console.log("Running Javascript validation."); ...
print 'Running python validation.' """ % port) elif lang == 'js':
random_line_split
vsmobilecentertest.ts
([^"]+)"/; function getEndpointAPIToken(endpointInputFieldName) { var errorMessage = tl.loc("CannotDecodeEndpoint"); var endpoint = tl.getInput(endpointInputFieldName, true); if (!endpoint) { throw new Error(errorMessage); } let authToken = tl.getEndpointAuthorizationParameter(endpoint, '...
() { tl.setResourcePath(path.join(__dirname, 'task.json')); let cliPath = getCliPath(); let loggedIn = false; let testRunId: string = null; try { tl.checkPath(cliPath, "mobile-center"); let debug: boolean = tl.getBoolInput('debug', false); let prepareTests: boolean = tl.get...
run
identifier_name
vsmobilecentertest.ts
"]+)"/; function getEndpointAPIToken(endpointInputFieldName) { var errorMessage = tl.loc("CannotDecodeEndpoint"); var endpoint = tl.getInput(endpointInputFieldName, true); if (!endpoint) { throw new Error(errorMessage); } let authToken = tl.getEndpointAuthorizationParameter(endpoint, 'api...
testRunner.arg('--quiet'); if (credsType === 'serviceEndpoint') { // add api key let apiToken = getEndpointAPIToken('serverEndpoint'); testRunner.arg(['--token', apiToken]); } testRunner.on('stdline', line => { let match = testRunIdLineRegexp.exec(line); if (mat...
{ testRunner.arg('--debug'); }
conditional_block
vsmobilecentertest.ts
"]+)"/; function getEndpointAPIToken(endpointInputFieldName) { var errorMessage = tl.loc("CannotDecodeEndpoint"); var endpoint = tl.getInput(endpointInputFieldName, true); if (!endpoint) { throw new Error(errorMessage); } let authToken = tl.getEndpointAuthorizationParameter(endpoint, 'api...
function addStringArg(argName: string, inputName: string, required: boolean, tr: ToolRunner) { addArg(argName, () => { return tl.getInput(inputName, required) }, tr); } function addBooleanArg(argName: string, inputName: string, tr: ToolRunner) { let booleanArg = tl.getBoolInput(inputName, false); if (boo...
{ let arg = getInput(); if (arg) { tr.arg([argName, arg]); } }
identifier_body
vsmobilecentertest.ts
([^"]+)"/; function getEndpointAPIToken(endpointInputFieldName) { var errorMessage = tl.loc("CannotDecodeEndpoint"); var endpoint = tl.getInput(endpointInputFieldName, true); if (!endpoint) { throw new Error(errorMessage); } let authToken = tl.getEndpointAuthorizationParameter(endpoint, '...
let debug: boolean = tl.getBoolInput('debug', false); let prepareTests: boolean = tl.getBoolInput('enablePrepare', false); let runTests: boolean = tl.getBoolInput('enableRun', false); let artifactsDir = tl.getInput('artifactsDir', true); let credsType = tl.getInput('credsType', t...
try { tl.checkPath(cliPath, "mobile-center");
random_line_split
net.py
2.5 seconds on 18 minions with 72 addresses for success. Failures take between 6 to 12 seconds. Optimizations should focus there. TODO: Convert commented out print statements to log.debug CLI Example: (Before DeepSea with a cluster configuration) .. code-block:: bash sudo salt-run net.pi...
""" Skip double underscore keys """ return {k:v for k,v in settings.iteritems() if not k.startswith('__')}
identifier_body
net.py
def ping(cluster = None, exclude = None, **kwargs): """ Ping all addresses from all addresses on all minions. If cluster is passed, restrict addresses to public and cluster networks. Note: Some optimizations could be done here in the multi module (such as skipping the source and destination when t...
TODO: Convert commented out print statements to log.debug CLI Example: (Before DeepSea with a cluster configuration) .. code-block:: bash sudo salt-run net.ping or you can run it with exclude .. code-block:: bash sudo salt-run net.ping exclude="E@host*,host-osd-name*,192.168.1.1" ...
unoptimized version is taking ~2.5 seconds on 18 minions with 72 addresses for success. Failures take between 6 to 12 seconds. Optimizations should focus there.
random_line_split
net.py
ping(cluster = None, exclude = None, **kwargs): """ Ping all addresses from all addresses on all minions. If cluster is passed, restrict addresses to public and cluster networks. Note: Some optimizations could be done here in the multi module (such as skipping the source and destination when they...
(total, results): """ Summarize the successes, failures and errors across all minions """ success = [] failed = [] errored = [] slow = [] log.debug( "_summarize: results {}".format(results)) for host in sorted(results.iterkeys()): if results[host]['succeeded'] == total: ...
_summarize
identifier_name
net.py
ping(cluster = None, exclude = None, **kwargs): """ Ping all addresses from all addresses on all minions. If cluster is passed, restrict addresses to public and cluster networks. Note: Some optimizations could be done here in the multi module (such as skipping the source and destination when they...
print "Succeeded: {} addresses from {} minions average rtt {} ms".format(total, len(success), "{0:.2f}".format(avg)) if slow: print "Warning: \n {}".format("\n ".join(slow))
avg = 0
conditional_block
core-help.js
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDesc...
framework.addJavaScriptHelp("apropos", "substring, fileName", "output all the helper functions whose name or description contains the given 'substring'"); function apropos(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, true), fileName); } else if (arguments.length > ...
{ if (arguments.length > 1) { write(getHelp(substring, false), fileName); } else if (arguments.length > 0) { write(getHelp(substring, false)); } else { write(getHelp("", false)); } }
identifier_body
core-help.js
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDesc...
} } framework.addJavaScriptHelp("apropos", "substring, fileName", "output all the helper functions whose name or description contains the given 'substring'"); function apropos(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, true), fileName); } else if (arguments.le...
random_line_split
core-help.js
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDesc...
else if (arguments.length > 0) { write(framework.getJavaScriptHelp(regex, false)); } }
{ write(framework.getJavaScriptHelp(regex, false), fileName); }
conditional_block
core-help.js
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function
(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDescription); } framework.addJavaScriptHelp("help", "substring, fileName", "output all the helper functions whose name contains the given 'substring'"); function help(substring, fileName) { if (argumen...
getHelp
identifier_name
test_1d.py
# -*- coding: utf-8 -*- from __future__ import division, print_function import finufft from finufft import interface import numpy as np import pytest __all__ = [ "test_nufft1d1", "test_nufft1d2", "test_nufft1d3", ] def test_nufft1d1(seed=42, iflag=1): np.random.seed(seed) ms = int(1e3) n = int(2e...
np.random.seed(seed) ms = int(1e3) n = int(2e3) tol = 1.0e-9 x = np.random.uniform(-np.pi, np.pi, n) c = np.random.uniform(-1.0, 1.0, n) + 1.0j*np.random.uniform(-1.0, 1.0, n) s = 0.5 * n * (1.7 + np.random.uniform(-1.0, 1.0, ms)) f = finufft.nufft1d3(x, c, s, eps=tol, iflag=iflag) f0...
identifier_body
test_1d.py
# -*- coding: utf-8 -*- from __future__ import division, print_function import finufft from finufft import interface import numpy as np import pytest __all__ = [ "test_nufft1d1", "test_nufft1d2", "test_nufft1d3", ] def test_nufft1d1(seed=42, iflag=1): np.random.seed(seed) ms = int(1e3) n = int(2e...
with pytest.raises(TypeError): f = finufft.nufft1d1(x, c, ms, eps=tol, iflag=iflag, fftw=100) f0 = interface.dirft1d1(x, c, ms, iflag=iflag) assert np.all(np.abs((f - f0) / f0) < 1e-6) def test_nufft1d2(seed=42, iflag=1): np.random.seed(seed) ms = int(1e3) n = int(2e3) tol = 1.0e...
# Make sure that this also works with other values of 'fftw' f = finufft.nufft1d1(x, c, ms, eps=tol, iflag=iflag, fftw=interface.FFTWOptions.measure)
random_line_split
test_1d.py
# -*- coding: utf-8 -*- from __future__ import division, print_function import finufft from finufft import interface import numpy as np import pytest __all__ = [ "test_nufft1d1", "test_nufft1d2", "test_nufft1d3", ] def test_nufft1d1(seed=42, iflag=1): np.random.seed(seed) ms = int(1e3) n = int(2e...
(seed=42, iflag=1): np.random.seed(seed) ms = int(1e3) n = int(2e3) tol = 1.0e-9 x = np.random.uniform(-np.pi, np.pi, n) c = np.random.uniform(-1.0, 1.0, n) + 1.0j*np.random.uniform(-1.0, 1.0, n) s = 0.5 * n * (1.7 + np.random.uniform(-1.0, 1.0, ms)) f = finufft.nufft1d3(x, c, s, eps=...
test_nufft1d3
identifier_name
0005_auto_20150802_0303.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
(migrations.Migration): dependencies = [ ('imager_profile', '0004_auto_20150802_0153'), ] operations = [ migrations.RemoveField( model_name='imagerprofile', name='name', ), migrations.AddField( model_name='imagerprofile', name...
Migration
identifier_name
0005_auto_20150802_0303.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
model_name='imagerprofile', name='camera', field=models.CharField(help_text=b'What is the make and model of your camera?', max_length=128, null=True, blank=True), ), migrations.AlterField( model_name='imagerprofile', name='photography_type', ...
dependencies = [ ('imager_profile', '0004_auto_20150802_0153'), ] operations = [ migrations.RemoveField( model_name='imagerprofile', name='name', ), migrations.AddField( model_name='imagerprofile', name='nickname', fiel...
identifier_body