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
setupFormatters.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
export default function setupFormatters() { getNumberFormatterRegistry() // Add shims for format strings that are deprecated or common typos. // Temporary solution until performing a db migration to fix this. .registerValue(',0', getNumberFormatter(',.4~f')) .registerValue('null', getNumberFormatter('...
getTimeFormatterRegistry, smartDateFormatter, smartDateVerboseFormatter, } from '@superset-ui/core';
random_line_split
setupFormatters.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
.registerValue('.r', getNumberFormatter('.4~f')) .registerValue('$,.0', getNumberFormatter('$,d')) .registerValue('$,.1', getNumberFormatter('$,.1~f')) .registerValue(',0s', getNumberFormatter(',.4~f')) .registerValue('%%%', getNumberFormatter('.0%')) .registerValue(',0f', getNumberFormatter(',d...
{ getNumberFormatterRegistry() // Add shims for format strings that are deprecated or common typos. // Temporary solution until performing a db migration to fix this. .registerValue(',0', getNumberFormatter(',.4~f')) .registerValue('null', getNumberFormatter(',.4~f')) .registerValue('%', getNumber...
identifier_body
setupFormatters.ts
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
() { getNumberFormatterRegistry() // Add shims for format strings that are deprecated or common typos. // Temporary solution until performing a db migration to fix this. .registerValue(',0', getNumberFormatter(',.4~f')) .registerValue('null', getNumberFormatter(',.4~f')) .registerValue('%', getNum...
setupFormatters
identifier_name
reference.py
import sys import pprint class Reference(object): def __init__(self, tb_index, varname, target): self.tb_index = tb_index self.varname = varname self.target = target def marker(self, xtb, tb_index, key): return Marker(self, xtb, tb_index, key) class Marker(object):
raise RuntimeError("Expecting to be called with " "XTraceback._format_variable in stack") pretty_repr = pprint.pformat(self.reference.target) if indent + len(self.key) + len(pretty_repr) > self.xtb.print_width \ or pretty_repr.find("\n") > 0: ...
def __init__(self, reference, xtb, tb_index, key): self.reference = reference self.xtb = xtb self.tb_index = tb_index self.key = key self.tb_offset = self.reference.tb_index - self.tb_index def __repr__(self): frame = sys._getframe(1) while frame: ...
identifier_body
reference.py
import sys
def __init__(self, tb_index, varname, target): self.tb_index = tb_index self.varname = varname self.target = target def marker(self, xtb, tb_index, key): return Marker(self, xtb, tb_index, key) class Marker(object): def __init__(self, reference, xtb, tb_index, key): ...
import pprint class Reference(object):
random_line_split
reference.py
import sys import pprint class Reference(object): def __init__(self, tb_index, varname, target): self.tb_index = tb_index self.varname = varname self.target = target def marker(self, xtb, tb_index, key): return Marker(self, xtb, tb_index, key) class Marker(object): def...
else: # pragma: no cover - defensive raise RuntimeError("Expecting to be called with " "XTraceback._format_variable in stack") pretty_repr = pprint.pformat(self.reference.target) if indent + len(self.key) + len(pretty_repr) > self.xtb.print_width \ ...
try: code = self.xtb._format_variable.func_code except AttributeError: # python 3 code = self.xtb._format_variable.__code__ if frame.f_code == code: indent = frame.f_locals["indent"] + 4 break frame = fra...
conditional_block
reference.py
import sys import pprint class Reference(object): def
(self, tb_index, varname, target): self.tb_index = tb_index self.varname = varname self.target = target def marker(self, xtb, tb_index, key): return Marker(self, xtb, tb_index, key) class Marker(object): def __init__(self, reference, xtb, tb_index, key): self.referenc...
__init__
identifier_name
mod.rs
use num::{One, Integer}; use num::bigint::{BigUint, RandBigInt}; use rand::Rng; use utils::primes::tests::PrimeTest; pub mod tests; const PRIME_TEST_COUNT: usize = 20; /// Generate new prime number with given bit size via given random number generator. /// /// Currently this function give guarantee that it ever end...
if tests::MillerRabin(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue } return Some(int) } }
{ continue }
conditional_block
mod.rs
use num::{One, Integer}; use num::bigint::{BigUint, RandBigInt}; use rand::Rng; use utils::primes::tests::PrimeTest; pub mod tests; const PRIME_TEST_COUNT: usize = 20; /// Generate new prime number with given bit size via given random number generator. /// /// Currently this function give guarantee that it ever end...
{ loop { let mut int = gen.gen_biguint(bits); if int.is_even() { int = int + BigUint::one(); } if tests::Fermat(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue } if tests::MillerRabin(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue } retur...
identifier_body
mod.rs
use num::{One, Integer}; use num::bigint::{BigUint, RandBigInt}; use rand::Rng; use utils::primes::tests::PrimeTest; pub mod tests; const PRIME_TEST_COUNT: usize = 20; /// Generate new prime number with given bit size via given random number generator. /// /// Currently this function give guarantee that it ever end...
<T: Rng + RandBigInt>(gen: &mut T, bits: usize) -> Option<BigUint> { loop { let mut int = gen.gen_biguint(bits); if int.is_even() { int = int + BigUint::one(); } if tests::Fermat(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue } if tests::MillerRabin(gen).test_loop...
generate_prime
identifier_name
mod.rs
use num::{One, Integer}; use num::bigint::{BigUint, RandBigInt}; use rand::Rng; use utils::primes::tests::PrimeTest; pub mod tests; const PRIME_TEST_COUNT: usize = 20; /// Generate new prime number with given bit size via given random number generator. /// /// Currently this function give guarantee that it ever end...
if tests::MillerRabin(gen).test_loop(&int, PRIME_TEST_COUNT).is_composite() { continue } return Some(int) } }
random_line_split
detector2dview.py
sum_1 = roi_matrix.sum(1) roi_matrix = matrix[ll_col:ur_col, ll_row:ur_row] sum_0 = roi_matrix.sum(0) sum_1 = roi_matrix.sum(1) # write to file base_name = os.path.join(output_dir, 'Exp{0}_Scan{1}_Pt{2}'.format(exp_number, scan_number, pt_number)) save_to_file(base_name,...
""" set ROI to class variables :param lower_left_corner: :param upper_right_corner: :param plot: if True, then plot ROI :return: """ # check inputs assert len(lower_left_corner) == 2, 'Lower left corner row/col coordinate {0} must have 2 items.' \ ...
identifier_body
detector2dview.py
self._roiStart = None self._roiEnd = None # mouse self._mousePressed = Detector2DView.MousePress.RELEASED # mouse position and resolution self._currX = 0. self._currY = 0. self._resolutionX = 0.005 self._resolutionY = 0.005 # parent window ...
elif self._mousePressed == Detector2DView.MousePress.RIGHT: # No operation if mouse' right button is pressed pass elif self._mousePressed == Detector2DView.MousePress.LEFT: if self._roiSelectMode is True: # in ROI selection mode, update the size ...
pass
conditional_block
detector2dview.py
self._roiStart = None self._roiEnd = None # mouse self._mousePressed = Detector2DView.MousePress.RELEASED # mouse position and resolution self._currX = 0. self._currY = 0. self._resolutionX = 0.005 self._resolutionY = 0.005 # parent window ...
#roi_matrix = matrix[ll_col:ur_col, ll_row:ur_row] #sum_0 = roi_matrix.sum(0) #sum_1 = roi_matrix.sum(1) roi_matrix = matrix[ll_col:ur_col, ll_row:ur_row] sum_0 = roi_matrix.sum(0) sum_1 = roi_matrix.sum(1) # write to file base_name = os.path.join(output...
ll_row = min(self._roiStart[0], self._roiEnd[0]) ll_col = min(self._roiStart[1], self._roiEnd[1]) ur_row = max(self._roiStart[0], self._roiEnd[0]) ur_col = max(self._roiStart[1], self._roiEnd[1])
random_line_split
detector2dview.py
self._roiStart = None self._roiEnd = None # mouse self._mousePressed = Detector2DView.MousePress.RELEASED # mouse position and resolution self._currX = 0. self._currY = 0. self._resolutionX = 0.005 self._resolutionY = 0.005 # parent window ...
(self, event): """ Event handing as mouse is moving :param event: :return: """ # skip if the mouse cursor is still outside of the canvas if event.xdata is None or event.ydata is None: return # check: _currX and _currY must be specified ...
on_mouse_motion
identifier_name
SSHGEComputingElement.py
######################################################################## # $HeadURL$ # File : SSHGEComputingElement.py # Author : A.T. V.H. ######################################################################## """ Grid Engine Computing Element with remote job submission via ssh/scp and using site shared area ...
output = '%s/DIRACPilot.o%s' % ( self.batchOutput, jobStamp ) error = '%s/DIRACPilot.e%s' % ( self.batchError, jobStamp ) return S_OK( (jobStamp, host, output, error) ) #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
""" The SUN Grid Engine interfacr """ ############################################################################# def __init__( self, ceUniqueID ): """ Standard constructor. """ SSHComputingElement.__init__( self, ceUniqueID ) self.ceType = CE_NAME self.controlScript = 'sgece' self.mand...
identifier_body
SSHGEComputingElement.py
######################################################################## # $HeadURL$ # File : SSHGEComputingElement.py # Author : A.T. V.H. ######################################################################## """ Grid Engine Computing Element with remote job submission via ssh/scp and using site shared area ...
jobStamp = result['Value']['FileName'] host = result['Value']['Host'] output = '%s/DIRACPilot.o%s' % ( self.batchOutput, jobStamp ) error = '%s/DIRACPilot.e%s' % ( self.batchError, jobStamp ) return S_OK( (jobStamp, host, output, error) ) #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EO...
return result
conditional_block
SSHGEComputingElement.py
######################################################################## # $HeadURL$ # File : SSHGEComputingElement.py # Author : A.T. V.H. ######################################################################## """ Grid Engine Computing Element with remote job submission via ssh/scp and using site shared area ...
( self, ceUniqueID ): """ Standard constructor. """ SSHComputingElement.__init__( self, ceUniqueID ) self.ceType = CE_NAME self.controlScript = 'sgece' self.mandatoryParameters = MANDATORY_PARAMETERS def _getJobOutputFiles( self, jobID ): """ Get output file names for the specific CE...
__init__
identifier_name
SSHGEComputingElement.py
########################################################################
""" Grid Engine Computing Element with remote job submission via ssh/scp and using site shared area for the job proxy placement """ __RCSID__ = "092c1d9 (2011-06-02 15:20:46 +0200) atsareg <atsareg@in2p3.fr>" from DIRAC.Resources.Computing.SSHComputingElement import SSHComputingElement from DIRAC.Core.Util...
# $HeadURL$ # File : SSHGEComputingElement.py # Author : A.T. V.H. ########################################################################
random_line_split
mut_reference.rs
use clippy_utils::diagnostics::span_lint; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use std::iter; declare_clippy_lint! { /// ...
<'tcx>( cx: &LateContext<'tcx>, arguments: &[Expr<'_>], type_definition: Ty<'tcx>, name: &str, fn_kind: &str, ) { match type_definition.kind() { ty::FnDef(..) | ty::FnPtr(_) => { let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs(); for (argument...
check_arguments
identifier_name
mut_reference.rs
use clippy_utils::diagnostics::span_lint; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use std::iter; declare_clippy_lint! { /// ...
argument.span, &format!("the {} `{}` doesn't need a mutable reference", fn_kind, name), ); } }, _ => (), } } }, _ => (),...
}) => { if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind { span_lint( cx, UNNECESSARY_MUT_PASSED,
random_line_split
mut_reference.rs
use clippy_utils::diagnostics::span_lint; use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use std::iter; declare_clippy_lint! { /// ...
} } } fn check_arguments<'tcx>( cx: &LateContext<'tcx>, arguments: &[Expr<'_>], type_definition: Ty<'tcx>, name: &str, fn_kind: &str, ) { match type_definition.kind() { ty::FnDef(..) | ty::FnPtr(_) => { let parameters = type_definition.fn_sig(cx.tcx).skip_binder...
{ match e.kind { ExprKind::Call(fn_expr, arguments) => { if let ExprKind::Path(ref path) = fn_expr.kind { check_arguments( cx, arguments, cx.typeck_results().expr_ty(fn_expr), ...
identifier_body
launch.js
require.config({ baseUrl: 'vendor', waitSeconds: 10, paths: { core: '../core', lang: '../lang', root: '..' }, shim: { 'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' }, 'underscore': { exports: '_' ...
App.launchRouting(); App.sendInfo('app-launched'); //triggers info:app-ready, info:app-first-launch and info:app-version-changed //Refresh at app launch can be canceled using the 'refresh-at-app-launch' App param, //th...
{ Utils.log( 'App version : ', Stats.getVersionDiff() ); Utils.log( 'App opening count : ', Stats.getCountOpen() ); Utils.log( 'Last app opening was on ', Stats.getLastOpenDate() ); }
conditional_block
launch.js
require.config({ baseUrl: 'vendor', waitSeconds: 10, paths: { core: '../core', lang: '../lang', root: '..' }, shim: {
'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' }, 'underscore': { exports: '_' } } }); require(['root/config'],function(Config){ require.config({ paths: { theme: '../themes/'+ Config.theme } }); require(['jq...
random_line_split
covtype-2.py
import optunity
import random positive_digit = 2 name='covtype-%d' % positive_digit num_folds=5 budget = 150 npos = 500 nneg = 1000 search={'logC': [-8, 1], 'logGamma': [-8, 1]} covtype = sklearn.datasets.fetch_covtype() n = covtype.data.shape[0] positive_idx = [i for i in range(n) if covtype.target[i] == positive_digit] negative...
import numpy as np import hpolib_generator as hpo import cloudpickle as pickle import sklearn.datasets
random_line_split
generatorTasks.js
var curVersion = 'v34'; var request = require('request'); module.exports = function(grunt) { var firebaseUrl = 'webhook'; var firebaseUri = null; if(firebaseUrl) { firebaseUri = 'https://' + firebaseUrl + '.firebaseio.com/generator_version.json'; } var checkVersion = function(callback) { if(fireb...
}); grunt.registerTask('assetsAfter', 'Initialize the firebase configuration file (installer should do this as well)', function() { generator.assetsAfter(grunt); }); // Change this to optionally prompt instead of requiring a sitename grunt.registerTask('init', 'Initialize the firebase configuration file...
}); grunt.registerTask('assetsMiddle', 'Initialize the firebase configuration file (installer should do this as well)', function() { generator.assetsMiddle(grunt);
random_line_split
generatorTasks.js
var curVersion = 'v34'; var request = require('request'); module.exports = function(grunt) { var firebaseUrl = 'webhook'; var firebaseUri = null; if(firebaseUrl) { firebaseUri = 'https://' + firebaseUrl + '.firebaseio.com/generator_version.json'; } var checkVersion = function(callback) { if(fire...
}; var generator = require('../libs/generator').generator(grunt.config, grunt.log, grunt.file, root); grunt.registerTask('buildTemplates', 'Generate static files from templates directory', function() { var done = this.async(); generator.renderTemplates(done, generator.reloadFiles); }); grunt.regis...
{ request({ url: firebaseUri, json: true }, function(e, r, body) { if(body) { if(body !== curVersion) { console.log('========================================================'.red); console.log('# This site is using old Webhook code. #'.red); console.log('=...
conditional_block
user.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import db from datetime import datetime class User(db.Model): __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8mb4' } id = db.Column(db.Integer, primary_key=True, autoincrement=True) openid = db.Column(db.String(3...
sex = db.Column(db.SmallInteger, default=0, nullable=False) province = db.Column(db.String(20), nullable=True) city = db.Column(db.String(20), nullable=True) country = db.Column(db.String(20), nullable=True) headimgurl = db.Column(db.String(150), nullable=True) regtime = db.Column(db.DateTime, d...
classname = db.Column(db.String(32), nullable=True)
random_line_split
user.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import db from datetime import datetime class User(db.Model): __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8mb4' } id = db.Column(db.Integer, primary_key=True, autoincrement=True) openid = db.Column(db.String(3...
def save(self): db.session.add(self) db.session.commit() return self def update(self): db.session.commit() return self
return '<openid %r>' % self.openid
identifier_body
user.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import db from datetime import datetime class User(db.Model): __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8mb4' } id = db.Column(db.Integer, primary_key=True, autoincrement=True) openid = db.Column(db.String(3...
(self): return '<openid %r>' % self.openid def save(self): db.session.add(self) db.session.commit() return self def update(self): db.session.commit() return self
__repr__
identifier_name
helpers.py
import functools import os import sys import unittest from contextlib import contextmanager from cloudbridge.cloud.factory import CloudProviderFactory from cloudbridge.cloud.interfaces import InstanceState from cloudbridge.cloud.interfaces import TestMockHelperMixin from six import reraise def parse_bool(val): ...
if instance: instance.terminate() instance.wait_for([InstanceState.TERMINATED, InstanceState.UNKNOWN], terminal_states=[InstanceState.ERROR]) def cleanup_test_resources(instance=None, network=None, security_group=None, key_pair=None): """Cle...
def delete_test_instance(instance):
random_line_split
helpers.py
import functools import os import sys import unittest from contextlib import contextmanager from cloudbridge.cloud.factory import CloudProviderFactory from cloudbridge.cloud.interfaces import InstanceState from cloudbridge.cloud.interfaces import TestMockHelperMixin from six import reraise def parse_bool(val): ...
class ProviderTestBase(unittest.TestCase): _provider = None def setUp(self): if isinstance(self.provider, TestMockHelperMixin): self.provider.setUpMock() def tearDown(self): if isinstance(self.provider, TestMockHelperMixin): self.provider.tearDownMock() s...
"""Clean up any combination of supplied resources.""" with cleanup_action(lambda: delete_test_network(network) if network else None): with cleanup_action(lambda: key_pair.delete() if key_pair else None): with cleanup_action( lambda: ...
identifier_body
helpers.py
import functools import os import sys import unittest from contextlib import contextmanager from cloudbridge.cloud.factory import CloudProviderFactory from cloudbridge.cloud.interfaces import InstanceState from cloudbridge.cloud.interfaces import TestMockHelperMixin from six import reraise def parse_bool(val): ...
(): return os.path.join(os.path.dirname(__file__), 'fixtures/') def delete_test_instance(instance): if instance: instance.terminate() instance.wait_for([InstanceState.TERMINATED, InstanceState.UNKNOWN], terminal_states=[InstanceState.ERROR]) def cleanup_test_resourc...
get_test_fixtures_folder
identifier_name
helpers.py
import functools import os import sys import unittest from contextlib import contextmanager from cloudbridge.cloud.factory import CloudProviderFactory from cloudbridge.cloud.interfaces import InstanceState from cloudbridge.cloud.interfaces import TestMockHelperMixin from six import reraise def parse_bool(val): ...
@contextmanager def cleanup_action(cleanup_func): """ Context manager to carry out a given cleanup action after carrying out a set of tasks, or when an exception occurs. If any errors occur during the cleanup action, those are ignored, and the original traceback is preserved. :params...
return False
conditional_block
split.js
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function execute (url, swagger) { var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags) { ...
return deferred.promise; } }) .run(function (plugins, split) { plugins.add(plugins.BEFORE_PARSE, split); });
}); } deferred.resolve(true);
random_line_split
split.js
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function execute (url, swagger)
swagger.tags.push({name: tag}); }); } deferred.resolve(true); return deferred.promise; } }) .run(function (plugins, split) { plugins.add(plugins.BEFORE_PARSE, split); });
{ var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags) { var tags = {}; angular.forEach(swagger.paths, function (path, key) { var t = key.replace(/^\/?([^\/]+).*$/g, '$1'); tags[t] = true; ...
identifier_body
split.js
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function
(url, swagger) { var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags) { var tags = {}; angular.forEach(swagger.paths, function (path, key) { var t = key.replace(/^\/?([^\/]+).*$/g, '$1'); tags[t] = ...
execute
identifier_name
split.js
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function execute (url, swagger) { var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags)
deferred.resolve(true); return deferred.promise; } }) .run(function (plugins, split) { plugins.add(plugins.BEFORE_PARSE, split); });
{ var tags = {}; angular.forEach(swagger.paths, function (path, key) { var t = key.replace(/^\/?([^\/]+).*$/g, '$1'); tags[t] = true; angular.forEach(path, function (method) { if (!method.tags || !metho...
conditional_block
cfalertdialog-helper.ts
import { alert } from "tns-core-modules/ui/dialogs"; import { CFAlertDialog, DialogOptions, CFAlertActionAlignment, CFAlertActionStyle, CFAlertStyle } from "nativescript-cfalert-dialog"; export class CFAlertDialogHelper { private cfalertDialog: CFAlertDialog; constructor() { this.cfalertDialog = new...
(blur: boolean): void { this.cfalertDialog.show({ dialogStyle: CFAlertStyle.ALERT, title: "Alert! Run 4 your life! 😱", backgroundBlur: blur, onDismiss: () => console.log("showAlert dismissed") }); } showNotification(): void { const options: DialogOptions = { dialogStyle: ...
showAlert
identifier_name
cfalertdialog-helper.ts
import { alert } from "tns-core-modules/ui/dialogs"; import { CFAlertDialog, DialogOptions, CFAlertActionAlignment, CFAlertActionStyle, CFAlertStyle } from "nativescript-cfalert-dialog"; export class CFAlertDialogHelper { private cfalertDialog: CFAlertDialog; constructor() { this.cfalertDialog = new...
showBottomSheet(): void { const onSelection = response => { alert({ title: "Your selection:", message: response, okButtonText: "OK" }); }; const options: DialogOptions = { dialogStyle: CFAlertStyle.BOTTOM_SHEET, title: "This is a bottom sheet!", messag...
const options: DialogOptions = { dialogStyle: CFAlertStyle.NOTIFICATION, title: "This is a notification!", message: "It is shown at the top of the screen, and the background is blurry (on iOS).", backgroundBlur: true, onDismiss: dialog => console.log(`Dialog was dismissed: ${dialog}`), ...
identifier_body
cfalertdialog-helper.ts
import { alert } from "tns-core-modules/ui/dialogs"; import { CFAlertDialog, DialogOptions, CFAlertActionAlignment, CFAlertActionStyle, CFAlertStyle } from "nativescript-cfalert-dialog"; export class CFAlertDialogHelper { private cfalertDialog: CFAlertDialog; constructor() { this.cfalertDialog = new...
const items: any = ["Tomato", "Potato", "Carrot", "Spinach"]; const options: DialogOptions = { dialogStyle: CFAlertStyle.ALERT, title: "This is a simple list!", simpleList: { items: items, onClick: (dialogInterface, index) => { alert({ title: "Your selecti...
}; this.cfalertDialog.show(options); } showSimpleList(): void {
random_line_split
browser.js
/** * Cloud Browser basic navigation support. */ var CloudBrowser = { /** Submit the "next" page results form. */ submitForm: function (formId) { document.getElementById(formId).submit(); return false; }, /** Return key pressed */ enterPressed: function (event) { var key = ...
() { var title = document.getElementById('diff_float').title; document.getElementById('diff_form_file').value = title; document.getElementById("diff_form").submit(); return false; }
submitDiffForm
identifier_name
browser.js
/** * Cloud Browser basic navigation support. */ var CloudBrowser = { /** Submit the "next" page results form. */ submitForm: function (formId) { document.getElementById(formId).submit(); return false; }, /** Return key pressed */ enterPressed: function (event) { var key = ...
} return paramStr !== '' ? [uri, paramStr].join('?') : uri; }, /** Set query parameters. */ setQueryParam: function (query, key, value) { var queryObj = CloudBrowser.getQueryObj(query); queryObj.params[key] = value; return CloudBrowser.toQueryString(queryObj); }...
{ var value = params[key]; // Yes, I know this is inefficient. paramStr += key + '=' + value; }
conditional_block
browser.js
/** * Cloud Browser basic navigation support. */ var CloudBrowser = { /** Submit the "next" page results form. */ submitForm: function (formId) { document.getElementById(formId).submit(); return false; }, /** Return key pressed */ enterPressed: function (event) { var key = ...
} } return { 'uri': uri, 'params': params }; }, /** Convert parameter object to string. */ toQueryString: function (queryObj) { var uri = queryObj.uri; var params = queryObj.params || {}; var paramStr = ''; for (va...
random_line_split
browser.js
/** * Cloud Browser basic navigation support. */ var CloudBrowser = { /** Submit the "next" page results form. */ submitForm: function (formId) { document.getElementById(formId).submit(); return false; }, /** Return key pressed */ enterPressed: function (event) { var key = ...
{ var title = document.getElementById('diff_float').title; document.getElementById('diff_form_file').value = title; document.getElementById("diff_form").submit(); return false; }
identifier_body
belt_interpreter_node.py
#!/usr/bin/env python import rospy from belt_parser import BeltParser import tf import tf2_ros import math import copy from memory_definitions.srv import GetDefinition from processing_belt_interpreter.msg import * from drivers_ard_others.msg import BeltRange from geometry_msgs.msg import Pose2D, TransformStamped, Poi...
(self): super(BeltInterpreter, self).__init__() rospy.init_node("belt_interpreter") rospy.loginfo("Belt interpreter is initializing...") # template for the sensor frame id, with '{}' being the sensor id self.SENSOR_FRAME_ID = "belt_{}" self.DEF_FILE = "processing/belt....
__init__
identifier_name
belt_interpreter_node.py
#!/usr/bin/env python import rospy from belt_parser import BeltParser import tf import tf2_ros import math import copy from memory_definitions.srv import GetDefinition from processing_belt_interpreter.msg import * from drivers_ard_others.msg import BeltRange from geometry_msgs.msg import Pose2D, TransformStamped, Poi...
self.process_range(data) if data.sensor_id != 'sensor_tera1' and not publish_now: if self._watchdog: self._watchdog.shutdown() self._watchdog = rospy.Timer(self.WATCHDOG_PERIOD_BELT, self.publish, oneshot=True) elif publish_now: self.publish(N...
random_line_split
belt_interpreter_node.py
#!/usr/bin/env python import rospy from belt_parser import BeltParser import tf import tf2_ros import math import copy from memory_definitions.srv import GetDefinition from processing_belt_interpreter.msg import * from drivers_ard_others.msg import BeltRange from geometry_msgs.msg import Pose2D, TransformStamped, Poi...
self._watchdog = rospy.Timer(self.WATCHDOG_PERIOD_TERA, self.publish, oneshot=True) if len(self._current_rects) > 0: self._previous_rects.append(copy.deepcopy(self._current_rects)) self._previous_statuses.append(copy.deepcopy(self._current_statuses)) ...
self._watchdog.shutdown()
conditional_block
belt_interpreter_node.py
#!/usr/bin/env python import rospy from belt_parser import BeltParser import tf import tf2_ros import math import copy from memory_definitions.srv import GetDefinition from processing_belt_interpreter.msg import * from drivers_ard_others.msg import BeltRange from geometry_msgs.msg import Pose2D, TransformStamped, Poi...
if __name__ == '__main__': b = BeltInterpreter()
get_def = rospy.ServiceProxy('/memory/definitions/get', GetDefinition) get_def.wait_for_service() try: res = get_def(self.DEF_FILE) if not res.success: msg = "Can't fetch belt definition file. Shutting down." rospy.logfatal(msg) r...
identifier_body
index.ts
import * as t from 'flow-runtime'; const voidType = t.void; const typeOf = t.typeOf; t.undef = () => { return voidType.bind(t)(); } t.nostrict = (...args: any[]) => { return t.union(...args, t.null(), t.undef()); } t.void = () => { return t.union(t.null(), t.undef()); } t.n = (...args: any[]) => { return t...
} export const lib = t; export default t; // const map: Map<string, any> = new Map(); // const intersect = t.intersect; // const declare = t.declare; // const ref = t.ref; // const decorate = t.decorate; // t.decorate = (type: any, shouldAssert?: boolean) => { // return (input: any, propertyName: any, descriptor: a...
random_line_split
index.ts
import * as t from 'flow-runtime'; const voidType = t.void; const typeOf = t.typeOf; t.undef = () => { return voidType.bind(t)(); } t.nostrict = (...args: any[]) => { return t.union(...args, t.null(), t.undef()); } t.void = () => { return t.union(t.null(), t.undef()); } t.n = (...args: any[]) => { return t...
return input; } } return typeOf.bind(t)(input); } export const lib = t; export default t; // const map: Map<string, any> = new Map(); // const intersect = t.intersect; // const declare = t.declare; // const ref = t.ref; // const decorate = t.decorate; // t.decorate = (type: any, shouldAssert?: boolea...
{ return t.Class(input); }
conditional_block
utils.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeStaticFileCache = makeStaticFileCache; var _caching = require("../caching"); var fs = _interopRequireWildcard(require("../../gensync-utils/fs")); function _fs2()
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(...
{ const data = _interopRequireDefault(require("fs")); _fs2 = function () { return data; }; return data; }
identifier_body
utils.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeStaticFileCache = makeStaticFileCache; var _caching = require("../caching"); var fs = _interopRequireWildcard(require("../../gensync-utils/fs")); function _fs2() { const data = _interopRequireDefault(require("fs")); _fs2...
} function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard...
return data;
random_line_split
utils.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeStaticFileCache = makeStaticFileCache; var _caching = require("../caching"); var fs = _interopRequireWildcard(require("../../gensync-utils/fs")); function _fs2() { const data = _interopRequireDefault(require("fs")); _fs2...
(filepath) { try { return +_fs2().default.statSync(filepath).mtime; } catch (e) { if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; } return null; }
fileMtime
identifier_name
utils.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeStaticFileCache = makeStaticFileCache; var _caching = require("../caching"); var fs = _interopRequireWildcard(require("../../gensync-utils/fs")); function _fs2() { const data = _interopRequireDefault(require("fs")); _fs2...
return newObj; } function makeStaticFileCache(fn) { return (0, _caching.makeStrongCache)(function* (filepath, cache) { const cached = cache.invalidate(() => fileMtime(filepath)); if (cached === null) { cache.forever(); return null; } return fn(filepath, yield* fs.readFile(filepath, "ut...
{ cache.set(obj, newObj); }
conditional_block
add_retag.rs
//! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate. //! It has to be run really early, before transformations like inlining, because //! introducing these calls *adds* UB -- so, conceptually, this pass is actually part //! of MIR building, and only after this pass we think of the program...
} } impl<'tcx> MirPass<'tcx> for AddRetag { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { if !tcx.sess.opts.debugging_opts.mir_emit_retag { return; } // We need an `AllCallEdges` pass before we can do any work. super::add_call_guards::AllCallEdges....
{ match ty.kind() { // Primitive types that are not references ty::Bool | ty::Char | ty::Float(_) | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Str | ty::FnDef(..) | ty::Never => false, // References ...
identifier_body
add_retag.rs
//! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate. //! It has to be run really early, before transformations like inlining, because //! introducing these calls *adds* UB -- so, conceptually, this pass is actually part //! of MIR building, and only after this pass we think of the program...
// FIXME: Consider using just the span covering the function // argument declaration. let source_info = SourceInfo::outermost(span); // Gather all arguments, skip return value. let places = local_decls .iter_enumerated() .skip(1...
// PART 1 // Retag arguments at the beginning of the start block. {
random_line_split
add_retag.rs
//! This pass adds validation calls (AcquireValid, ReleaseValid) where appropriate. //! It has to be run really early, before transformations like inlining, because //! introducing these calls *adds* UB -- so, conceptually, this pass is actually part //! of MIR building, and only after this pass we think of the program...
(ty: Ty<'tcx>) -> bool { match ty.kind() { // Primitive types that are not references ty::Bool | ty::Char | ty::Float(_) | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Str | ty::FnDef(..) | ty::Never => false,...
may_be_reference
identifier_name
init.py
from __init__ import * import sys import os.path from PIL import Image import numpy as np from arg_parser import parse_args from printer import print_header, print_usage, print_line sys.path.insert(0, ROOT) from utils import * def init_images(app_data): print("[init.py] : initializing images...") app_args ...
pipe_data = {} app_data['pipe_data'] = pipe_data get_input(app_data) init_images(app_data) return
identifier_body
init.py
from __init__ import * import sys import os.path from PIL import Image import numpy as np from arg_parser import parse_args from printer import print_header, print_usage, print_line sys.path.insert(0, ROOT) from utils import * def init_images(app_data): print("[init.py] : initializing images...") app_args ...
pipe_data = {} app_data['pipe_data'] = pipe_data get_input(app_data) init_images(app_data) return
def init_all(app_data):
random_line_split
init.py
from __init__ import * import sys import os.path from PIL import Image import numpy as np from arg_parser import parse_args from printer import print_header, print_usage, print_line sys.path.insert(0, ROOT) from utils import * def init_images(app_data): print("[init.py] : initializing images...") app_args ...
R = img1.shape[0] C = img1.shape[1] off_left = 31 total_pad = 60 # convert input image to floating point image1_f = np.float32(img1) / 255.0 image2_f = np.float32(img2) / 255.0 # create ghost zone and copy image roi # Image 1: image1_ghost = np.empty((rows+total_pad, cols+...
app_data['error'] = 1 return
conditional_block
init.py
from __init__ import * import sys import os.path from PIL import Image import numpy as np from arg_parser import parse_args from printer import print_header, print_usage, print_line sys.path.insert(0, ROOT) from utils import * def init_images(app_data): print("[init.py] : initializing images...") app_args ...
(app_data): # parse the command-line arguments app_args = parse_args() app_data['app_args'] = app_args app_data['mode'] = app_args.mode app_data['runs'] = int(app_args.runs) app_data['graph_gen'] = bool(app_args.graph_gen) app_data['timer'] = app_args.timer # storage optimization a...
get_input
identifier_name
rename.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::Cow; use std::str::FromStr; /// The type of identifier to be renamed. #[derive(Debug, Clone, Cop...
/// Applies the rename rule to a string pub fn apply<'a>(self, text: &'a str, context: IdentifierType) -> Cow<'a, str> { use heck::*; if text.is_empty() { return Cow::Borrowed(text); } Cow::Owned(match self { RenameRule::None => return Cow::Borrowed(te...
{ match self { RenameRule::None => None, other => Some(other), } }
identifier_body
rename.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::Cow; use std::str::FromStr; /// The type of identifier to be renamed. #[derive(Debug, Clone, Cop...
(s: &str) -> Result<RenameRule, Self::Err> { match s { "none" => Ok(RenameRule::None), "None" => Ok(RenameRule::None), "mGeckoCase" => Ok(RenameRule::GeckoCase), "GeckoCase" => Ok(RenameRule::GeckoCase), "gecko_case" => Ok(RenameRule::GeckoCase), ...
from_str
identifier_name
rename.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::borrow::Cow; use std::str::FromStr; /// The type of identifier to be renamed. #[derive(Debug, Clone, Cop...
pub(crate) fn not_none(self) -> Option<Self> { match self { RenameRule::None => None, other => Some(other), } } /// Applies the rename rule to a string pub fn apply<'a>(self, text: &'a str, context: IdentifierType) -> Cow<'a, str> { use heck::*; ...
impl RenameRule {
random_line_split
iplookup.py
"""This will perform basic enrichment on a given IP.""" import csv import json import mmap import os import socket import urllib import dns.resolver import dns.reversename from geoip import geolite2 from IPy import IP from joblib import Parallel, delayed from netaddr import AddrFormatError, IPSet torcsv = 'Tor_ip_li...
(lookupvar): """Do a single IP lookup.""" result = mainlookup(lookupvar) return result def csvout(inputdict): """Generate a CSV file from the output inputdict.""" fhandle = open(OUTFILE, "a") # header = 0 # if header == 0: # fhandle.write("Boop") # header = 1 try: ...
single
identifier_name
iplookup.py
"""This will perform basic enrichment on a given IP.""" import csv import json import mmap import os import socket import urllib import dns.resolver import dns.reversename from geoip import geolite2 from IPy import IP from joblib import Parallel, delayed from netaddr import AddrFormatError, IPSet torcsv = 'Tor_ip_li...
def iprange(sample, sub): """Identify if the given ip address is in the previous range.""" if sub is not 0: try: ipset = IPSet([sub]) if sample in ipset: return True except AddrFormatError: return False else: return False def m...
"""Look up a value in a file.""" try: fhandle = open(fname) except IOError: sourceFile = urllib.URLopener() sourceFile.retrieve( sfile, fname) fhandle = open(fname) search = mmap.mmap(fhandle.fileno(), 0, access=mmap.ACCESS_READ) if search.find(val...
identifier_body
iplookup.py
"""This will perform basic enrichment on a given IP.""" import csv import json import mmap import os import socket import urllib import dns.resolver import dns.reversename from geoip import geolite2 from IPy import IP from joblib import Parallel, delayed from netaddr import AddrFormatError, IPSet torcsv = 'Tor_ip_li...
"""Generate a CSV file from the output inputdict.""" fhandle = open(OUTFILE, "a") # header = 0 # if header == 0: # fhandle.write("Boop") # header = 1 try: writer = csv.writer(fhandle, quoting=csv.QUOTE_ALL) writer.writerow(( inputdict['ip-address'], ...
def csvout(inputdict):
random_line_split
iplookup.py
"""This will perform basic enrichment on a given IP.""" import csv import json import mmap import os import socket import urllib import dns.resolver import dns.reversename from geoip import geolite2 from IPy import IP from joblib import Parallel, delayed from netaddr import AddrFormatError, IPSet torcsv = 'Tor_ip_li...
main()
conditional_block
agent-jvm-heap-chart-container.ts
import { PrimitiveArray, Data } from 'billboard.js'; import { Observable } from 'rxjs'; import { IInspectorChartContainer } from './inspector-chart-container-factory'; import { makeYData, makeXData, getMaxTickValue } from 'app/core/utils/chart-util'; import { IInspectorChartData, InspectorChartDataService } from './in...
getTooltipFormat(v: number, columnId: string, i: number): string { return columnId === 'fgcTime' ? `${v}ms ${this.fgcCount[i] > 1 ? '(' + this.fgcCount[i] + ')' : ''}` : this.convertWithUnit(v); } }
{ const unitList = ['', 'K', 'M', 'G']; return [...unitList].reduce((acc: string, curr: string, i: number, arr: string[]) => { const v = Number(acc); return v >= 1000 ? (v / 1000).toString() : (arr.splice(i + 1), Number.isInteger(v) ? `${v}${curr...
identifier_body
agent-jvm-heap-chart-container.ts
import { PrimitiveArray, Data } from 'billboard.js'; import { Observable } from 'rxjs'; import { IInspectorChartContainer } from './inspector-chart-container-factory'; import { makeYData, makeXData, getMaxTickValue } from 'app/core/utils/chart-util'; import { IInspectorChartData, InspectorChartDataService } from './in...
(value: number): string { const unitList = ['', 'K', 'M', 'G']; return [...unitList].reduce((acc: string, curr: string, i: number, arr: string[]) => { const v = Number(acc); return v >= 1000 ? (v / 1000).toString() : (arr.splice(i + 1), Number.is...
convertWithUnit
identifier_name
agent-jvm-heap-chart-container.ts
import { PrimitiveArray, Data } from 'billboard.js'; import { Observable } from 'rxjs'; import { IInspectorChartContainer } from './inspector-chart-container-factory'; import { makeYData, makeXData, getMaxTickValue } from 'app/core/utils/chart-util'; import { IInspectorChartData, InspectorChartDataService } from './in...
}, min: 0, max: (() => { const maxTickValue = getMaxTickValue(data, 1, 3); return maxTickValue === 0 ? this.defaultYMax : maxTickValue; })(), default: [0, this.defaultYMax] }, ...
format: (v: number): string => this.convertWithUnit(v) }, padding: { top: 0, bottom: 0
random_line_split
agent-jvm-heap-chart-container.ts
import { PrimitiveArray, Data } from 'billboard.js'; import { Observable } from 'rxjs'; import { IInspectorChartContainer } from './inspector-chart-container-factory'; import { makeYData, makeXData, getMaxTickValue } from 'app/core/utils/chart-util'; import { IInspectorChartData, InspectorChartDataService } from './in...
if (t > 0) { totalSumGCTime += t; } return gcOldCount[i] > 0 ? totalSumGCTime : null; }); return [ ['x', ...makeXData(charts.x)], ['max', ...makeYData(charts.y['JVM_MEMORY_HEAP_MAX'], 1)], ['used', ...makeYData(c...
{ totalSumGCTime = 0; }
conditional_block
omd_livestatus.py
. Inspired by the DigitalOcean inventory script: https://github.com/ansible/ansible/blob/devel/contrib/inventory/digital_ocean.py :author: Andreas Härpfer <andreas.haerpfer@consol.de> """ from __future__ import print_function __version__ = '0.2' import datetime import os import sys import optparse ...
def host(self, name, indent=None, sort_keys=False): """Return hostvars for a single host as JSON.""" if name in self.inventory['_meta']['hostvars']: return(json.dumps( self.inventory['_meta']['hostvars'][name], indent=indent, sort_keys=sor...
""Return full inventory data as JSON.""" return json.dumps(self.inventory, indent=indent, sort_keys=sort_keys)
identifier_body
omd_livestatus.py
socket. Inspired by the DigitalOcean inventory script: https://github.com/ansible/ansible/blob/devel/contrib/inventory/digital_ocean.py :author: Andreas Härpfer <andreas.haerpfer@consol.de> """ from __future__ import print_function __version__ = '0.2' import datetime import os import sys import optparse ...
self): """Read data from remote Livestatus socket via SSH. Assumes non-interactive (e.g. via ssh-agent) access to the remote host. The `unixcat` command (part of Livestatus) has to be available via $PATH at the remote end. """ l = self.location.split(':', 1) l....
read_from_ssh(
identifier_name
omd_livestatus.py
socket. Inspired by the DigitalOcean inventory script: https://github.com/ansible/ansible/blob/devel/contrib/inventory/digital_ocean.py :author: Andreas Härpfer <andreas.haerpfer@consol.de> """ from __future__ import print_function __version__ = '0.2' import datetime import os import sys import optparse ...
out.append('{0}\t{1}'.format(host, ' '.join(hostvars))) return '\n'.join(out) def _save_method(option, opt_str, value, parser): parser.values.method = opt_str.lstrip('-') parser.values.location = value def parse_arguments(): """Parse command line arguments.""" parser = optpar...
ostvars.append('{0}="{1}"'.format(varname, vars[varname]))
conditional_block
omd_livestatus.py
socket. Inspired by the DigitalOcean inventory script: https://github.com/ansible/ansible/blob/devel/contrib/inventory/digital_ocean.py :author: Andreas Härpfer <andreas.haerpfer@consol.de> """ from __future__ import print_function __version__ = '0.2' import datetime import os import sys import optparse ...
out.append('{0}\t{1}'.format(host, ' '.join(hostvars))) return '\n'.join(out) def _save_method(option, opt_str, value, parser): parser.values.method = opt_str.lstrip('-') parser.values.location = value def parse_arguments(): """Parse command line arguments.""" parser = optpar...
hostvars = [] for varname in vars.keys(): hostvars.append('{0}="{1}"'.format(varname, vars[varname]))
random_line_split
allowedaddresspairs.py
# Copyright 2013 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
(cfg=cfg.CONF): cfg.register_opts(allowed_address_pair_opts)
register_allowed_address_pair_opts
identifier_name
allowedaddresspairs.py
# Copyright 2013 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
def register_allowed_address_pair_opts(cfg=cfg.CONF): cfg.register_opts(allowed_address_pair_opts)
random_line_split
allowedaddresspairs.py
# Copyright 2013 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
cfg.register_opts(allowed_address_pair_opts)
identifier_body
test_zendesk.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
side_loading=True) assert results == {'groups': [], 'users': [], 'tickets': []}
zendesk_hook.get_conn = mock.Mock(return_value=mock_conn) results = zendesk_hook.call(".../tickets.json", query={"include": "users,groups"}, get_all_pages=False,
random_line_split
test_zendesk.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
@mock.patch("airflow.providers.zendesk.hooks.zendesk.Zendesk") def test_returns_single_page_if_get_all_pages_false(self, _): zendesk_hook = ZendeskHook("conn_id") mock_connection = mock.Mock() mock_connection.host = "some_host" zendesk_hook.get_connection = mock.Mock(return_val...
sleep_time = 10 # To break out of the otherwise infinite tries mocked_time.sleep = mock.Mock(side_effect=ValueError, return_value=3) conn_mock = mock.Mock() mock_response = mock.Mock() mock_response.headers.get.return_value = sleep_time conn_mock.call = mock.Mock( ...
identifier_body
test_zendesk.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
(unittest.TestCase): @mock.patch("airflow.providers.zendesk.hooks.zendesk.time") def test_sleeps_for_correct_interval(self, mocked_time): sleep_time = 10 # To break out of the otherwise infinite tries mocked_time.sleep = mock.Mock(side_effect=ValueError, return_value=3) conn_moc...
TestZendeskHook
identifier_name
main.rs
fn can_spell(w: &str, blocks: &Vec<&str>) -> bool { fn solve(chars: Vec<char>, avail_blocks: &Vec<&str>) -> bool { if chars.is_empty() { true } else if avail_blocks.is_empty() { false } else { let pos = avail_blocks.iter().position(|&b| b.chars().any(|c| c...
"TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]; for w in words.iter() { println!("Can I spell {}: {}", w, can_spell(w, &blocks)); } }
random_line_split
main.rs
fn can_spell(w: &str, blocks: &Vec<&str>) -> bool
} } } solve(w.chars().collect(), blocks) } fn main() { let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]; let blocks = vec!["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", ...
{ fn solve(chars: Vec<char>, avail_blocks: &Vec<&str>) -> bool { if chars.is_empty() { true } else if avail_blocks.is_empty() { false } else { let pos = avail_blocks.iter().position(|&b| b.chars().any(|c| c == chars[0])); match pos { ...
identifier_body
main.rs
fn can_spell(w: &str, blocks: &Vec<&str>) -> bool { fn
(chars: Vec<char>, avail_blocks: &Vec<&str>) -> bool { if chars.is_empty() { true } else if avail_blocks.is_empty() { false } else { let pos = avail_blocks.iter().position(|&b| b.chars().any(|c| c == chars[0])); match pos { Some(n)...
solve
identifier_name
read_test.py
from tests.api import auth_for from tests.data import add_fixtures, clubs, users def test_lva(db_session, client): lva = clubs.lva(owner=users.john()) add_fixtures(db_session, lva) res = client.get("/clubs/{id}".format(id=lva.id)) assert res.status_code == 200 assert res.json == { "id": l...
res = client.get("/clubs/{id}".format(id=lva.id), headers=auth_for(john)) assert res.status_code == 200 assert res.json == { "id": lva.id, "name": "LV Aachen", "timeCreated": "2015-12-24T12:34:56+00:00", "website": "http://www.lv-aachen.de", "isWritable": True, ...
def test_writable(db_session, client): lva = clubs.lva() john = users.john(club=lva) add_fixtures(db_session, lva, john)
random_line_split
read_test.py
from tests.api import auth_for from tests.data import add_fixtures, clubs, users def test_lva(db_session, client): lva = clubs.lva(owner=users.john()) add_fixtures(db_session, lva) res = client.get("/clubs/{id}".format(id=lva.id)) assert res.status_code == 200 assert res.json == { "id": l...
def test_missing(client): res = client.get("/clubs/10000000") assert res.status_code == 404 def test_invalid_id(client): res = client.get("/clubs/abc") assert res.status_code == 404
lva = clubs.lva() john = users.john(club=lva) add_fixtures(db_session, lva, john) res = client.get("/clubs/{id}".format(id=lva.id), headers=auth_for(john)) assert res.status_code == 200 assert res.json == { "id": lva.id, "name": "LV Aachen", "timeCreated": "2015-12-24T12:34:...
identifier_body
read_test.py
from tests.api import auth_for from tests.data import add_fixtures, clubs, users def test_lva(db_session, client): lva = clubs.lva(owner=users.john()) add_fixtures(db_session, lva) res = client.get("/clubs/{id}".format(id=lva.id)) assert res.status_code == 200 assert res.json == { "id": l...
(db_session, client): sfn = clubs.sfn() add_fixtures(db_session, sfn) res = client.get("/clubs/{id}".format(id=sfn.id)) assert res.status_code == 200 assert res.json == { u"id": sfn.id, u"name": u"Sportflug Niederberg", u"timeCreated": "2017-01-01T12:34:56+00:00", u"...
test_sfn
identifier_name
union-fields-2.rs
// revisions: mirunsafeck thirunsafeck // [thirunsafeck]compile-flags: -Z thir-unsafeck union U { a: u8, b: u16, } fn main() { let u = U {}; //~ ERROR union expressions should have exactly one field let u = U { a: 0 }; // OK let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly...
let U { a, b } = u; //~ ERROR union patterns should have exactly one field let U { a, b, c } = u; //~ ERROR union patterns should have exactly one field //~^ ERROR union `U` does not have a field named `c` let U { .. } = u; //~ ERROR union patterns should have exactly one field ...
let u = U { ..u }; //~ ERROR union expressions should have exactly one field //~^ ERROR functional record update syntax requires a struct let U {} = u; //~ ERROR union patterns should have exactly one field let U { a } = u; // OK
random_line_split
union-fields-2.rs
// revisions: mirunsafeck thirunsafeck // [thirunsafeck]compile-flags: -Z thir-unsafeck union U { a: u8, b: u16, } fn main()
{ let u = U {}; //~ ERROR union expressions should have exactly one field let u = U { a: 0 }; // OK let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly one field let u = U { a: 0, b: 1, c: 2 }; //~ ERROR union expressions should have exactly one field ...
identifier_body
union-fields-2.rs
// revisions: mirunsafeck thirunsafeck // [thirunsafeck]compile-flags: -Z thir-unsafeck union U { a: u8, b: u16, } fn
() { let u = U {}; //~ ERROR union expressions should have exactly one field let u = U { a: 0 }; // OK let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly one field let u = U { a: 0, b: 1, c: 2 }; //~ ERROR union expressions should have exactly one field ...
main
identifier_name
people.edit.route.ts
import { Component, OnInit, OnDestroy } from 'angular2/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; import { RouteParams } from '@ngrx/router'; import { Store } from '@ngrx/store'; // interfaces import { IPerson } ...
implements OnInit, OnDestroy { public person$: Observable<IPerson> = this._params.pluck('id') .mergeMap(id => this._store.let(getOne$(id))) // dom event streams public onPatch$ = new Subject<any>(); // action streams public queryIdSetAction$ = this._params.pluck('id').map(one()); public patchAction$ ...
PeopleEditRoute
identifier_name
people.edit.route.ts
import { Component, OnInit, OnDestroy } from 'angular2/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; import { RouteParams } from '@ngrx/router'; import { Store } from '@ngrx/store'; // interfaces import { IPerson } ...
ngOnInit() { this._subscription = Observable .merge( this.queryIdSetAction$, this.patchAction$ ) .subscribe(this._store); } ngOnDestroy() { this._subscription.unsubscribe(); } }
{}
identifier_body
people.edit.route.ts
import { Component, OnInit, OnDestroy } from 'angular2/core'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; import { RouteParams } from '@ngrx/router'; import { Store } from '@ngrx/store'; // interfaces import { IPerson } ...
// dom event streams public onPatch$ = new Subject<any>(); // action streams public queryIdSetAction$ = this._params.pluck('id').map(one()); public patchAction$ = this.onPatch$ .mergeMap( id => this._params.pluck('id'), (data, id) => ({ id: id, data: data }) ) .m...
random_line_split
employe-autocomplete.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { CommonModule, APP_BASE_HREF } from '@angular/common'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { UsedMaterialModule } from '...
it('should be created', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('Filter infSurname', () => { let filteredEmp: Employe[]; let employeId: number; component.filteredEmployes.subscribe(e => { filteredEmp = e; employeId = filteredEmp[0].id; }); ...
component.employesSubject = ApplicationSharedData.getInstance().getEmployes(); component.injectSearch = ApplicationSharedData.getInstance().getEmpAutoCompInjectSearch(); component.employesSubject.next(employess); fixture.detectChanges(); });
random_line_split
papers.py
from django import template import randomcolor register = template.Library() CATEGORY_NAMES = { 'cs.AI': 'Artificial Intelligence', 'cs.CL': 'Computation and Language', 'cs.CC': 'Computational Complexity', 'cs.CE': 'Computational Engineering', 'cs.CG': 'Computational Geometry', 'cs.GT': 'Game ...
(category): if category not in CATEGORY_NAMES: return {} return { 'category': category, 'name': CATEGORY_NAMES[category], 'color': randomcolor.RandomColor(category).generate(luminosity='dark')[0], }
category_badge
identifier_name
papers.py
from django import template import randomcolor register = template.Library() CATEGORY_NAMES = { 'cs.AI': 'Artificial Intelligence', 'cs.CL': 'Computation and Language', 'cs.CC': 'Computational Complexity', 'cs.CE': 'Computational Engineering', 'cs.CG': 'Computational Geometry', 'cs.GT': 'Game ...
if category not in CATEGORY_NAMES: return {} return { 'category': category, 'name': CATEGORY_NAMES[category], 'color': randomcolor.RandomColor(category).generate(luminosity='dark')[0], }
identifier_body
papers.py
from django import template import randomcolor register = template.Library() CATEGORY_NAMES = { 'cs.AI': 'Artificial Intelligence', 'cs.CL': 'Computation and Language', 'cs.CC': 'Computational Complexity',
'cs.CV': 'Computer Vision', 'cs.CY': 'Computers and Society', 'cs.CR': 'Cryptography and Security', 'cs.DS': 'Data Structures and Algorithms', 'cs.DB': 'Databases', 'cs.DL': 'Digital Libraries', 'cs.DM': 'Discrete Mathematics', 'cs.DC': 'Distributed Computing', 'cs.ET': 'Emerging Tec...
'cs.CE': 'Computational Engineering', 'cs.CG': 'Computational Geometry', 'cs.GT': 'Game Theory',
random_line_split
papers.py
from django import template import randomcolor register = template.Library() CATEGORY_NAMES = { 'cs.AI': 'Artificial Intelligence', 'cs.CL': 'Computation and Language', 'cs.CC': 'Computational Complexity', 'cs.CE': 'Computational Engineering', 'cs.CG': 'Computational Geometry', 'cs.GT': 'Game ...
return { 'category': category, 'name': CATEGORY_NAMES[category], 'color': randomcolor.RandomColor(category).generate(luminosity='dark')[0], }
return {}
conditional_block