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
control.py
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
return model
model = 'exp'
conditional_block
control.py
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR ...
random_line_split
titleUnlock.js
/* * Copyright (C) 2016 Max Prettyjohns * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is d...
return this.belongsTo('TitleType', 'title_id'); } }); return bookshelf.model('TitleUnlock', TitleUnlock); }
idAttribute: 'id', parse: snakeToCamel, tableName: 'bookbrainz.title_unlock', title() {
random_line_split
titleUnlock.js
/* * Copyright (C) 2016 Max Prettyjohns * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is d...
}); return bookshelf.model('TitleUnlock', TitleUnlock); }
{ return this.belongsTo('TitleType', 'title_id'); }
identifier_body
titleUnlock.js
/* * Copyright (C) 2016 Max Prettyjohns * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is d...
() { return this.belongsTo('TitleType', 'title_id'); } }); return bookshelf.model('TitleUnlock', TitleUnlock); }
title
identifier_name
hummus-recipe-tests.ts
import Recipe = require('hummus-recipe'); import fs = require('fs'); // $ExpectType Recipe
version: 1.6, author: 'John Doe', title: 'Hummus Recipe', subject: 'A brand new PDF', }); // $ExpectType Recipe newDoc .createPage(595, 842) .text('Memento Mori', 100, 100) .endPage() .endPDF(); // $ExpectError newDoc.createPage('A5') .text('Memento Mori', 100, 100) .endPage() ...
const newDoc = new Recipe('new', 'test.pdf', {
random_line_split
Pair.js
/** * Pair. * * MIT License * Copyright (c) 2015 notrubp@gmail.com * * 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,...
* @class Pair * @param {*} first * @param {*} second */ var Pair = function(first, second) { this.first = first; this.second = second; } /** * Make a new pair. * @function make * @memberof Pair * @static * @param {*} first * @param {*} second * @returns {Pair} */ Pai...
random_line_split
cdp.py
# -*- coding: utf-8 -*- import fcntl import glob import json import os import random import shutil import socket import subprocess import sys import tempfile import time TEST_DIR = os.path.normpath(os.path.dirname(os.path.realpath(os.path.join(__file__, "..")))) def browser_path(headless=True): """Return path t...
(self, port): f = None try: f = open(os.path.join(tempfile.gettempdir(), ".cdp-%i.lock" % port), "w") fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) self._cdp_port_lockfile = f return True except (IOError, OSError): if f: ...
claim_port
identifier_name
cdp.py
# -*- coding: utf-8 -*- import fcntl import glob import json import os import random import shutil import socket import subprocess import sys import tempfile import time TEST_DIR = os.path.normpath(os.path.dirname(os.path.realpath(os.path.join(__file__, "..")))) def browser_path(headless=True): """Return path t...
Exit with an error if none is found. """ if headless: g = glob.glob("/usr/lib*/chromium-browser/headless_shell") if g: return g[0] p = subprocess.check_output("which chromium-browser || which chromium || which google-chrome || true", shell=True).strip() if p: re...
- "chromium-browser", "chromium", or "google-chrome" in $PATH (distro package) - node_modules/chromium/lib/chromium/chrome-linux/chrome (npm install chromium)
random_line_split
cdp.py
# -*- coding: utf-8 -*- import fcntl import glob import json import os import random import shutil import socket import subprocess import sys import tempfile import time TEST_DIR = os.path.normpath(os.path.dirname(os.path.realpath(os.path.join(__file__, "..")))) def browser_path(headless=True): """Return path t...
return self._browser_path def start(self): environ = os.environ.copy() if self.lang: environ["LC_ALL"] = self.lang self.cur_frame = None # allow attaching to external browser cdp_port = None if "TEST_CDP_PORT" in os.environ: p = int...
self._browser_path = browser_path(self.headless)
conditional_block
cdp.py
# -*- coding: utf-8 -*- import fcntl import glob import json import os import random import shutil import socket import subprocess import sys import tempfile import time TEST_DIR = os.path.normpath(os.path.dirname(os.path.realpath(os.path.join(__file__, "..")))) def browser_path(headless=True): """Return path t...
try: del kwargs["no_trace"] except KeyError: pass cmd = fn + "(" + json.dumps(kwargs) + ")" # frame support for Runtime.evaluate(): map frame name to # executionContextId and insert into argument object; this must not be quoted # see "Frame track...
def __init__(self, lang=None, headless=True, verbose=False, trace=False, inject_helpers=[]): self.lang = lang self.timeout = 60 self.valid = False self.headless = headless self.verbose = verbose self.trace = trace self.inject_helpers = inject_helpers self....
identifier_body
communication.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
#[derive(Debug)] pub enum Error { BadStatus, Timeout, Parse, } type RpcSender = Mutex<mpsc::Sender<(hyper::Request, oneshot::Sender<Result<hyper::Chunk, Error>>)>>; pub struct RpcClient { sender: RpcSender, uri: RwLock<hyper::Uri>, } impl RpcClient { pub fn create(upstream: &UpStream) -> ...
use jsonrpc_types::{rpc_request, rpc_types}; use libproto::blockchain::UnverifiedTransaction;
random_line_split
communication.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
else { Err(Error::BadStatus) } }
{ Ok(result.hash) }
conditional_block
communication.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
(upstream: &UpStream) -> Result<rpc_types::MetaData, Error> { let height = rpc_types::BlockNumber::latest(); let req = rpc_request::GetMetaDataParams::new(height).into_request(1); let result = rpc_send_and_get_result_from_reply!(upstream, req, rpc_types::MetaData); Ok(result) } pub fn cita_send_transac...
cita_get_metadata
identifier_name
communication.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
} // Pack the result type into a reply type, and parse result from the reply, and return the result. // The user of this macro do NOT have to care about the inner reply type. macro_rules! rpc_send_and_get_result_from_reply { ($upstream:ident, $request:ident, $result_type:path) => {{ define_reply_type!(Rep...
{ let uri = { self.uri.read().clone() }; trace!("Send body {:?} to {:?}.", body, uri); let mut req = hyper::Request::new(hyper::Method::Post, uri); req.headers_mut().set(hyper::header::ContentType::json()); req.set_body(body.to_owned()); let (tx, rx) = oneshot::channel();...
identifier_body
NetworkInformation.d.ts
// Type definitions for Apache Cordova Network Information plugin. // Project: https://github.com/apache/cordova-plugin-network-information // Definitions by: Microsoft Open Technologies, Inc. <http://msopentech.com> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // // Copyright (c) Microsoft Open ...
* Connection.CELL_4G * Connection.CELL * Connection.NONE */ type: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Connection: { UNKNOWN: string; ETHERNET: string; WIFI: string; CELL_2...
random_line_split
functional-struct-update-noncopyable.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} fn main() { let a = A { y: Arc::new(1), x: Arc::new(2) }; let _b = A { y: Arc::new(3), ..a }; //~ ERROR cannot move out of type `A` let _c = a; }
{ println!("x={}", *self.x); }
identifier_body
functional-struct-update-noncopyable.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ y: Arc<isize>, x: Arc<isize> } impl Drop for A { fn drop(&mut self) { println!("x={}", *self.x); } } fn main() { let a = A { y: Arc::new(1), x: Arc::new(2) }; let _b = A { y: Arc::new(3), ..a }; //~ ERROR cannot move out of type `A` let _c = a; }
A
identifier_name
functional-struct-update-noncopyable.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // issue 7327 use std::sync::Arc; struct A { y: Arc<isize>, x: Arc<isize> } impl Drop for A { fn drop(&mut self) { println!("x={}", *self.x); } } f...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
admin_geofinder.rs
::new(), admin_by_id: BTreeMap::new(), } } } impl FromIterator<Admin> for AdminGeoFinder { fn from_iter<I: IntoIterator<Item = Admin>>(admins: I) -> Self { let mut geofinder = AdminGeoFinder::default(); for admin in admins { geofinder.insert(admin); } ...
40., Some(ZoneType::StateDistrict), 2.,
random_line_split
admin_geofinder.rs
&mut self, admin: Admin) { use ordered_float::OrderedFloat; fn min(a: OrderedFloat<f32>, b: f64) -> f32 { a.0.min(down(b as f32)) } fn max(a: OrderedFloat<f32>, b: f64) -> f32 { a.0.max(up(b as f32)) } let rect = { let mut coords = mat...
nsert(
identifier_name
admin_geofinder.rs
(a: OrderedFloat<f32>, b: f64) -> f32 { a.0.min(down(b as f32)) } fn max(a: OrderedFloat<f32>, b: f64) -> f32 { a.0.max(up(b as f32)) } let rect = { let mut coords = match admin.boundary { Some(ref b) => b.0.iter().flat_map(|poly| (pol...
} // the goal is that f in [down(f as f32) as f64, up(f as f32) as f64] fn down(f: f32) -> f32 { f - (f * ::std::f32::EPSILON).abs() } fn up(f: f32) -> f32 { f + (f * ::std::f32::EPSILON).abs() } #[test] fn test_up_down() { for &f in [1.0f64, 0., -0., -1., 0.1, -0.1, 0.9, -0.9, 42., -42.].iter() { ...
let mut geofinder = AdminGeoFinder::default(); for admin in admins { geofinder.insert(admin); } geofinder }
identifier_body
yii2-yandex-map.js
ivphpanYandexMap = { id:'', idCords:'#ivphpanYandexMapCords', options: { center: [], zoom: 16, controls: ["zoomControl", "fullscreenControl","geolocationControl"] }, map:'', cords:[], points:[], events:[], init:function(id,options) { ivphpanYandexMap...
for(key in cords) { cords[key]=parseFloat(cords[key]); } ivphpanYandexMap.map.panTo(cords); } };
{ var cords = typeof cords!='undefined' ? cords : ivphpanYandexMap.cords;
random_line_split
yii2-yandex-map.js
ivphpanYandexMap = { id:'', idCords:'#ivphpanYandexMapCords', options: { center: [], zoom: 16, controls: ["zoomControl", "fullscreenControl","geolocationControl"] }, map:'', cords:[], points:[], events:[], init:function(id,options) { ivphpanYandexMa...
ymaps.ready(function(){ ivphpanYandexMap.map = new ymaps.Map(ivphpanYandexMap.id,ivphpanYandexMap.options); ivphpanYandexMap.map.events.add('click', function (e) { // Получение координат щелчка ivphpanYandexMap.cords = e.get('coords'); ...
{ ivphpanYandexMap.options = options; }
conditional_block
dates.js
/** * @arliteam/arli v0.2.1 * https://github.com/arliteam/arli * * Copyright (c) Mohamed Elkebir (https://getsupercode.com) * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ "use strict"; exports.__esModule = true; /** * ...
* * https://en.wikipedia.org/wiki/Date_format_by_country * * @example * 12/30/2000 | 12/30/99 * 12-30-2000 | 12-30-99 * 12.30.2000 | 12.30.99 * 12 30 2000 | 12 30 99 * * @param date A string of date to be tested */ exports.isDateMDY = function (date) { var pattern = /^(12|11|10|0[1-9])(\/|\.|-| )(31|30|(...
* Date format: MM/DD/YY[YY] MM.DD.YY[YY] MM-DD-YY[YY] MM DD YY[YY]
random_line_split
Fields.ts
import { FieldPresence, FieldProcessorAdt, FieldSchema, ValueSchema } from '@ephox/boulder'; import { Arr, Fun, Option, Result } from '@ephox/katamari'; import * as Debugging from '../debugging/Debugging'; import * as MenuMarkers from '../menu/util/MenuMarkers'; const _initSize: FieldProcessorAdt = FieldSchema.strict...
// We care about where the handler was declared (in terms of which schema) const trace = Debugging.getTrace(); return FieldSchema.field( fieldName, fieldName, presence, // Apply some wrapping to their supplied function ValueSchema.valueOf((f) => { return Result.value((...args: any[]) => ...
return FieldSchema.strictObjOf('markers', Arr.map(required, FieldSchema.strict)); }; const onPresenceHandler = (label: string, fieldName: string, presence: any): FieldProcessorAdt => {
random_line_split
imagenet_utils.py
from __future__ import absolute_import, division, print_function ''' From https://github.com/fchollet/deep-learning-models ''' import json from keras.utils.data_utils import get_file from keras import backend as K import numpy as np CLASS_INDEX = None CLASS_INDEX_PATH = 'https://s3.amazonaws.com/deep-learning-m...
def preprocess_input(x, dim_ordering='default', mean=None, std=None): if dim_ordering == 'default': dim_ordering = K.image_dim_ordering() assert dim_ordering in {'tf', 'th'} if mean is not None: x = x - np.array(mean, dtype='float32') if std is not None: if 0.0 in std: ...
random_line_split
imagenet_utils.py
from __future__ import absolute_import, division, print_function ''' From https://github.com/fchollet/deep-learning-models ''' import json from keras.utils.data_utils import get_file from keras import backend as K import numpy as np CLASS_INDEX = None CLASS_INDEX_PATH = 'https://s3.amazonaws.com/deep-learning-m...
(preds, top=5): global CLASS_INDEX if len(preds.shape) != 2 or preds.shape[1] != 1000: raise ValueError('`decode_predictions` expects ' 'a batch of predictions ' '(i.e. a 2D array of shape (samples, 1000)). ' 'Found array with sh...
decode_imagenet_predictions
identifier_name
imagenet_utils.py
from __future__ import absolute_import, division, print_function ''' From https://github.com/fchollet/deep-learning-models ''' import json from keras.utils.data_utils import get_file from keras import backend as K import numpy as np CLASS_INDEX = None CLASS_INDEX_PATH = 'https://s3.amazonaws.com/deep-learning-m...
global CLASS_INDEX if len(preds.shape) != 2 or preds.shape[1] != 1000: raise ValueError('`decode_predictions` expects ' 'a batch of predictions ' '(i.e. a 2D array of shape (samples, 1000)). ' 'Found array with shape: ' + str(preds.s...
identifier_body
imagenet_utils.py
from __future__ import absolute_import, division, print_function ''' From https://github.com/fchollet/deep-learning-models ''' import json from keras.utils.data_utils import get_file from keras import backend as K import numpy as np CLASS_INDEX = None CLASS_INDEX_PATH = 'https://s3.amazonaws.com/deep-learning-m...
return x def decode_imagenet_predictions(preds, top=5): global CLASS_INDEX if len(preds.shape) != 2 or preds.shape[1] != 1000: raise ValueError('`decode_predictions` expects ' 'a batch of predictions ' '(i.e. a 2D array of shape (samples, 1000)). ...
if dim_ordering == 'th': x[:, 0, :, :] -= 103.939 x[:, 1, :, :] -= 116.779 x[:, 2, :, :] -= 123.68 # 'RGB'->'BGR' x = x[:, ::-1, :, :] else: x[:, :, :, 0] -= 103.939 x[:, :, :, 1] -= 116.779 x[:, :, :, 2] -= 123.68 ...
conditional_block
log.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
line, to_safe_cstring(function).as_ptr(), code, to_safe_cstring(message).as_ptr()); } } // Fall back if the Suricata C context is not registered which is // the case when Rust unit tests are running. // // We don't log the time...
to_safe_cstring(filename).as_ptr(),
random_line_split
log.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
() -> i32 { unsafe { LEVEL } } pub fn log_set_level(level: i32) { unsafe { LEVEL = level; } } #[no_mangle] pub extern "C" fn rs_log_set_level(level: i32) { log_set_level(level); } fn basename(filename: &str) -> &str { let path = Path::new(filename); for os_str in path.file...
get_log_level
identifier_name
log.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
// This macro returns the function name. // // This macro has been borrowed from https://github.com/popzxc/stdext-rs, which // is released under the MIT license as there is currently no macro in Rust // to provide the function name. #[cfg(feature = "function-macro")] #[macro_export(local_inner_macros)] macro_rules!fu...
{ let filename = basename(file); sc_log_message(level, filename, line, function, code, message); }
identifier_body
constants.py
EC2_INSTANCE_TYPES = [ 't2.micro', 't2.small', 't2.medium',
] RDS_INSTANCE_TYPES = [ 'db.t2.micro', 'db.t2.small', 'db.t2.medium', 'db.t2.large' ] ELASTICACHE_INSTANCE_TYPES = [ 'cache.m1.small' ] ALLOW_ALL_CIDR = '0.0.0.0/0' VPC_CIDR = '10.0.0.0/16' GRAPHITE = 2003 GRAPHITE_WEB = 8080 HTTP = 80 HTTPS = 443 KIBANA = 5601 POSTGRESQL = 5432 REDIS = 6379 RE...
't2.large', 'r4.large'
random_line_split
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # nala - file/directory watcher # Copyright (C) 2013 Eugenio "g7" Paolantonio <me@medesimo.eu> # # This program is free software: you can redistribute it and/or modify
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along ...
# it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #
random_line_split
lib.rs
use std::f64::consts::PI; /// Calculates the volume of the n-sphere. pub fn sphere_volume(radius: f64, dim: u64) -> f64
#[test] fn volume_of_1_sphere_works() { for radius in (0..5000000).map(|n| n as f64 / 7000.) { let expected = PI * radius.powi(2); let actual = sphere_volume(radius, 2); assert!(equals(expected, actual, 0.0001, 5), "Expected: {}, Actual: {}", expected, actual); } } #[test] fn volume_o...
{ let gamma = if dim % 2 == 0 { // This works because dim / 2 is a whole number. fact(dim / 2) as f64 } else { // This works because the function is gamma(1/2 + n) where n = dim / 2 + 1 let n = dim / 2 + 1; (fact(2 * n) as f64 / (4u64.pow(n as u32) * fact(n)) as f64) * PI...
identifier_body
lib.rs
use std::f64::consts::PI; /// Calculates the volume of the n-sphere. pub fn sphere_volume(radius: f64, dim: u64) -> f64 { let gamma = if dim % 2 == 0 { // This works because dim / 2 is a whole number. fact(dim / 2) as f64 } else { // This works because the function is gamma(1/2 + n) whe...
let a_i64 = unsafe{::std::mem::transmute::<_, i64>(a)}; let b_i64 = unsafe{::std::mem::transmute::<_, i64>(b)}; let ulps_diff = i64::abs(a_i64 - b_i64); return ulps_diff <= max_ulps_diff; } #[inline] fn fact(n: u64) -> u64 { //TODO: This could be made faster with better algorithm, but it's called ...
{ return false; }
conditional_block
lib.rs
use std::f64::consts::PI; /// Calculates the volume of the n-sphere. pub fn sphere_volume(radius: f64, dim: u64) -> f64 { let gamma = if dim % 2 == 0 {
// This works because dim / 2 is a whole number. fact(dim / 2) as f64 } else { // This works because the function is gamma(1/2 + n) where n = dim / 2 + 1 let n = dim / 2 + 1; (fact(2 * n) as f64 / (4u64.pow(n as u32) * fact(n)) as f64) * PI.sqrt() }; (PI.powf(0.5 * di...
random_line_split
lib.rs
use std::f64::consts::PI; /// Calculates the volume of the n-sphere. pub fn sphere_volume(radius: f64, dim: u64) -> f64 { let gamma = if dim % 2 == 0 { // This works because dim / 2 is a whole number. fact(dim / 2) as f64 } else { // This works because the function is gamma(1/2 + n) whe...
(a: f64, b: f64, max_diff: f64, max_ulps_diff: i64) -> bool { let diff = f64::abs(a - b); if diff <= max_diff { return true; } if a.is_sign_positive() && !b.is_sign_positive() { return false; } let a_i64 = unsafe{::std::mem::transmute::<_, i64>(a)}; let b_i64 = unsafe{::std::...
equals
identifier_name
def.rs
#[test] fn parse_macro_def_no_params() { super::test_parser( r#" <marker type="NODE_MACRO_DEF">macro test<marker type="NODE_MACRO_PARAM_LIST">()</marker> { }</marker> "#, ) } #[test] fn parse_macro_def() { super::test_parser( r#" <marker type="NODE_MACRO_DEF">mac...
#[test] fn parse_var_with_initializer() { super::test_parser( r#" <marker type="NODE_VARIABLE_DEF">type_attribute a = <marker type="NODE_BINARY_EXPR">a | b</marker>;</marker> "#, ) }
{ super::test_parser( r#" <marker type="NODE_VARIABLE_DEF">type a;</marker> "#, ) }
identifier_body
def.rs
#[test] fn parse_macro_def_no_params() { super::test_parser( r#" <marker type="NODE_MACRO_DEF">macro test<marker type="NODE_MACRO_PARAM_LIST">()</marker> { }</marker> "#, ) } #[test] fn parse_macro_def() { super::test_parser( r#" <marker type="NODE_MACRO_DEF">mac...
() { super::test_parser( r#" <marker type="KW_ABSTRACT">abstract</marker> block test {} "#, ); } #[test] fn parse_abstract_container_with_extends_list() { super::test_parser( r#" abstract block test <marker type="NODE_EXTENDS_LIST">extends abc</marker> {} "#, ); ...
parse_abstract_container_def
identifier_name
def.rs
#[test] fn parse_macro_def_no_params() { super::test_parser( r#" <marker type="NODE_MACRO_DEF">macro test<marker type="NODE_MACRO_PARAM_LIST">()</marker> { }</marker> "#, ) } #[test] fn parse_macro_def() { super::test_parser( r#" <marker type="NODE_MACRO_DEF">mac...
}
random_line_split
client_basics.rs
extern crate riak; use riak::Client; use riak::bucket::{BucketProps, BucketTypeProps}; use riak::object::{DeleteObjectReq, FetchObjectReq, ObjectContent, StoreObjectReq}; use riak::yokozuna::{SearchQuery, YokozunaIndex}; use std::fs::File; use std::io::Read; #[test] fn test_basics() { // connect and ping let ...
} assert_eq!(lives_on_nodes, 3); assert!(has_primary_node); // set properties for a bucket type let mut bucket_props = BucketTypeProps::new("testbuckettype"); bucket_props.set_backend("leveldb"); riak.set_bucket_type_properties(bucket_props).unwrap(); // get the properties back for a ...
{ has_primary_node = true; }
conditional_block
client_basics.rs
extern crate riak; use riak::Client; use riak::bucket::{BucketProps, BucketTypeProps}; use riak::object::{DeleteObjectReq, FetchObjectReq, ObjectContent, StoreObjectReq}; use riak::yokozuna::{SearchQuery, YokozunaIndex}; use std::fs::File; use std::io::Read; #[test] fn test_basics()
// store an object let contents = ObjectContent::new("this is a test".as_bytes()); let mut req = StoreObjectReq::new("testbucket", contents); req.set_key("testkey"); riak.store_object(req).unwrap(); // fetch an object let req = FetchObjectReq::new("testbucket", "testkey"); let object =...
{ // connect and ping let mut riak = Client::new("10.0.0.2:8087").unwrap(); riak.ping().unwrap(); // get the server info let (node, version) = riak.server_info().unwrap(); println!("connected to node {} running Riak version {}", node, version); // set bucket prope...
identifier_body
client_basics.rs
extern crate riak; use riak::Client; use riak::bucket::{BucketProps, BucketTypeProps}; use riak::object::{DeleteObjectReq, FetchObjectReq, ObjectContent, StoreObjectReq}; use riak::yokozuna::{SearchQuery, YokozunaIndex}; use std::fs::File; use std::io::Read; #[test] fn
() { // connect and ping let mut riak = Client::new("10.0.0.2:8087").unwrap(); riak.ping().unwrap(); // get the server info let (node, version) = riak.server_info().unwrap(); println!("connected to node {} running Riak version {}", node, version); // set bucket pr...
test_basics
identifier_name
client_basics.rs
extern crate riak;
use riak::yokozuna::{SearchQuery, YokozunaIndex}; use std::fs::File; use std::io::Read; #[test] fn test_basics() { // connect and ping let mut riak = Client::new("10.0.0.2:8087").unwrap(); riak.ping().unwrap(); // get the server info let (node, version) = riak.server_info().unwrap(); println!(...
use riak::Client; use riak::bucket::{BucketProps, BucketTypeProps}; use riak::object::{DeleteObjectReq, FetchObjectReq, ObjectContent, StoreObjectReq};
random_line_split
noIrregularWhitespaceRule.ts
import * as ts from 'typescript'; import * as Lint from 'tslint/lib/lint'; export class Rule extends Lint.Rules.AbstractRule { public static RULE_NAME = 'no-irregular-whitespace'; public static FAILURE_STRING = 'irregular whitespace not allowed'; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[]
} class NoIrregularWhitespaceWalker extends Lint.RuleWalker { private IRREGULAR_WHITESPACE = /[\u0085\u00A0\ufeff\f\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u202f\u205f\u3000]+/mg; private IRREGULAR_LINE_TERMINATORS = /[\u2028\u2029]/mg; protected visitSourceF...
{ const walker = new NoIrregularWhitespaceWalker(sourceFile, this.getOptions()); return this.applyWithWalker(walker); }
identifier_body
noIrregularWhitespaceRule.ts
import * as ts from 'typescript'; import * as Lint from 'tslint/lib/lint'; export class
extends Lint.Rules.AbstractRule { public static RULE_NAME = 'no-irregular-whitespace'; public static FAILURE_STRING = 'irregular whitespace not allowed'; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { const walker = new NoIrregularWhitespaceWalker(sourceFile, this.getOptions()); return th...
Rule
identifier_name
noIrregularWhitespaceRule.ts
import * as ts from 'typescript'; import * as Lint from 'tslint/lib/lint'; export class Rule extends Lint.Rules.AbstractRule { public static RULE_NAME = 'no-irregular-whitespace'; public static FAILURE_STRING = 'irregular whitespace not allowed'; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { ...
match = this.IRREGULAR_LINE_TERMINATORS.exec(line); while (match) { this.addFailure(this.createFailure(node.getPositionOfLineAndCharacter(i, match.index), 1, Rule.FAILURE_STRING)); match = this.IRREGULAR_LINE_TERMINATORS.exec(line); } }); } }
{ this.addFailure(this.createFailure(node.getPositionOfLineAndCharacter(i, match.index), 1, Rule.FAILURE_STRING)); match = this.IRREGULAR_WHITESPACE.exec(line); }
conditional_block
noIrregularWhitespaceRule.ts
import * as ts from 'typescript'; import * as Lint from 'tslint/lib/lint'; export class Rule extends Lint.Rules.AbstractRule { public static RULE_NAME = 'no-irregular-whitespace'; public static FAILURE_STRING = 'irregular whitespace not allowed'; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { ...
if (failure.getRuleName() === Rule.RULE_NAME) { if (failure.getStartPosition().getPosition() >= start && failure.getEndPosition().getPosition() <= end) { failures.splice(i, 1); } } } } private validateIrregularWhitespace(node: ts.SourceFile) { const lines = node.text....
for (let i = failures.length - 1; i >= 0; i--) { let failure = failures[i];
random_line_split
test_udp_socket.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; use std::str; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl UdpHandl...
if events.is_writable() { match token { SENDER => { let addr = self.rx.local_addr().unwrap(); let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap() .unwrap(); ...
{ match token { LISTENER => { debug!("We are receiving a datagram now..."); let (cnt, _) = unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()).unwrap() .unwrap() ...
conditional_block
test_udp_socket.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; use std::str; use localhost; const LISTENER: Token = Token(0); const SENDER: Token = Token(1); pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl UdpHandl...
(&mut self, event_loop: &mut EventLoop<UdpHandler>, token: Token, events: EventSet) { if events.is_readable() { match token { LISTENER => { debug!("We are receiving a datagram now..."); let (cnt, _) = unsafe { self.rx.r...
ready
identifier_name
test_udp_socket.rs
use mio::*; use mio::udp::*; use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; use std::str; use localhost;
pub struct UdpHandler { tx: UdpSocket, rx: UdpSocket, msg: &'static str, buf: SliceBuf<'static>, rx_buf: RingBuf } impl UdpHandler { fn new(tx: UdpSocket, rx: UdpSocket, msg : &'static str) -> UdpHandler { UdpHandler { tx: tx, rx: rx, msg: msg, ...
const LISTENER: Token = Token(0); const SENDER: Token = Token(1);
random_line_split
LocationHelper.js
var LocationHelper = function() { var instance = null; var osname = Ti.Platform.osname, version = Ti.Platform.version, height = Ti.Platform.displayCaps.platformHeight, width = Ti.Platform.displayCaps.platformWidth; var self = { isIOS: (osname === 'iphone') || (osname === 'ipad'), isAndroid: (osname ==...
minUpdateDistance : 0.0, minUpdateTime : self.minUpdateTime }); Ti.Geolocation.Android.addLocationProvider(providerGps); Ti.Geolocation.Android.manualMode = true; Ti.Geolocation.addEventListener('location', self.onLocationChanged); } else { alert('Please enable location services'); ...
name : Ti.Geolocation.PROVIDER_GPS,
random_line_split
LocationHelper.js
var LocationHelper = function() { var instance = null; var osname = Ti.Platform.osname, version = Ti.Platform.version, height = Ti.Platform.displayCaps.platformHeight, width = Ti.Platform.displayCaps.platformWidth; var self = { isIOS: (osname === 'iphone') || (osname === 'ipad'), isAndroid: (osname ==...
else { Ti.API.info('coords: ' + JSON.stringify(e.coords)); Ti.App.fireEvent('zwarm.location.updated', e.coords); self.updateReceived = true; } }; // PUBLIC FUNCTION /** * start listening for continuous location updates */ self.start = function() { if(self.isIOS) { // iOS if(Ti.Geolocation....
{ Ti.API.info('error:' + JSON.stringify(e.error)); }
conditional_block
util.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * The global object. * @type {!Object} */ const global = this; // TODO(estade): This should be removed and calls replaced with cr.isMac const ...
* @param {string} name The name of the message to send. * @param {!Array} params The parameters to send. * @param {string} callbackName The name of the function that the backend calls. * @param {!Function} The function to call. */ function chromeSend(name, params, callbackName, callback) { var old = global[callb...
/** * Calls chrome.send with a callback and restores the original afterwards.
random_line_split
util.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * The global object. * @type {!Object} */ const global = this; // TODO(estade): This should be removed and calls replaced with cr.isMac const ...
(s) { // http://www.w3.org/TR/css3-values/#uris // Parentheses, commas, whitespace characters, single quotes (') and double // quotes (") appearing in a URI must be escaped with a backslash var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1'); // WebKit has a bug when it comes to URLs that end with \ // ht...
url
identifier_name
util.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * The global object. * @type {!Object} */ const global = this; // TODO(estade): This should be removed and calls replaced with cr.isMac const ...
function swapDomNodes(a, b) { var afterA = a.nextSibling; if (afterA == b) { swapDomNodes(b, a); return; } var aParent = a.parentNode; b.parentNode.replaceChild(a, b); aParent.insertBefore(b, afterA); } // Handle click on a link. If the link points to a chrome: or file: url, then // call into the...
{ var last = false; while (node != null && !(last = predicate(node))) { node = node.parentNode; } return last ? node : null; }
identifier_body
rsa-isolement.js
var mongoose = require('mongoose'); var es = require('event-stream'); var config = require('../lib/config/config'); var _ = require('lodash'); require('../lib/config/mongoose')(mongoose, config); var Situation = mongoose.model('Situation'); Situation.find({ status: 'test' }).stream() .pipe(es.map(function (situa...
situation.save(function (err) { if (err) { console.log('Cannot save migrated situation %s', situation.id); console.trace(err); } else if (isSituationUpdated) console.log('Situation migrée'); done(); }); ...
{ situation.individus[0].isolementRecent = true; isSituationUpdated = true; }
conditional_block
rsa-isolement.js
var mongoose = require('mongoose'); var es = require('event-stream'); var config = require('../lib/config/config'); var _ = require('lodash'); require('../lib/config/mongoose')(mongoose, config); var Situation = mongoose.model('Situation');
.pipe(es.map(function (situation, done) { var isSituationUpdated = false; hasConjoint = _.find(situation.individus, { role: 'conjoint' }); hasEnfant = _.find(situation.individus, { role: 'enfant' }); if (hasEnfant && ! hasConjoint) { situation.individus[0].isolementRece...
Situation.find({ status: 'test' }).stream()
random_line_split
lub-glb-with-unbound-infer-var.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let a_f: fn(_) = |_| (); let b_f: fn(_) = |_| (); let c_f = match 22 { 0 => a_f, _ => b_f, }; c_f(4); }
identifier_body
lub-glb-with-unbound-infer-var.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// in-progress PR. fn main() { let a_f: fn(_) = |_| (); let b_f: fn(_) = |_| (); let c_f = match 22 { 0 => a_f, _ => b_f, }; c_f(4); }
random_line_split
lub-glb-with-unbound-infer-var.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let a_f: fn(_) = |_| (); let b_f: fn(_) = |_| (); let c_f = match 22 { 0 => a_f, _ => b_f, }; c_f(4); }
main
identifier_name
table.py
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
(values, minimum_width=0): max_width = len(max(values, key=len)) if values else minimum_width return max_width if max_width > minimum_width else minimum_width class PropertyValueTable(formatters.Formatter): @classmethod def format(cls, subject, *args, **kwargs): attributes = kwargs.ge...
_get_required_column_width
identifier_name
table.py
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
else: # If only 1 width value is provided then # apply it to all columns else fix at 28. width = widths[0] if len(widths) == 1 else 28 columns = zip(attributes, [width for i in range(0, len(attributes))]) # Format result to tabl...
columns = zip(attributes, widths)
conditional_block
table.py
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
@staticmethod def _get_required_column_width(values, minimum_width=0): max_width = len(max(values, key=len)) if values else minimum_width return max_width if max_width > minimum_width else minimum_width class PropertyValueTable(formatters.Formatter): @classmethod def format(cls, sub...
if not name: return None friendly_name = name.replace('_', ' ').replace('.', ' ').capitalize() return friendly_name
identifier_body
table.py
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
table.max_width[column[0]] = column[1] table.padding_width = 1 table.align = 'l' table.valign = 't' for entry in entries: # TODO: Improve getting values of nested dict. values = [] for field_name in table.field_names: if '.'...
# Format result to table. table = PrettyTable() for column in columns: table.field_names.append(column[0])
random_line_split
grpc_version.py
# Copyright 2016, Google 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIA...
random_line_split
main.rs
use std::io::Write; use std::str::FromStr; fn main()
fn gcd(mut n: u64, mut m: u64) -> u64 { assert!(n != 0 && m != 0); while m != 0 { if m < n { let t = m; m = n; n = t; } m = m % n; } n } #[test] fn test_gcd() { assert_eq!(gcd(2 * 3 * 5 * 11 * 17, 3 * 7 * 11 * 13 * 19), 3 * 11); }
{ let mut numbers = Vec::new(); for arg in std::env::args().skip(1) { numbers.push(u64::from_str(&arg).expect("error parsing argument")); } if numbers.len() == 0 { writeln!(std::io::stderr(), "Usage: gcd NUMBER ...").unwrap(); std::process::exit(1); } let mut d = numbe...
identifier_body
main.rs
use std::io::Write; use std::str::FromStr; fn
() { let mut numbers = Vec::new(); for arg in std::env::args().skip(1) { numbers.push(u64::from_str(&arg).expect("error parsing argument")); } if numbers.len() == 0 { writeln!(std::io::stderr(), "Usage: gcd NUMBER ...").unwrap(); std::process::exit(1); } let mut d = nu...
main
identifier_name
main.rs
use std::io::Write; use std::str::FromStr; fn main() { let mut numbers = Vec::new(); for arg in std::env::args().skip(1) { numbers.push(u64::from_str(&arg).expect("error parsing argument")); } if numbers.len() == 0 { writeln!(std::io::stderr(), "Usage: gcd NUMBER ...").unwrap(); ...
m = m % n; } n } #[test] fn test_gcd() { assert_eq!(gcd(2 * 3 * 5 * 11 * 17, 3 * 7 * 11 * 13 * 19), 3 * 11); }
{ let t = m; m = n; n = t; }
conditional_block
main.rs
use std::io::Write; use std::str::FromStr; fn main() { let mut numbers = Vec::new(); for arg in std::env::args().skip(1) { numbers.push(u64::from_str(&arg).expect("error parsing argument")); } if numbers.len() == 0 { writeln!(std::io::stderr(), "Usage: gcd NUMBER ...").unwrap(); ...
} println!("The greatest common divisor of {:?} is {}", numbers, d); } fn gcd(mut n: u64, mut m: u64) -> u64 { assert!(n != 0 && m != 0); while m != 0 { if m < n { let t = m; m = n; n = t; } m = m % n; } n } #[test] fn test_gcd() { ...
let mut d = numbers[0]; for m in &numbers[1..] { d = gcd(d, *m);
random_line_split
docker_image_availability.py
ries (according to inventory vars) that docker will try for unscoped images regs = self.ensure_list("openshift_docker_additional_registries") # currently one of these registries is added whether the user wants it or not. deployment_type = self.get_var("openshift_deployment_type") if depl...
continue # blocked will never be consulted
conditional_block
docker_image_availability.py
without waiting to pull them. dependencies = ["python-docker-py", "skopeo"] # command for checking if remote registries have an image, without docker pull skopeo_command = "timeout 10 skopeo inspect --tls-verify={tls} {creds} docker://{registry}/{image}" skopeo_example_command = "skopeo inspect [--tls-...
available_images
identifier_name
docker_image_availability.py
scoped images regs = self.ensure_list("openshift_docker_additional_registries") # currently one of these registries is added whether the user wants it or not. deployment_type = self.get_var("openshift_deployment_type") if deployment_type == "origin" and "docker.io" not in regs: ...
for registry in registries: if registry in self.registries["blocked"]: continue # blocked will never be consulted if registry not in self.reachable_registries:
random_line_split
docker_image_availability.py
look for images available remotely without waiting to pull them. dependencies = ["python-docker-py", "skopeo"] # command for checking if remote registries have an image, without docker pull skopeo_command = "timeout 10 skopeo inspect --tls-verify={tls} {creds} docker://{registry}/{image}" skopeo_exampl...
"""Return the task var as a list.""" # https://bugzilla.redhat.com/show_bug.cgi?id=1497274 # If the result was a string type, place it into a list. We must do this # as using list() on a string will split the string into its characters. # Otherwise cast to a list as was done previously. ...
identifier_body
materialize-css-tests.ts
=> { alert('Opened'); } }); $(collapseHtml).collapsible('destroy'); $(collapseHtml).collapsible('open', 0); // Dialogs - Toasts Materialize.toast('I am a toast!', 4000); Materialize.toast('I am a toast!', 3000, 'rounded');
// Dialogs - Tooltip let tooltipHtml = '<a class="btn tooltipped" data-position="bottom" data-delay="50" data-tooltip="I am tooltip">Hover me!</a>'; $(tooltipHtml).tooltip(); $(tooltipHtml).tooltip({ delay: 100 }); $(tooltipHtml).tooltip('remove'); // DropDown let dropDownHtml = '<a class="dropdown-button btn" data-be...
Materialize.toast('I am a toast!', 3000, 'rounded', () => console.log('callback')); let $toastContent = $('<span>I am toast content</span>'); Materialize.toast($toastContent, 5000); Materialize.Toast.removeAll();
random_line_split
BeforeInputEventUtils.ts
import { TinyAssertions, TinyContentActions, TinySelections } from '@ephox/wrap-mcagar';
import { NormalizedEvent } from 'tinymce/src/core/main/ts/events/EventUtils'; export const testBeforeInputEvent = (performEditAction: (editor: Editor) => void, eventType: string) => ( editor: Editor, setupHtml: string, setupPath: number[], setupOffset: number, expectedHtml: string, cancelBefo...
import { assert } from 'chai'; import Editor from 'tinymce/core/api/Editor'; import { EditorEvent } from 'tinymce/core/api/util/EventDispatcher'; import * as InsertNewLine from 'tinymce/core/newline/InsertNewLine';
random_line_split
BeforeInputEventUtils.ts
import { TinyAssertions, TinyContentActions, TinySelections } from '@ephox/wrap-mcagar'; import { assert } from 'chai'; import Editor from 'tinymce/core/api/Editor'; import { EditorEvent } from 'tinymce/core/api/util/EventDispatcher'; import * as InsertNewLine from 'tinymce/core/newline/InsertNewLine'; import { Normal...
}; editor.on('input', collect); editor.on('beforeinput', beforeInputCollect); editor.setContent(setupHtml); TinySelections.setCursor(editor, setupPath, setupOffset); performEditAction(editor); editor.off('beforeinput', beforeInputCollect); editor.off('input', collect); TinyAsserti...
{ event.preventDefault(); }
conditional_block
sectioned-form-section.component.ts
import { Component, Input, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { SkyVerticalTabComponent } from './../vertical-tabset/vertical-tab.component'; import { SkySectionedFormService } from './sectioned-form.service'; @Component({ selector: 'sky-sectioned-form-section', templateUrl: './sectioned-form-section.component.html', providers: [SkySectionedFormService], styleUrls...
import { Subject } from 'rxjs/Subject';
random_line_split
sectioned-form-section.component.ts
import { Component, Input, ViewChild, OnInit, OnDestroy } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { SkyVerticalTabComponent } from './../vertical-tabset/vertical-tab.component'; import { SkySectionedFormService } from './sectioned-form.service'; @Component({ selector: 'sky-se...
() { this.sectionedFormService.requiredChange .takeUntil(this._ngUnsubscribe) .subscribe((required: boolean) => this.fieldRequired = required); this.sectionedFormService.invalidChange .takeUntil(this._ngUnsubscribe) .subscribe((invalid: boolean) => this.fieldInvalid = invalid); } public ngOn...
ngOnInit
identifier_name
sectioned-form-section.component.ts
import { Component, Input, ViewChild, OnInit, OnDestroy } from '@angular/core'; import { Subject } from 'rxjs/Subject'; import { SkyVerticalTabComponent } from './../vertical-tabset/vertical-tab.component'; import { SkySectionedFormService } from './sectioned-form.service'; @Component({ selector: 'sky-se...
public ngOnDestroy() { this._ngUnsubscribe.next(); this._ngUnsubscribe.complete(); } }
{ this.sectionedFormService.requiredChange .takeUntil(this._ngUnsubscribe) .subscribe((required: boolean) => this.fieldRequired = required); this.sectionedFormService.invalidChange .takeUntil(this._ngUnsubscribe) .subscribe((invalid: boolean) => this.fieldInvalid = invalid); }
identifier_body
main.py
import web from web import form import socket print("http://" + socket.gethostbyname(socket.gethostname()) + ":8080") urls = ( '/','Login', '/page_one','Page_one', '/left', 'Left', '/right', 'Right', '/forward', 'Forward', '/start', 'Start', '/stop', ...
print("left") return "left" class Right: def GET(self): print("right") return "right" class Forward: def GET(self): print("forward") return "forward" class Start: def GET(self): print("start") return "start" class Backward...
return "123" class Left: def GET(self):
random_line_split
main.py
import web from web import form import socket print("http://" + socket.gethostbyname(socket.gethostname()) + ":8080") urls = ( '/','Login', '/page_one','Page_one', '/left', 'Left', '/right', 'Right', '/forward', 'Forward', '/start', 'Start', '/stop', ...
class Left: def GET(self): print("left") return "left" class Right: def GET(self): print("right") return "right" class Forward: def GET(self): print("forward") return "forward" class Start: def GET(self): print("start") ...
def GET(self): print("test") return "123"
identifier_body
main.py
import web from web import form import socket print("http://" + socket.gethostbyname(socket.gethostname()) + ":8080") urls = ( '/','Login', '/page_one','Page_one', '/left', 'Left', '/right', 'Right', '/forward', 'Forward', '/start', 'Start', '/stop', ...
: def GET(self): print("right") return "right" class Forward: def GET(self): print("forward") return "forward" class Start: def GET(self): print("start") return "start" class Backward: def GET(self): print("backward") r...
Right
identifier_name
main.py
import web from web import form import socket print("http://" + socket.gethostbyname(socket.gethostname()) + ":8080") urls = ( '/','Login', '/page_one','Page_one', '/left', 'Left', '/right', 'Right', '/forward', 'Forward', '/start', 'Start', '/stop', ...
class Page_one: def GET(self): return render.page_one() def POST(self): return render.page_one() class return_num: def GET(self): print("test") return "123" class Left: def GET(self): print("left") return "left" ...
session.logged_in = True return web.seeother('/page_one')
conditional_block
__init__.py
__VERSION__="ete2-2.2rev1026" # -*- coding: utf-8 -*- # #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://ete.cgenomics.org # # ETE is free software: you can redistribute it and/or modify it # under the t...
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public # License for more details. # # You should have received a copy of the GNU General Public License # along with ETE. If not, see <http://www.gnu.org/licenses/>. # # # ...
random_line_split
base.py
"""Common settings and globals.""" from os.path import abspath, basename, dirname, join, normpath from sys import path ########## PATH CONFIGURATION # Absolute filesystem path to the Django project directory: DJANGO_ROOT = dirname(dirname(abspath(__file__))) # Absolute filesystem path to the top-level project fold...
normpath(join(SITE_ROOT, 'templates')), ) ########## END TEMPLATE CONFIGURATION ########## MIDDLEWARE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes MIDDLEWARE_CLASSES = ( # Default Django middleware. 'django.middleware.common.CommonMiddleware', 'django.con...
TEMPLATE_DIRS = (
random_line_split
admin-article-pagebreak.es6.js
/** * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ (() => { 'use strict'; window.insertPagebreak = (editor) => { // Get the pagebreak title let title = document.getElementById('title'...
// Get the pagebreak toc alias -- not inserting for now don't know which attribute to use.. let alt = document.getElementById('alt').value; title = (title !== '') ? `title="${title}"` : ''; alt = (alt !== '') ? `alt="${alt}"` : ''; const tag = `<hr class="system-pagebreak" ${title} ${alt}>`; w...
{ // Something went wrong! window.parent.Joomla.Modal.getCurrent().close(); return false; }
conditional_block
admin-article-pagebreak.es6.js
/** * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ (() => { 'use strict'; window.insertPagebreak = (editor) => { // Get the pagebreak title
if (!window.parent.Joomla.getOptions('xtd-pagebreak')) { // Something went wrong! window.parent.Joomla.Modal.getCurrent().close(); return false; } // Get the pagebreak toc alias -- not inserting for now don't know which attribute to use.. let alt = document.getElementById('alt').valu...
let title = document.getElementById('title').value;
random_line_split
sale_order.py
('self', lambda value: value.id) def copy(self, default=None): if self.sale_order_template_id and self.sale_order_template_id.number_of_days > 0: default = dict(default or {}) default['validity_date'] = fields.Date.context_today(self) + timedelta(self.sale_order_template_id.number_of...
self.ensure_one() sale_order = self.order_id if sale_order.state not in ['draft', 'sent']: raise UserError(_('You cannot add options to a confirmed order.')) values = self._get_values_to_add_to_order() order_line = self.env['sale.order.line'].create(values) order_l...
identifier_body
sale_order.py
sale_order_template_id = fields.Many2one( 'sale.order.template', 'Quotation Template', readonly=True, check_company=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") sale_or...
sale_order_option_ids = fields.One2many('sale.order.option', 'line_id', 'Optional Products Lines') # Take the description on the order template if the product is present in it @api.onchange('product_id') def product_id_change(self): domain = super(SaleOrderLine, self).product_id_change() ...
class SaleOrderLine(models.Model): _inherit = "sale.order.line" _description = "Sales Order Line"
random_line_split
sale_order.py
sale_order_template_id = fields.Many2one( 'sale.order.template', 'Quotation Template', readonly=True, check_company=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") sale_or...
'customer_lead': self._get_customer_lead(line.product_id.product_tmpl_id), }) order_lines.append((0, 0, data)) self.order_line = order_lines self.order_line._compute_tax_id() # then, process the list of optional products from the template ...
data = self._compute_line_data_for_template_change(line) if line.product_id: price = line.product_id.lst_price discount = 0 if self.pricelist_id: pricelist_price = self.pricelist_id.with_context(uom=line.product_uom_id.id).get_product_pri...
conditional_block
sale_order.py
sale_order_template_id = fields.Many2one( 'sale.order.template', 'Quotation Template', readonly=True, check_company=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") sale_or...
(self, line): return { 'display_type': line.display_type, 'name': line.name, 'state': 'draft', } def _compute_option_data_for_template_change(self, option): price = option.product_id.lst_price discount = 0 if self.pricelist_id: ...
_compute_line_data_for_template_change
identifier_name
error.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(_err: ethkey::Error) -> Self { ErrorKind::Auth.into() } } impl From<crypto::Error> for Error { fn from(_err: crypto::Error) -> Self { ErrorKind::Auth.into() } } #[test] fn test_errors() { assert_eq!(DisconnectReason::ClientQuit, DisconnectReason::from_u8(8)); let mut r = DisconnectReason::DisconnectRequeste...
from
identifier_name
error.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
PeerNotFound { description("Peer not found"), display("Peer not found"), } #[doc = "Peer is disconnected"] Disconnect(reason: DisconnectReason) { description("Peer disconnected"), display("Peer disconnected: {}", reason), } #[doc = "Invalid node id"] InvalidNodeId { description("Invalid n...
display("Expired message"), } #[doc = "Peer not found"]
random_line_split
error.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} impl From<crypto::Error> for Error { fn from(_err: crypto::Error) -> Self { ErrorKind::Auth.into() } } #[test] fn test_errors() { assert_eq!(DisconnectReason::ClientQuit, DisconnectReason::from_u8(8)); let mut r = DisconnectReason::DisconnectRequested; for i in 0 .. 20 { r = DisconnectReason::from_u8(i); ...
{ ErrorKind::Auth.into() }
identifier_body
bert_embeddings.py
"""Contains function for calculating BERT embeddings""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json import re import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.dis...
(self, unique_id, text): self.unique_id = unique_id self.text = text class InputFeatures(object): """A single set of features of data.""" def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self....
__init__
identifier_name
bert_embeddings.py
"""Contains function for calculating BERT embeddings""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json import re import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.dis...
assert len(input_ids) == self.max_seq_length assert len(input_mask) == self.max_seq_length assert len(input_type_ids) == self.max_seq_length features.append( InputFeatures( unique_id=example.unique_id, tokens=toke...
input_ids.append(0) input_mask.append(0) input_type_ids.append(0)
conditional_block
bert_embeddings.py
"""Contains function for calculating BERT embeddings""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json import re
import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.distributed import DistributedSampler from pytorch_pretrained_bert.tokenization import BertTokenizer from pytorch_pretrained_bert.modeling import BertModel from scipy.spatial.distance import cosine, euclidean ...
random_line_split