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
proptest_types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_address::AccountAddress, identifier::Identifier, language_storage::{StructTag, TypeTag}, transaction_argument::TransactionArgument, }; use proptest::{collection::vec, prelude::*}; impl Arbitrary for ...
) .prop_map(|(address, module, name, type_params)| { Struct(StructTag { address, module, name, type_params, }) ...
{ use TypeTag::*; let leaf = prop_oneof![ Just(Bool), Just(U8), Just(U64), Just(U128), Just(Address), Just(Vector(Box::new(Bool))), ]; leaf.prop_recursive( 8, // levels deep 16, // max size ...
identifier_body
proptest_types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_address::AccountAddress, identifier::Identifier, language_storage::{StructTag, TypeTag}, transaction_argument::TransactionArgument, }; use proptest::{collection::vec, prelude::*}; impl Arbitrary for ...
(_args: Self::Parameters) -> Self::Strategy { use TypeTag::*; let leaf = prop_oneof![ Just(Bool), Just(U8), Just(U64), Just(U128), Just(Address), Just(Vector(Box::new(Bool))), ]; leaf.prop_recursive( 8, ...
arbitrary_with
identifier_name
proptest_types.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_address::AccountAddress, identifier::Identifier, language_storage::{StructTag, TypeTag}, transaction_argument::TransactionArgument, }; use proptest::{collection::vec, prelude::*}; impl Arbitrary for ...
}) }) }, ) .boxed() } } impl Arbitrary for TransactionArgument { type Parameters = (); fn arbitrary_with(_args: ()) -> Self::Strategy { prop_oneof![ any::<bool>().prop_map(TransactionArgument::Bool), any...
name, type_params,
random_line_split
spendfrom.py
.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1...
(bitcoind, fromaddresses, toaddress, amount, fee): all_coins = list_available(bitcoind) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outpu...
create_tx
identifier_name
spendfrom.py
of settings""" from ConfigParser import SafeConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[all]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sech...
pass # Keep asking for passphrase until they get it right txdata = create_tx(bitcoind, options.fromaddresses.split(","), options.to, amount, fee) sanity_test_fee(bitcoind, txdata, amount*Decimal("0.01"))
random_line_split
spendfrom.py
.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1...
# outputs = { toaddress : float(amount) } (inputs, change_amount) = select_coins(needed, potential_inputs) if change_amount > BASE_FEE: # don't bother with zero or tiny change change_address = fromaddresses[-1] if change_address in outputs: outputs[change_address] += float...
all_coins = list_available(bitcoind) total_available = Decimal("0.0") needed = amount+fee potential_inputs = [] for addr in fromaddresses: if addr not in all_coins: continue potential_inputs.extend(all_coins[addr]["outputs"]) total_available += all_coins[addr]["total...
identifier_body
spendfrom.py
.path import platform import sys import time from jsonrpc import ServiceProxy, json BASE_FEE=Decimal("0.001") def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1...
return result except: sys.stderr.write("Error connecting to RPC server at "+connect+"\n") sys.exit(1) def unlock_wallet(bitcoind): info = bitcoind.getinfo() if 'unlocked_until' not in info: return True # wallet is not encrypted t = int(info['unlocked_until']) if t <...
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") sys.exit(1)
conditional_block
markdown-it-container-tests.ts
import MarkdownIt = require("markdown-it"); import Token = require("markdown-it/lib/token"); import MarkdownItContainer = require("markdown-it-container"); const md = new MarkdownIt(); md.use(MarkdownItContainer, 'spoiler', { validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), render: (tokens: Toke...
} } }); const src = `:::spoiler This Is Spoiler Title Here is spoiler content. :::`; md.render(src);
); } else { return '</div></div>\n';
random_line_split
markdown-it-container-tests.ts
import MarkdownIt = require("markdown-it"); import Token = require("markdown-it/lib/token"); import MarkdownItContainer = require("markdown-it-container"); const md = new MarkdownIt(); md.use(MarkdownItContainer, 'spoiler', { validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), render: (tokens: Toke...
else { return '</div></div>\n'; } } }); const src = `:::spoiler This Is Spoiler Title Here is spoiler content. :::`; md.render(src);
{ return ( // tslint:disable-next-line prefer-template '<div class="markdown__spoiler">\n' + '<div class="markdown__spoiler-title" onclick="' + onClick + '">\n' + md.utils.escapeHtml(match && match[1] || '') + '\n' + '</div>\n' + '<div class="markdown__spoiler-content">\n' ); }
conditional_block
maskSpec.js
xdescribe('uiMask', function () { var inputHtml = "<input ui-mask=\"'(9)9'\" ng-model='x'>"; var $compile, $rootScope, element; beforeEach(module('ui.directives')); beforeEach(inject(function (_$rootScope_, _$compile_) { $rootScope = _$rootScope_; $compile = _$compile_; })); describe('ui changes o...
}); expect(element.val()).toBe(''); }); }); describe('model binding on ui change', function () { //TODO: was having har time writing those tests, will open a separate issue for those }); describe('should fail', function() { it('errors on missing quotes', function() { $rootScope.x...
expect(element.val()).toBe('(1)2'); $rootScope.$apply(function () { $rootScope.x = 1;
random_line_split
tastings.service.ts
// import 'rxjs/Rx'; import {Injectable} from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { catchError, } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; import { apiConfig } from '../api.config'; @Injectable() export class TastingsService { p...
.post(this._baseURL, wishlist) .map((res: Response) => res.json()) .catch(this.handleError); } read(wishlistId: string): Observable<any> { return this._http .get(`${this._baseURL}/${wishlistId}`) .map((res: Response) => res.json()) .catch(this.handleError); } update(w...
/* handled in scotches module create(wishlist: any): Observable<any> { return this._http
random_line_split
tastings.service.ts
// import 'rxjs/Rx'; import {Injectable} from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { catchError, } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; import { apiConfig } from '../api.config'; @Injectable() export class TastingsService { p...
(): Observable<any> { return this._http .get(this._baseURL) .pipe(catchError(this.handleError)); } /* getWishlistId(wishlist: string): Observable<any> { return this._http .get(`${this._baseURL}/byName/${wishlist}`) .map((res: Response) => res.json()) .catch(this.handleError)...
list
identifier_name
tastings.service.ts
// import 'rxjs/Rx'; import {Injectable} from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { catchError, } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; import { apiConfig } from '../api.config'; @Injectable() export class TastingsService { p...
}
{ return throwError(error.error.message || 'Server error'); }
identifier_body
ansible-report.py
# (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' callback: debug type: stdout short_description: formated stdout/stderr display...
def v2_runner_on_ok(self, result): host = result._host self.results[-1]['tasks'][-1]['hosts'][host.name] = result._result self.results[-1]['tasks'][-1]['hosts'][host.name]['epoch'] = time.time() self.module_filter(result) return CallbackModule_default.v2_runner_on_ok(self,r...
self.results[-1]['tasks'].append(self._new_task(task)) return CallbackModule_default.v2_playbook_on_task_start(self, task, is_conditional)
identifier_body
ansible-report.py
# (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' callback: debug type: stdout short_description: formated stdout/stderr display...
# End module filter def _new_play(self, play): return { 'play': { 'name': play.name, 'id': str(play._uuid) }, 'tasks': [] } def _new_task(self, task): return { 'task': { 'name': task.na...
value = str(dargs[data]) self.db_update_value(result._host,data,value,result._result['epoch'],result._task.name) #########################
random_line_split
ansible-report.py
# (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' callback: debug type: stdout short_description: formated stdout/stderr display...
(self, play): return { 'play': { 'name': play.name, 'id': str(play._uuid) }, 'tasks': [] } def _new_task(self, task): return { 'task': { 'name': task.name, 'id': str(task._uuid) ...
_new_play
identifier_name
ansible-report.py
# (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' callback: debug type: stdout short_description: formated stdout/stderr display...
dargs = result._task.args['data'] for data in dargs: value = str(dargs[data]) self.db_update_value(result._host,data,value,result._result['epoch'],result._task.name) ######################### # End module filter def _new_play(sel...
dbfile = result._task.args['sqlite'] self.init_sqlite(dbfile)
conditional_block
AgentProfileManager.py
import json import datetime from django.core.files.base import ContentFile from django.core.exceptions import ValidationError from django.utils.timezone import utc from ..models import AgentProfile from ..exceptions import IDNotFoundError, ParamError from ..utils import etag class AgentProfileManager(): def __...
try: self.get_profile(profile_id).delete() # we don't want it anyway except AgentProfile.DoesNotExist: pass except IDNotFoundError: pass
identifier_body
AgentProfileManager.py
import json import datetime from django.core.files.base import ContentFile from django.core.exceptions import ValidationError from django.utils.timezone import utc from ..models import AgentProfile from ..exceptions import IDNotFoundError, ParamError from ..utils import etag class AgentProfileManager(): def __...
(self, p, profile, request_dict): p.content_type = request_dict['headers']['CONTENT_TYPE'] p.etag = etag.create_tag(profile.read()) if 'updated' in request_dict['headers'] and request_dict['headers']['updated']: p.updated = request_dict['headers']['updated'] else: ...
save_non_json_profile
identifier_name
AgentProfileManager.py
import json import datetime from django.core.files.base import ContentFile from django.core.exceptions import ValidationError from django.utils.timezone import utc from ..models import AgentProfile from ..exceptions import IDNotFoundError, ParamError from ..utils import etag class AgentProfileManager(): def __...
if created: p.json_profile = post_profile p.content_type = "application/json" p.etag = etag.create_tag(post_profile) # If incoming profile is application/json and if a profile already # existed with the same agent and profileId else: orig_p...
# already exist with the same agent and profileId
random_line_split
AgentProfileManager.py
import json import datetime from django.core.files.base import ContentFile from django.core.exceptions import ValidationError from django.utils.timezone import utc from ..models import AgentProfile from ..exceptions import IDNotFoundError, ParamError from ..utils import etag class AgentProfileManager(): def __...
def get_profile(self, profile_id): try: return self.Agent.agentprofile_set.get(profile_id=profile_id) except: err_msg = 'There is no agent profile associated with the id: %s' % profile_id raise IDNotFoundError(err_msg) def get_profile_ids(self, since=None):...
etag.check_preconditions(request_dict, p, created) the_profile = request_dict['profile'] p.json_profile = the_profile p.content_type = request_dict['headers']['CONTENT_TYPE'] p.etag = etag.create_tag(the_profile) # Set updated if 'updated' in requ...
conditional_block
colorUtils.ts
///<reference path="../reference.ts" /> module Plottable { export module Utils { export module Color { let nativeMath: Math = (<any>window).Math; /** * Return contrast ratio between two colors * Based on implementation from chroma.js by Gregor Aisch (gka) (licensed under BSD) * chroma.js may ...
/** * Gets the Hex Code of the color resulting by applying the className CSS class to the * colorTester selection. Returns null if the tester is transparent. * * @param {d3.Selection<void>} colorTester The d3 selection to apply the CSS class to * @param {string} className The name of the ...
{ let hsl = <d3.Hsl> d3.hsl(color).brighter(factor); return hsl.rgb().toString(); }
identifier_body
colorUtils.ts
///<reference path="../reference.ts" /> module Plottable { export module Utils { export module Color { let nativeMath: Math = (<any>window).Math; /** * Return contrast ratio between two colors * Based on implementation from chroma.js by Gregor Aisch (gka) (licensed under BSD) * chroma.js may ...
let rgb = /\((.+)\)/.exec(colorStyle)[1] .split(",") .map((colorValue: string) => { let colorNumber = +colorValue; let hexValue = colorNumber.toString(16); return colorNumber < ...
{ return null; }
conditional_block
colorUtils.ts
///<reference path="../reference.ts" /> module Plottable { export module Utils { export module Color { let nativeMath: Math = (<any>window).Math; /** * Return contrast ratio between two colors * Based on implementation from chroma.js by Gregor Aisch (gka) (licensed under BSD) * chroma.js may ...
(colorTester: d3.Selection<void>, className: string) { colorTester.classed(className, true); // Use regex to get the text inside the rgb parentheses let colorStyle = colorTester.style("background-color"); if (colorStyle === "transparent") { return null; } let rgb = /\((.+)\)/...
colorTest
identifier_name
colorUtils.ts
///<reference path="../reference.ts" /> module Plottable { export module Utils { export module Color { let nativeMath: Math = (<any>window).Math; /** * Return contrast ratio between two colors * Based on implementation from chroma.js by Gregor Aisch (gka) (licensed under BSD) * chroma.js may ...
*/ export function colorTest(colorTester: d3.Selection<void>, className: string) { colorTester.classed(className, true); // Use regex to get the text inside the rgb parentheses let colorStyle = colorTester.style("background-color"); if (colorStyle === "transparent") { return nul...
* colorTester selection. Returns null if the tester is transparent. * * @param {d3.Selection<void>} colorTester The d3 selection to apply the CSS class to * @param {string} className The name of the class to be applied * @return {string} The hex code of the computed color
random_line_split
serial.rs
use lazy_static::lazy_static; use spin::Mutex; use uart_16550::SerialPort; lazy_static! { pub static ref SERIAL1: Mutex<SerialPort> = { let mut serial_port = unsafe { SerialPort::new(0x3F8) }; serial_port.init(); Mutex::new(serial_port) }; } pub fn print(args: ::core::fmt::Arguments)
/// Prints to the host through the serial interface. #[macro_export] macro_rules! serial_print { ($($arg:tt)*) => { $crate::serial::print(format_args!($($arg)*)); }; } /// Prints to the host through the serial interface, appending a newline. #[macro_export] macro_rules! serial_println { () => ($c...
{ use core::fmt::Write; SERIAL1 .lock() .write_fmt(args) .expect("Printing to serial failed"); }
identifier_body
serial.rs
use lazy_static::lazy_static; use spin::Mutex; use uart_16550::SerialPort; lazy_static! { pub static ref SERIAL1: Mutex<SerialPort> = { let mut serial_port = unsafe { SerialPort::new(0x3F8) }; serial_port.init(); Mutex::new(serial_port) }; } pub fn
(args: ::core::fmt::Arguments) { use core::fmt::Write; SERIAL1 .lock() .write_fmt(args) .expect("Printing to serial failed"); } /// Prints to the host through the serial interface. #[macro_export] macro_rules! serial_print { ($($arg:tt)*) => { $crate::serial::print(format_ar...
print
identifier_name
serial.rs
use lazy_static::lazy_static; use spin::Mutex; use uart_16550::SerialPort;
serial_port.init(); Mutex::new(serial_port) }; } pub fn print(args: ::core::fmt::Arguments) { use core::fmt::Write; SERIAL1 .lock() .write_fmt(args) .expect("Printing to serial failed"); } /// Prints to the host through the serial interface. #[macro_export] macro_ru...
lazy_static! { pub static ref SERIAL1: Mutex<SerialPort> = { let mut serial_port = unsafe { SerialPort::new(0x3F8) };
random_line_split
contacts.rs
use postgres; use ipm::PostgresReqExt; use rustc_serialize::json::ToJson; use time::Timespec; #[derive(ToJson)] pub struct Contact { pub contact_id: i32, pub forename: String, pub surname: String, pub email: String, pub cell: String, pub description: String, pub modified: Timespec } impl Cont...
let rows = stmt.query(&[]).unwrap(); for row in rows { vec.push(Contact { contact_id: row.get(0), forename: row.get(1), surname: row.get(2), email: row.get(3), cell: row.get(4), description: row.g...
let stmt = conn.prepare( "SELECT * FROM contacts" ).unwrap();
random_line_split
contacts.rs
use postgres; use ipm::PostgresReqExt; use rustc_serialize::json::ToJson; use time::Timespec; #[derive(ToJson)] pub struct
{ pub contact_id: i32, pub forename: String, pub surname: String, pub email: String, pub cell: String, pub description: String, pub modified: Timespec } impl Contact { pub fn get_all(req: &PostgresReqExt) -> Vec<Contact> { let mut vec = Vec::new(); let conn = req.db_conn(...
Contact
identifier_name
stream.ts
/* Copyright 2016 kanreisa Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
}, { in: "query", name: "type", type: "string", enum: ["create", "update", "remove"], required: false } ], responses: { 200: { description: "OK", schema: { type: "arra...
required: false
random_line_split
stream.ts
/* Copyright 2016 kanreisa Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
res.write(JSON.stringify(message) + "\n,\n"); } }; get.apiDoc = { tags: ["events", "stream"], operationId: "getEventsStream", parameters: [ { in: "query", name: "resource", type: "string", enum: ["program", "service", "tune...
{ return; }
conditional_block
stream.ts
/* Copyright 2016 kanreisa Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
}; get.apiDoc = { tags: ["events", "stream"], operationId: "getEventsStream", parameters: [ { in: "query", name: "resource", type: "string", enum: ["program", "service", "tuner"], required: false }, { ...
{ if (req.query.resource && req.query.resource !== message.resource) { return; } if (req.query.type && req.query.type !== message.type) { return; } res.write(JSON.stringify(message) + "\n,\n"); }
identifier_body
stream.ts
/* Copyright 2016 kanreisa Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
(message: EventMessage) { if (req.query.resource && req.query.resource !== message.resource) { return; } if (req.query.type && req.query.type !== message.type) { return; } res.write(JSON.stringify(message) + "\n,\n"); } }; get.apiDoc = ...
_listener
identifier_name
TransformUI.py
########################################################################## # # Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import Gaffer import GafferUI impor...
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
random_line_split
createWatchProgram.js
_1.getTsconfigPath(rawTsconfigPath, extra); const existingWatch = knownWatchProgramMap.get(tsconfigPath); if (!existingWatch) { continue; } let fileList = programFileListCache.get(tsconfigPath); let updatedProgram = null; if (!fileList) { updatedPr...
{ return updatedProgram; }
conditional_block
createWatchProgram.js
ModifiedTimestampCache.clear(); } exports.clearCaches = clearCaches; function saveWatchCallback(trackingMap) { return (fileName, callback) => { const normalizedFileName = shared_1.getCanonicalFileName(fileName); const watchers = (() => { let watchers = trackingMap.get(normalizedFileName)...
/** * Calculate project environments using options provided by consumer and paths from config * @param code The code being linted * @param filePathIn The path of the file being parsed * @param extra.tsconfigRootDir The root directory for relative tsconfig paths * @param extra.projects Provided tsconfig paths * @...
{ // No ts.sys in browser environments. if (ts.sys && ts.sys.createHash) { return ts.sys.createHash(content); } return content; }
identifier_body
createWatchProgram.js
extra.projects Provided tsconfig paths * @returns The programs corresponding to the supplied tsconfig paths */ function getProgramsForProjects(code, filePathIn, extra) { const filePath = shared_1.getCanonicalFileName(filePathIn); const results = []; // preserve reference to code and file being linted ...
let hasCallback = false; while (current !== next) { current = next; const folderWatchCallbacks = folderWatchCallbackTrackingMap.get(current);
random_line_split
createWatchProgram.js
ModifiedTimestampCache.clear(); } exports.clearCaches = clearCaches; function saveWatchCallback(trackingMap) { return (fileName, callback) => { const normalizedFileName = shared_1.getCanonicalFileName(fileName); const watchers = (() => { let watchers = trackingMap.get(normalizedFileName)...
(content) { // No ts.sys in browser environments. if (ts.sys && ts.sys.createHash) { return ts.sys.createHash(content); } return content; } /** * Calculate project environments using options provided by consumer and paths from config * @param code The code being linted * @param filePathIn The...
createHash
identifier_name
bar.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.recursive_point = recursive_point
identifier_body
bar.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Model): """ The URIs that are used to perform a retrieval of a public blob, queue or table object. :param recursive_point: Recursive Endpoints :type recursive_point: :class:`Endpoints <fixtures.acceptancetestsstoragemanagementclient.models.Endpoints>` """ _attribute_map = { ...
Bar
identifier_name
tests.rs
use super::*; use crate::ffi::OsStr; use crate::mem; use crate::ptr; use crate::sys::cvt; macro_rules! t { ($e:expr) => { match $e { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } }; } #[test] #[cfg_attr( any( // See #1423...
() { unsafe { // Test to make sure that a signal mask does not get inherited. let mut cmd = Command::new(OsStr::new("cat")); let mut set = mem::MaybeUninit::<libc::sigset_t>::uninit(); let mut old_set = mem::MaybeUninit::<libc::sigset_t>::uninit(); t!(cvt(sigemptyset(set.as_...
test_process_mask
identifier_name
tests.rs
use super::*; use crate::ffi::OsStr; use crate::mem; use crate::ptr; use crate::sys::cvt; macro_rules! t { ($e:expr) => { match $e { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } }; } #[test] #[cfg_attr( any( // See #1423...
t!(cat.wait()); } }
let mut buf = [0; 5]; if let Ok(ret) = stdout_read.read(&mut buf) { assert_eq!(ret, 0); }
random_line_split
tests.rs
use super::*; use crate::ffi::OsStr; use crate::mem; use crate::ptr; use crate::sys::cvt; macro_rules! t { ($e:expr) => { match $e { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } }; } #[test] #[cfg_attr( any( // See #1423...
t!(cat.wait()); } }
{ assert_eq!(ret, 0); }
conditional_block
tests.rs
use super::*; use crate::ffi::OsStr; use crate::mem; use crate::ptr; use crate::sys::cvt; macro_rules! t { ($e:expr) => { match $e { Ok(t) => t, Err(e) => panic!("received error for `{}`: {}", stringify!($e), e), } }; } #[test] #[cfg_attr( any( // See #1423...
t!(cvt(libc::kill(cat.id() as libc::pid_t, libc::SIGINT))); // We need to wait until SIGINT is definitely delivered. The // easiest way is to write something to cat, and try to read it // back: if SIGINT is unmasked, it'll get delivered when cat is // next scheduled. let ...
{ unsafe { // Test to make sure that a signal mask does not get inherited. let mut cmd = Command::new(OsStr::new("cat")); let mut set = mem::MaybeUninit::<libc::sigset_t>::uninit(); let mut old_set = mem::MaybeUninit::<libc::sigset_t>::uninit(); t!(cvt(sigemptyset(set.as_mut...
identifier_body
base.py
PositiveSmallIntegerField=(0, 4294967295), PositiveIntegerField=(0, 18446744073709551615), ) def date_extract_sql(self, lookup_type, field_name): # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html if lookup_type == 'week_day': # DAYOFWEEK() returns an i...
self.features = DatabaseFeatures(self) self.ops = DatabaseOperations(self) self.client = DatabaseClient(self) self.creation = DatabaseCreation(self) self.introspection = DatabaseIntrospection(self)
random_line_split
base.py
except ValueError: sql = field_name else: format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]]) sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) return sql def datetime_extract_sql(self, lookup_type, field_n...
conn = Database.connect(**conn_params) conn.encoders[SafeText] = conn.encoders[six.text_type] conn.encoders[SafeBytes] = conn.encoders[bytes] return conn
identifier_body
base.py
cursor.execute("SELECT 1 FROM mysql.time_zone LIMIT 1") return cursor.fetchone() is not None class DatabaseOperations(BaseDatabaseOperations): compiler_module = "django.db.backends.mysql.compiler" # MySQL stores positive fields as UNSIGNED ints. integer_field_ranges = dict(BaseDat...
__init__
identifier_name
base.py
# specific behavior. self.close() class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () update_can_self_select = False allows_group_by_pk = True related_fields_match_type = True allow_sliced_subqueries = False has_bulk_insert = True has_select_for_update = True ...
raise ValueError('The database backend does not accept 0 as a ' 'value for AutoField.')
conditional_block
test_source_api.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ...
(self): """Test case for get_source_tags Get all tags associated with a specific source # noqa: E501 """ pass def test_remove_description(self): """Test case for remove_description Remove description from a specific source # noqa: E501 """ pass ...
test_get_source_tags
identifier_name
test_source_api.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ...
from __future__ import absolute_import import unittest import wavefront_api_client from wavefront_api_client.api.source_api import SourceApi # noqa: E501 from wavefront_api_client.rest import ApiException class TestSourceApi(unittest.TestCase): """SourceApi unit test stubs""" def setUp(self): sel...
OpenAPI spec version: v2 Contact: chitimba@wavefront.com Generated by: https://github.com/swagger-api/swagger-codegen.git """
random_line_split
test_source_api.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ...
pass def test_delete_source(self): """Test case for delete_source Delete metadata (description and tags) for a specific source # noqa: E501 """ pass def test_get_all_source(self): """Test case for get_all_source Get all sources for a customer # noqa:...
"""SourceApi unit test stubs""" def setUp(self): self.api = wavefront_api_client.api.source_api.SourceApi() # noqa: E501 def tearDown(self): pass def test_add_source_tag(self): """Test case for add_source_tag Add a tag to a specific source # noqa: E501 """ ...
identifier_body
test_source_api.py
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ...
unittest.main()
conditional_block
mongo.js
} }, // Simply return the entered string if the user hasn't specified a smarter handler. mockHandler: function(inputString) { return function() { this._process = function() { return inputString; }; }; } }; var MongoHandler = function() { this._connection = new Connection(); this._curren...
_next: function() { if(this._tutorialPtr < this._tutorialMax) { return this['_t' + (this._tutorialPtr + 1)](); } else { return "You've reached the end of the tutorial. To go to the beginning, type 'tutorial'"; } }, // go to the previous step in the tutorial. _back: function() { ...
// go to the next step in the tutorial.
random_line_split
mongo.js
} }, // Simply return the entered string if the user hasn't specified a smarter handler. mockHandler: function(inputString) { return function() { this._process = function() { return inputString; }; }; } }; var MongoHandler = function() { this._connection = new Connection(); this._curren...
} catch(err) { // Allows for dynamic creation of db collections. // We catch the exception, create the collection, then try the command again. matches = this._currentCommand.match(/db\.(\w+)/); if(matches && matches.length == 2 && errorCheck !== true && !this.collections.in...
{ return this._evaluator(tokens); }
conditional_block
butterfaces-clientSideFilter.jquery.js
/** * butterItemFilterField is a jQuery plugin that filters html element with the css class <code>filterable-item</code>. * It is applied to the search field.<br/> * If no filter text is entered, then all filterable-items are displayed. Else the search field value is matched against <b>all</b> text contained by a fi...
var $this = $(this); $this.keyup(function () { delay(function () { var filterValue = $this.val(); // find container again every time, because it could have been rerendered. var $filterableItemContainer; ...
$.fn.butterItemFilterField = function (filterableItemContainerSelector) { return this.each(function () {
random_line_split
butterfaces-clientSideFilter.jquery.js
/** * butterItemFilterField is a jQuery plugin that filters html element with the css class <code>filterable-item</code>. * It is applied to the search field.<br/> * If no filter text is entered, then all filterable-items are displayed. Else the search field value is matched against <b>all</b> text contained by a fi...
}); }, 300); }); }); }; }(jQuery)); (function ($) { $.expr[":"].containsIgnoreCase = $.expr.createPseudo(function (arg) { return function (elem) { return !arg || $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }...
{ $filterableItem.attr("hidden", "hidden"); }
conditional_block
observable-simple.component.ts
/* * MIT License * * Copyright (c) 2017-2018 Stefano Cappa * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, cop...
}
{ this.titleService.titleEvent.emit('Demo - Observable simple'); }
identifier_body
observable-simple.component.ts
/* * MIT License * * Copyright (c) 2017-2018 Stefano Cappa * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, cop...
(private titleService: TitleService) { this.titleService.titleEvent.emit('Demo - Observable simple'); } }
constructor
identifier_name
observable-simple.component.ts
/* * MIT License *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial ...
* Copyright (c) 2017-2018 Stefano Cappa * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights
random_line_split
integration_parameters.rs
use na::{self, RealField}; /// Parameters for a time-step of the physics engine. #[derive(Clone)] pub struct IntegrationParameters<N: RealField> { /// The timestep (default: `1.0 / 60.0`) dt: N, /// The inverse of `dt`. inv_dt: N, /// If `true`, the world's `step` method will stop right after resol...
else { self.inv_dt = N::one() / dt } } /// Sets the inverse time-stepping length (i.e. the frequency). /// /// This automatically recompute `self.dt`. #[inline] pub fn set_inv_dt(&mut self, inv_dt: N) { self.inv_dt = inv_dt; if inv_dt == N::zero() { ...
{ self.inv_dt = N::zero() }
conditional_block
integration_parameters.rs
use na::{self, RealField}; /// Parameters for a time-step of the physics engine. #[derive(Clone)] pub struct IntegrationParameters<N: RealField> { /// The timestep (default: `1.0 / 60.0`) dt: N, /// The inverse of `dt`. inv_dt: N, /// If `true`, the world's `step` method will stop right after resol...
} impl<N: RealField> Default for IntegrationParameters<N> { fn default() -> Self { Self::new( na::convert(1.0 / 60.0), na::convert(0.2), na::convert(1.0), na::convert(1.0), na::convert(0.001), na::convert(0.001), na::conve...
{ self.inv_dt = inv_dt; if inv_dt == N::zero() { self.dt = N::zero() } else { self.dt = N::one() / inv_dt } }
identifier_body
integration_parameters.rs
use na::{self, RealField}; /// Parameters for a time-step of the physics engine. #[derive(Clone)] pub struct IntegrationParameters<N: RealField> { /// The timestep (default: `1.0 / 60.0`) dt: N, /// The inverse of `dt`. inv_dt: N, /// If `true`, the world's `step` method will stop right after resol...
inv_dt: if dt == N::zero() { N::zero() } else { N::one() / dt }, erp, warmstart_coeff, restitution_velocity_threshold, allowed_linear_error, allowed_angular_error, max_linear_corre...
IntegrationParameters { t: N::zero(), dt,
random_line_split
integration_parameters.rs
use na::{self, RealField}; /// Parameters for a time-step of the physics engine. #[derive(Clone)] pub struct
<N: RealField> { /// The timestep (default: `1.0 / 60.0`) dt: N, /// The inverse of `dt`. inv_dt: N, /// If `true`, the world's `step` method will stop right after resolving exactly one CCD event (default: `false`). /// This allows the user to take action during a timestep, in-between two CCD ev...
IntegrationParameters
identifier_name
Pagination.py
''' Created on 17-Feb-2015 @author: Asawari.Vaidya ''' from PythonNetBanxSDK.common.DomainObject import DomainObject class Pagination(DomainObject): ''' classdocs ''' def __init__(self,obj): ''' Constructor ''' # Handler dictionary handler = dict() han...
''' Property Start Date ''' def startDate(self, startDate): self.__dict__['startDate'] = startDate ''' Property End Date ''' def endDate(self, endDate): self.__dict__['endDate'] = endDate
self.__dict__['offset'] = offset
identifier_body
Pagination.py
''' Created on 17-Feb-2015 @author: Asawari.Vaidya ''' from PythonNetBanxSDK.common.DomainObject import DomainObject class Pagination(DomainObject): ''' classdocs ''' def __init__(self,obj): ''' Constructor ''' # Handler dictionary handler = dict() han...
def startDate(self, startDate): self.__dict__['startDate'] = startDate ''' Property End Date ''' def endDate(self, endDate): self.__dict__['endDate'] = endDate
random_line_split
Pagination.py
''' Created on 17-Feb-2015 @author: Asawari.Vaidya ''' from PythonNetBanxSDK.common.DomainObject import DomainObject class Pagination(DomainObject): ''' classdocs ''' def __init__(self,obj): ''' Constructor ''' # Handler dictionary handler = dict() han...
(self, startDate): self.__dict__['startDate'] = startDate ''' Property End Date ''' def endDate(self, endDate): self.__dict__['endDate'] = endDate
startDate
identifier_name
Pagination.py
''' Created on 17-Feb-2015 @author: Asawari.Vaidya ''' from PythonNetBanxSDK.common.DomainObject import DomainObject class Pagination(DomainObject): ''' classdocs ''' def __init__(self,obj): ''' Constructor ''' # Handler dictionary handler = dict() han...
''' Property Limit ''' def limit(self, limit): self.__dict__['limit'] = limit ''' Property Offset ''' def offset(self, offset): self.__dict__['offset'] = offset ''' Property Start Date ''' def startDate(self, startDate): ...
pass
conditional_block
conus_boundary_test.py
"""Unit tests for conus_boundary.py.""" import unittest import numpy from gewittergefahr.gg_utils import conus_boundary QUERY_LATITUDES_DEG = numpy.array([ 33.7, 42.6, 39.7, 34.9, 40.2, 33.6, 36.4, 35.1, 30.8, 47.4, 44.2, 45.1, 49.6, 38.9, 35.0, 38.1, 40.7, 47.1, 30.2, 39.2 ]) QUERY_LONGITUDES_DEG = numpy.arr...
(self): """Ensures correct output from find_points_in_conus. In this case, uses shortcuts. """ conus_latitudes_deg, conus_longitudes_deg = ( conus_boundary.read_from_netcdf() ) these_flags = conus_boundary.find_points_in_conus( conus_latitudes_d...
test_find_points_in_conus_with_shortcuts
identifier_name
conus_boundary_test.py
"""Unit tests for conus_boundary.py.""" import unittest import numpy from gewittergefahr.gg_utils import conus_boundary QUERY_LATITUDES_DEG = numpy.array([ 33.7, 42.6, 39.7, 34.9, 40.2, 33.6, 36.4, 35.1, 30.8, 47.4, 44.2, 45.1, 49.6, 38.9, 35.0, 38.1, 40.7, 47.1, 30.2, 39.2 ]) QUERY_LONGITUDES_DEG = numpy.arr...
unittest.main()
conditional_block
conus_boundary_test.py
"""Unit tests for conus_boundary.py.""" import unittest import numpy from gewittergefahr.gg_utils import conus_boundary QUERY_LATITUDES_DEG = numpy.array([ 33.7, 42.6, 39.7, 34.9, 40.2, 33.6, 36.4, 35.1, 30.8, 47.4, 44.2, 45.1, 49.6, 38.9, 35.0, 38.1, 40.7, 47.1, 30.2, 39.2 ]) QUERY_LONGITUDES_DEG = numpy.arr...
def test_find_points_in_conus_with_shortcuts(self): """Ensures correct output from find_points_in_conus. In this case, uses shortcuts. """ conus_latitudes_deg, conus_longitudes_deg = ( conus_boundary.read_from_netcdf() ) these_flags = conus_boundary.f...
"""Ensures correct output from find_points_in_conus. In this case, does not use shortcuts. """ conus_latitudes_deg, conus_longitudes_deg = ( conus_boundary.read_from_netcdf() ) these_flags = conus_boundary.find_points_in_conus( conus_latitudes_deg=conus...
identifier_body
conus_boundary_test.py
"""Unit tests for conus_boundary.py.""" import unittest import numpy from gewittergefahr.gg_utils import conus_boundary QUERY_LATITUDES_DEG = numpy.array([ 33.7, 42.6, 39.7, 34.9, 40.2, 33.6, 36.4, 35.1, 30.8, 47.4, 44.2, 45.1, 49.6, 38.9, 35.0, 38.1, 40.7, 47.1, 30.2, 39.2 ]) QUERY_LONGITUDES_DEG = numpy.arr...
conus_longitudes_deg=conus_longitudes_deg, query_latitudes_deg=QUERY_LATITUDES_DEG, query_longitudes_deg=QUERY_LONGITUDES_DEG, use_shortcuts=False) self.assertTrue(numpy.array_equal(these_flags, IN_CONUS_FLAGS)) def test_find_points_in_conus_with_shortcuts(self): ...
these_flags = conus_boundary.find_points_in_conus( conus_latitudes_deg=conus_latitudes_deg,
random_line_split
LinkUtility.ts
import AsyncStateNavigator from './AsyncStateNavigator'; import { LinkProps } from './Props'; class LinkUtility { static getData(stateNavigator: AsyncStateNavigator, navigationData, includeCurrentData: boolean, currentDataKeys: string | string[]): any { if (currentDataKeys || includeCurrentData) { ...
rops: any): any { var htmlProps = {}; for(var key in props) { if (key !== 'stateNavigator' && key !== 'stateKey' && key !== 'navigationData' && key !== 'includeCurrentData' && key !== 'currentDataKeys' && key !== 'hash' && key !== 'activeStyle' && key !== 'act...
HtmlProps(p
identifier_name
LinkUtility.ts
import AsyncStateNavigator from './AsyncStateNavigator'; import { LinkProps } from './Props'; class LinkUtility { static getData(stateNavigator: AsyncStateNavigator, navigationData, includeCurrentData: boolean, currentDataKeys: string | string[]): any {
static isActive(stateNavigator: AsyncStateNavigator, navigationData: any): boolean { var active = true; for (var key in navigationData) { var val = navigationData[key]; active = active && (val == null || this.areEqual(val, stateNavigator.stateContext.data[key])); } ...
if (currentDataKeys || includeCurrentData) { var keys = typeof currentDataKeys === 'string' ? currentDataKeys.trim().split(/\s*,\s*/) : currentDataKeys; navigationData = stateNavigator.stateContext.includeCurrentData(navigationData, keys); } return navigationData; }
identifier_body
LinkUtility.ts
import AsyncStateNavigator from './AsyncStateNavigator'; import { LinkProps } from './Props'; class LinkUtility { static getData(stateNavigator: AsyncStateNavigator, navigationData, includeCurrentData: boolean, currentDataKeys: string | string[]): any { if (currentDataKeys || includeCurrentData) { ...
return active; } static setActive(active: boolean, props: any, toProps: any) { if (active && props.activeStyle) toProps.style = {...toProps.style, ...props.activeStyle}; if (active && props.activeCssClass) toProps.className = (!toProps.className ? '' : toProps.cl...
active = active && (val == null || this.areEqual(val, stateNavigator.stateContext.data[key])); }
random_line_split
selection_manager.ts
import {HasProps} from "./has_props" import {Geometry} from "./geometry" import {Selection} from "models/selections/selection" import {Renderer, RendererView} from "models/renderers/renderer" import {GlyphRendererView} from "models/renderers/glyph_renderer" import {GraphRendererView} from "models/renderers/graph_render...
(attrs?: Partial<SelectionManager.Attrs>) { super(attrs) } static initClass(): void { this.internal({ source: [ p.Any ], }) } inspectors: {[key: string]: Selection} = {} select(renderer_views: RendererView[], geometry: Geometry, final: boolean, append: boolean = false): boolean { // d...
constructor
identifier_name
selection_manager.ts
import {HasProps} from "./has_props" import {Geometry} from "./geometry" import {Selection} from "models/selections/selection" import {Renderer, RendererView} from "models/renderers/renderer" import {GlyphRendererView} from "models/renderers/glyph_renderer" import {GraphRendererView} from "models/renderers/graph_render...
this.source.selected.clear() if (rview != null) this.get_or_create_inspector(rview.model).clear() } get_or_create_inspector(rmodel: Renderer): Selection { if (this.inspectors[rmodel.id] == null) this.inspectors[rmodel.id] = new Selection() return this.inspectors[rmodel.id] } } Selecti...
random_line_split
selection_manager.ts
import {HasProps} from "./has_props" import {Geometry} from "./geometry" import {Selection} from "models/selections/selection" import {Renderer, RendererView} from "models/renderers/renderer" import {GlyphRendererView} from "models/renderers/glyph_renderer" import {GraphRendererView} from "models/renderers/graph_render...
} SelectionManager.initClass()
{ if (this.inspectors[rmodel.id] == null) this.inspectors[rmodel.id] = new Selection() return this.inspectors[rmodel.id] }
identifier_body
Sam and sub-strings.py
# -*- coding: utf-8 -*- """ Problem Statement Samantha and Sam are playing a game. They have 'N' balls in front of them, each ball numbered from 0 to 9, except the first ball which is numbered from 1 to 9. Samantha calculates all the sub-strings of the number thus formed, one by one. If the sub-string is S, Sam has to...
(self, cipher): """ O(N^2) :param cipher: the cipher """ A = map(int, list(cipher)) f = A[0] num = A[0] sig = 1 for i in xrange(1, len(A)): num = 10 * num + A[i] sig *= 10 temp = num temp_sig = sig ...
solve_TLE
identifier_name
Sam and sub-strings.py
# -*- coding: utf-8 -*- """ Problem Statement Samantha and Sam are playing a game. They have 'N' balls in front of them, each ball numbered from 0 to 9, except the first ball which is numbered from 1 to 9. Samantha calculates all the sub-strings of the number thus formed, one by one. If the sub-string is S, Sam has to...
temp %= temp_sig temp_sig /= 10 return int(f) def solve(self, cipher): """ O(N) example: 1234 1 12, 2 123, 23, 3 1234, 234, 34, 4 :param cipher: :return: """ pre = [0 for _ in cipher] ...
def solve_TLE(self, cipher): """ O(N^2) :param cipher: the cipher """ A = map(int, list(cipher)) f = A[0] num = A[0] sig = 1 for i in xrange(1, len(A)): num = 10 * num + A[i] sig *= 10 temp = num te...
identifier_body
Sam and sub-strings.py
# -*- coding: utf-8 -*- """ Problem Statement Samantha and Sam are playing a game. They have 'N' balls in front of them, each ball numbered from 0 to 9, except the first ball which is numbered from 1 to 9. Samantha calculates all the sub-strings of the number thus formed, one by one. If the sub-string is S, Sam has to...
temp %= temp_sig temp_sig /= 10 return int(f) def solve(self, cipher): """ O(N) example: 1234 1 12, 2 123, 23, 3 1234, 234, 34, 4 :param cipher: :return: """ pre = [0 for _ in cipher] ...
temp_sig = sig while temp_sig >= 1: f += temp f %= MOD
random_line_split
Sam and sub-strings.py
# -*- coding: utf-8 -*- """ Problem Statement Samantha and Sam are playing a game. They have 'N' balls in front of them, each ball numbered from 0 to 9, except the first ball which is numbered from 1 to 9. Samantha calculates all the sub-strings of the number thus formed, one by one. If the sub-string is S, Sam has to...
return int(s) if __name__ == "__main__": import sys f = open("0.in", "r") # f = sys.stdin solution = Solution() # construct cipher cipher = f.readline().strip() # solve s = "%s\n" % (solution.solve(cipher)) print s,
s = (s + elt) % MOD
conditional_block
StackColumn.ts
/** * Created by sam on 04.11.2016. */ import CompositeNumberColumn from './CompositeNumberColumn'; import {IMultiLevelColumn} from './CompositeColumn'; import Column, {IFlatColumn} from './Column'; /** * factory for creating a description creating a stacked column * @param label * @returns {{type: string, label...
() { return this.collapsed; } flatten(r: IFlatColumn[], offset: number, levelsToGo = 0, padding = 0) { var self = null; const children = levelsToGo <= Column.FLAT_ALL_COLUMNS ? this._children : this._children.filter((c) => !c.isHidden()); //no more levels or just this one if (levelsToGo === 0 |...
getCollapsed
identifier_name
StackColumn.ts
/** * Created by sam on 04.11.2016. */ import CompositeNumberColumn from './CompositeNumberColumn'; import {IMultiLevelColumn} from './CompositeColumn'; import Column, {IFlatColumn} from './Column'; /** * factory for creating a description creating a stacked column * @param label * @returns {{type: string, label...
getCollapsed() { return this.collapsed; } flatten(r: IFlatColumn[], offset: number, levelsToGo = 0, padding = 0) { var self = null; const children = levelsToGo <= Column.FLAT_ALL_COLUMNS ? this._children : this._children.filter((c) => !c.isHidden()); //no more levels or just this one if (le...
{ if (this.collapsed === value) { return; } this.fire([StackColumn.EVENT_COLLAPSE_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY], this.collapsed, this.collapsed = value); }
identifier_body
StackColumn.ts
/** * Created by sam on 04.11.2016. */ import CompositeNumberColumn from './CompositeNumberColumn'; import {IMultiLevelColumn} from './CompositeColumn'; import Column, {IFlatColumn} from './Column'; /** * factory for creating a description creating a stacked column * @param label * @returns {{type: string, label...
r.push(self = {col: this, offset: offset, width: w}); if (levelsToGo === 0) { return w; } } //push children var acc = offset; children.forEach((c) => { acc += c.flatten(r, acc, levelsToGo - 1, padding) + padding; }); if (self) { //nesting my even increase my widt...
{ w += (children.length - 1) * padding; }
conditional_block
StackColumn.ts
/** * Created by sam on 04.11.2016. */ import CompositeNumberColumn from './CompositeNumberColumn'; import {IMultiLevelColumn} from './CompositeColumn'; import Column, {IFlatColumn} from './Column'; /** * factory for creating a description creating a stacked column * @param label * @returns {{type: string, label...
weights.push((1 - s) * (1 / -delta)); } } else if (s <= 100) { for (var i = 0; i < -delta; ++i) { weights.push((100 - s) * (1 / -delta)); } } } weights = weights.slice(0, this.length); s = weights.reduce((p, a) => p + a, 0) / this.getWidth(); weigh...
delta = weights.length - this.length; if (delta < 0) { s = weights.reduce((p, a) => p + a, 0); if (s <= 1) { for (var i = 0; i < -delta; ++i) {
random_line_split
testingContentProvider.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
else if (message) { text = message.value; language = this.modeService.create('markdown'); } break; } if (text === undefined) { return null; } return this.modelService.createModel(text, language, resource, true); } }
{ text = message; }
conditional_block
testingContentProvider.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(resource: URI): Promise<ITextModel | null> { const existing = this.modelService.getModel(resource); if (existing && !existing.isDisposed()) { return existing; } const parsed = parseTestUri(resource); if (!parsed) { return null; } const test = this.resultService.getResult(parsed.resultId)?.getStat...
provideTextContent
identifier_name
testingContentProvider.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (!parsed) { return null; } const test = this.resultService.getResult(parsed.resultId)?.getStateById(parsed.testExtId); if (!test) { return null; } let text: string | undefined; let language: ILanguageSelection | null = null; switch (parsed.type) { case TestUriType.ResultActualOutput: { ...
} const parsed = parseTestUri(resource);
random_line_split
pydevconsole.py
try: from code import InteractiveConsole except ImportError: from pydevconsole_code_for_ironpython import InteractiveConsole import os import sys try: False True except NameError: # version < 2.3 -- didn't have the True/False builtins import __builtin__ setattr(__builtin__, 'True', 1) # Pyth...
#======================================================================================================================= # StartServer #======================================================================================================================= def StartServer(host, port, client_port): # replace exit ...
os._exit(0)
conditional_block
pydevconsole.py
try: from code import InteractiveConsole except ImportError: from pydevconsole_code_for_ironpython import InteractiveConsole import os import sys try: False True except NameError: # version < 2.3 -- didn't have the True/False builtins import __builtin__ setattr(__builtin__, 'True', 1) # Pyth...
try: import builtins builtins.runfile = runfile except: import __builtin__ __builtin__.runfile = runfile #======================================================================================================================= # InterpreterInterface #====================================================...
pass # Pull in runfile, the interface to UMD that wraps execfile from pydev_umd import runfile, _set_globals_function
random_line_split
pydevconsole.py
try: from code import InteractiveConsole except ImportError: from pydevconsole_code_for_ironpython import InteractiveConsole import os import sys try: False True except NameError: # version < 2.3 -- didn't have the True/False builtins import __builtin__ setattr(__builtin__, 'True', 1) # Pyth...
def Sync(runnable): runnable.run() try: try: execfile # Not in Py3k except NameError: from pydev_imports import execfile import builtins # @UnresolvedImport -- only Py3K builtins.execfile = execfile except: pass # Pull in runfile, the interface to UMD that...
def __init__(self, interpreter, line): self.interpreter = interpreter self.line = line def run(self): self.more = self.interpreter.push(self.line)
identifier_body
pydevconsole.py
try: from code import InteractiveConsole except ImportError: from pydevconsole_code_for_ironpython import InteractiveConsole import os import sys try: False True except NameError: # version < 2.3 -- didn't have the True/False builtins import __builtin__ setattr(__builtin__, 'True', 1) # Pyth...
(self, interpreter, line): self.interpreter = interpreter self.line = line def run(self): self.more = self.interpreter.push(self.line) def Sync(runnable): runnable.run() try: try: execfile # Not in Py3k except NameError: from pydev_imp...
__init__
identifier_name
test_rfc2314.py
# # This file is part of pyasn1-modules software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # import sys from pyasn1.codec.der import decoder as der_decoder from pyasn1.codec.der import encoder as der_encoder from pyasn1_modules import pem from pyasn1_m...
(unittest.TestCase): pem_text = """\ MIIDATCCAekCAQAwgZkxCzAJBgNVBAYTAlJVMRYwFAYDVQQIEw1Nb3Njb3cgUmVn aW9uMQ8wDQYDVQQHEwZNb3Njb3cxGjAYBgNVBAoTEVNOTVAgTGFib3JhdG9yaWVz MQwwCgYDVQQLFANSJkQxFTATBgNVBAMTDHNubXBsYWJzLmNvbTEgMB4GCSqGSIb3 DQEJARYRaW5mb0Bzbm1wbGFicy5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw ggEKAoIBAQC9n2NfGS9...
CertificationRequestTestCase
identifier_name
test_rfc2314.py
# # This file is part of pyasn1-modules software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # import sys from pyasn1.codec.der import decoder as der_decoder from pyasn1.codec.der import encoder as der_encoder from pyasn1_modules import pem from pyasn1_m...
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decoder.decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encoder.encode(asn1Object) == substrate suite = unittest.TestLo...
self.asn1Spec = rfc2314.CertificationRequest()
identifier_body
test_rfc2314.py
# # This file is part of pyasn1-modules software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # import sys from pyasn1.codec.der import decoder as der_decoder from pyasn1.codec.der import encoder as der_encoder from pyasn1_modules import pem from pyasn1_m...
unittest.TextTestRunner(verbosity=2).run(suite)
conditional_block
test_rfc2314.py
# # This file is part of pyasn1-modules software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # import sys from pyasn1.codec.der import decoder as der_decoder from pyasn1.codec.der import encoder as der_encoder from pyasn1_modules import pem from pyasn1_m...
self.asn1Spec = rfc2314.CertificationRequest() def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decoder.decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encoder.enc...
random_line_split
hotkeysDialog.tsx
/* * Copyright 2016 Palantir Technologies, Inc. All rights reserved. * * Licensed under the terms of the LICENSE file distributed with this project. */ import * as classNames from "classnames"; import * as React from "react"; import * as ReactDOM from "react-dom"; import { Classes } from "../../common"; import { ...
export function setHotkeysDialogProps(props: Partial<IHotkeysDialogProps>) { for (const key in props) { if (props.hasOwnProperty(key)) { (HOTKEYS_DIALOG.componentProps as any)[key] = (props as any)[key]; } } } export function showHotkeysDialog(hotkeys: IHotkeyProps[]) { HOTKEY...
{ return HOTKEYS_DIALOG.isShowing(); }
identifier_body
hotkeysDialog.tsx
/* * Copyright 2016 Palantir Technologies, Inc. All rights reserved. * * Licensed under the terms of the LICENSE file distributed with this project. */ import * as classNames from "classnames"; import * as React from "react"; import * as ReactDOM from "react-dom"; import { Classes } from "../../common"; import { ...
() { if (this.container != null) { ReactDOM.unmountComponentAtNode(this.container); this.container.remove(); delete this.container; } } /** * Because hotkeys can be registered globally and locally and because * event ordering cannot be guaranteed, w...
unmount
identifier_name
hotkeysDialog.tsx
/* * Copyright 2016 Palantir Technologies, Inc. All rights reserved. * * Licensed under the terms of the LICENSE file distributed with this project. */ import * as classNames from "classnames"; import * as React from "react"; import * as ReactDOM from "react-dom"; import { Classes } from "../../common"; import { ...
if (this.container == null) { this.container = document.createElement("div"); this.container.classList.add(Classes.PORTAL); document.body.appendChild(this.container); } return this.container; } private renderComponent() { return ( ...
public isShowing() { return this.isDialogShowing; } private getContainer() {
random_line_split