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
run_tests.py
#!/usr/bin/env python import os import re import subprocess import sys import tempfile CC = "gcc" CFLAGS = "-fmax-errors=4 -std=c99 -pipe -D_POSIX_C_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-set-variable -Wno-unused-function -Wno-main".split...
src.close() def do_run(): if headers.mode == TestMode.disable: return TestMode.disable # make is for fags tc = os.path.join(workdir, "t.c") tcf = open(tc, "w") tempfiles.append(tc) res = subprocess.call(["./main", "cg_c", filename], stdout=tcf) ...
raise Exception("Unknown header '%s'" % name)
conditional_block
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn node_names_mentioned(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body...
} first = false; res.push_str(&unparse_mbe(&*sub_pat, actl, &marched_ctxt, s)); } res } (&Scope(ref form, _), &Node(ref form_actual, ref body, _)) => { if form == form_actual { unparse_mbe(&*form.grammar,...
if !first { res.push(' ');
random_line_split
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn node_names_mentioned(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body...
// TODO: this really ought to notice when `actl` is ill-formed for `pat`. match (pat, actl) { (&Named(name, ref body), _) => { // TODO: why does the `unwrap_or` case happen once after each variable is printed? unparse_mbe(&*body, context.get_leaf(name).unwrap_or(&ast!((at ""))).c...
{ // HACK: handle underdetermined forms let undet = crate::ty_compare::underdetermined_form.with(|u| u.clone()); match actl { Node(form, body, _) if form == &undet => { return crate::ty_compare::unification.with(|unif| { let var = body.get_leaf_or_panic(&n("id")).to_name(...
identifier_body
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn
(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body); res.push(n); res } Scope(_, _) => vec![], Pick(_, _) => vec![], Star(ref body) | Plus(ref body) | NameImport(ref...
node_names_mentioned
identifier_name
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn node_names_mentioned(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body...
let sub_res = unparse_mbe(&*sub_pat, actl, context, s); if sub_res != "" { return sub_res; } // HACK: should use `Option` } // HACK: certain forms don't live in the syntax environment, // but "belong" under an `Alt...
any_scopes = true; continue; }
conditional_block
definitions.ts
/** * Copyright(c) dtysky<dtysky@outlook.com> * Created: 24 Oct 2017 * Description: */ export default { none: 'NONE', theme: { init: 'THEME_INIT', refresh: 'THEME_REFRESH', updateList: 'THEME_UPDATE_LIST', updateCurrent: 'THEME_UPDATE_CURRENT' }, shelf: { load: 'SHELF_LOAD', add: 'SH...
notification: { info: 'NOTIFICATION_INFO', success: 'NOTIFICATION_SUCCESS', warn: 'NOTIFICATION_WARN', error: 'NOTIFICATION_ERROR', close: 'NOTIFICATION_CLOSE' }, modal: { info: 'MODAL_INFO', success: 'MODAL_SUCCESS', warn: 'MODAL_WARN', error: 'MODAL_ERROR', close: 'MODAL_...
saveEpic: 'PAGE_SAVE_EPIC' },
random_line_split
flow_control.rs
#![allow(dead_code, unreachable_code, unused_variables)] pub fn flow_control() { println!("***Flow Control***"); if_else(); loops(); whiles(); for_ranges(); matching(); if_let(); while_let(); println!(""); } fn if_else() { let n = 5; if n < 0 { print!("{} is nega...
match reference { &val => println!("Got by destructuring: {:?}", val), } // to avoid the '&', dereference before matching match *reference { val => println!("Got by dereferencing: {:?}", val), } // same as &3 let ref is_a_ref = 3; let value = 5; let mut mut_value...
let reference = &4;
random_line_split
flow_control.rs
#![allow(dead_code, unreachable_code, unused_variables)] pub fn flow_control() { println!("***Flow Control***"); if_else(); loops(); whiles(); for_ranges(); matching(); if_let(); while_let(); println!(""); } fn if_else() { let n = 5; if n < 0 { print!("{} is nega...
{ 15 }
identifier_body
flow_control.rs
#![allow(dead_code, unreachable_code, unused_variables)] pub fn flow_control() { println!("***Flow Control***"); if_else(); loops(); whiles(); for_ranges(); matching(); if_let(); while_let(); println!(""); } fn if_else() { let n = 5; if n < 0 { print!("{} is nega...
() -> u32 { 15 }
age
identifier_name
Perforce.py
"""SCons.Tool.Perforce.py Tool-specific initialization for Perforce Source Code Management system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 20...
(env): """Add a Builder factory function and construction variables for Perforce to an Environment.""" def PerforceFactory(env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The Perforce() factory is deprecated and there is no replacement.""") ...
generate
identifier_name
Perforce.py
"""SCons.Tool.Perforce.py Tool-specific initialization for Perforce Source Code Management system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 20...
# Perforce seems to use the PWD environment variable rather than # calling getcwd() for itself, which is odd. If no PWD variable # is present, p4 WILL call getcwd, but this seems to cause problems # with good ol' Windows's tilde-mangling for long file names. environ['PWD'] = env.Dir('#').get_abspa...
"""Add a Builder factory function and construction variables for Perforce to an Environment.""" def PerforceFactory(env=env): """ """ import SCons.Warnings as W W.warn(W.DeprecatedSourceCodeWarning, """The Perforce() factory is deprecated and there is no replacement.""") return ...
identifier_body
Perforce.py
"""SCons.Tool.Perforce.py Tool-specific initialization for Perforce Source Code Management system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 20...
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "src/engine/SCons/Tool/Perforce.py 2014/03/02 14:18:15 garyo" import os import SCons.Action import SCons.Builder import SCons.Node.FS import SCons.Util # This fun...
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
random_line_split
Perforce.py
"""SCons.Tool.Perforce.py Tool-specific initialization for Perforce Source Code Management system. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 20...
if SCons.Util.can_read_reg: # If we can read the registry, add the path to Perforce to our environment. try: k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Perforce\\environment') val, tok = SCons.Util.RegQ...
environ[var] = v
conditional_block
mywheel.js
/*var numSegments = 4; var segments = [ {'fillStyle' : '#747474', 'text' : 'Pen/Eraser'}, {'fillStyle' : '#43A5F6', 'text' : 'True Money'}, {'fillStyle' : '#FF4180', 'text' : 'Thank You'}, {'fillStyle' : '#FED352', 'text' : 'Flash Drive'} ]; var theWheel = new Winwheel({ 'canvasId' : 'myCanvas', 'numSegment...
//return item; } function testProbability(times) { var map = [0, 0, 0]; for (var i = 0; i < times; i++) { map[getStopAngle()]++; } console.log("Probability result from " + times + " loops"); console.log(map); } theWheel.animation.stopAngle = getStopAngle(); // Vars used by the code i...
{ var selection = myRNG() * 1000; var item = 0; //console.log("Random range: " + selection); if (spinningCount < 50) spinningCount++; if (selection >= 0 && selection <= 100 && spinningCount >= 50) { item = 0; spinningCount = 0; } else if (selection > 100 && selection <= 300 &...
identifier_body
mywheel.js
/*var numSegments = 4; var segments = [ {'fillStyle' : '#747474', 'text' : 'Pen/Eraser'}, {'fillStyle' : '#43A5F6', 'text' : 'True Money'}, {'fillStyle' : '#FF4180', 'text' : 'Thank You'}, {'fillStyle' : '#FED352', 'text' : 'Flash Drive'} ]; var theWheel = new Winwheel({ 'canvasId' : 'myCanvas', 'numSegment...
// ------------------------------------------------------- // Function to handle the onClick on the power buttons. // ------------------------------------------------------- function powerSelected(powerLevel) { // Ensure that power can't be changed while wheel is spinning. if (wheelSpinning == false) { ...
theWheel.animation.stopAngle = getStopAngle(); // Vars used by the code in this page to do power controls. var wheelPower = 0; var wheelSpinning = false;
random_line_split
mywheel.js
/*var numSegments = 4; var segments = [ {'fillStyle' : '#747474', 'text' : 'Pen/Eraser'}, {'fillStyle' : '#43A5F6', 'text' : 'True Money'}, {'fillStyle' : '#FF4180', 'text' : 'Thank You'}, {'fillStyle' : '#FED352', 'text' : 'Flash Drive'} ]; var theWheel = new Winwheel({ 'canvasId' : 'myCanvas', 'numSegment...
(start, end) { return start + Math.random() * (end - start); } // Probability function function getStopAngle() { var selection = myRNG() * 1000; var item = 0; //console.log("Random range: " + selection); if (spinningCount < 50) spinningCount++; if (selection >= 0 && selection <= 100 && spinnin...
randomRange
identifier_name
mywheel.js
/*var numSegments = 4; var segments = [ {'fillStyle' : '#747474', 'text' : 'Pen/Eraser'}, {'fillStyle' : '#43A5F6', 'text' : 'True Money'}, {'fillStyle' : '#FF4180', 'text' : 'Thank You'}, {'fillStyle' : '#FED352', 'text' : 'Flash Drive'} ]; var theWheel = new Winwheel({ 'canvasId' : 'myCanvas', 'numSegment...
} // ------------------------------------------------------- // Function for reset button. // ------------------------------------------------------- function resetWheel() { theWheel.stopAnimation(false); // Stop the animation, false as param so does not call callback function. theWheel.rotationAngle = 0; ...
{ resetWheel(); return false; }
conditional_block
context.rs
//! Provides a Rust wrapper around Cuda's context. use device::{IDevice, DeviceType, IDeviceSyncOut}; use device::Error as DeviceError; use super::api::DriverFFI; use super::{Driver, DriverError, Device}; use super::memory::*; #[cfg(feature = "native")] use frameworks::native::flatbox::FlatBox; use memory::MemoryType;...
id: Rc::new(id as isize), devices: devices } } /// Returns the id as isize. pub fn id(&self) -> isize { *self.id } /// Returns the id as its C type. pub fn id_c(&self) -> DriverFFI::CUcontext { *self.id as DriverFFI::CUcontext } /// Sync...
/// Initializes a new Cuda platform from its C type. pub fn from_c(id: DriverFFI::CUcontext, devices: Vec<Device>) -> Context { Context {
random_line_split
context.rs
//! Provides a Rust wrapper around Cuda's context. use device::{IDevice, DeviceType, IDeviceSyncOut}; use device::Error as DeviceError; use super::api::DriverFFI; use super::{Driver, DriverError, Device}; use super::memory::*; #[cfg(feature = "native")] use frameworks::native::flatbox::FlatBox; use memory::MemoryType;...
(devices: Device) -> Result<Context, DriverError> { Ok( Context::from_c( try!(Driver::create_context(devices.clone())), vec!(devices.clone()) ) ) } /// Initializes a new Cuda platform from its C type. pub fn from_c(id: DriverFFI::CUcon...
new
identifier_name
context.rs
//! Provides a Rust wrapper around Cuda's context. use device::{IDevice, DeviceType, IDeviceSyncOut}; use device::Error as DeviceError; use super::api::DriverFFI; use super::{Driver, DriverError, Device}; use super::memory::*; #[cfg(feature = "native")] use frameworks::native::flatbox::FlatBox; use memory::MemoryType;...
/// Synchronize this Context. pub fn synchronize(&self) -> Result<(), DriverError> { Driver::synchronize_context() } } #[cfg(feature = "native")] impl IDeviceSyncOut<FlatBox> for Context { type M = Memory; fn sync_out(&self, source_data: &Memory, dest_data: &mut FlatBox) -> Result<(), Dev...
{ *self.id as DriverFFI::CUcontext }
identifier_body
special.py
'''Defines the Special class for theia.''' # Provides: # class Special # __init__ # lines import numpy as np from ..helpers import geometry, settings from ..helpers.units import deg, cm, pi from .optic import Optic class Special(Optic): ''' Special class. This class represents general opt...
(self, Wedge = 0., Alpha = 0., X = 0., Y = 0., Z = 0., Theta = pi/2., Phi = 0., Diameter = 10.e-2, HRr = .99, HRt = .01, ARr = .1, ARt = .9, HRK = 0.01, ARK = 0, Thickness = 2.e-2, N = 1.4585, KeepI = False, RonHR = 0, TonHR = 0, RonAR = 0,...
__init__
identifier_name
special.py
'''Defines the Special class for theia.''' # Provides: # class Special # __init__ # lines import numpy as np from ..helpers import geometry, settings from ..helpers.units import deg, cm, pi from .optic import Optic class Special(Optic): ''' Special class. This class represents general opt...
def lines(self): '''Returns the list of lines necessary to print the object.''' sph = geometry.rectToSph(self.HRNorm) return ["Special: %s {" % str(self.Ref), "TonHR, RonHR: %s, %s" % (str(self.TonHR), str(self.RonHR)), "TonAR, RonAR: %s, %s" % (str(self.TonAR), str(self.Ro...
self.geoCheck("mirror")
conditional_block
special.py
'''Defines the Special class for theia.''' # Provides: # class Special # __init__ # lines import numpy as np from ..helpers import geometry, settings from ..helpers.units import deg, cm, pi from .optic import Optic class Special(Optic): ''' Special class. This class represents general opt...
np.cos(Theta)], dtype = np.float64) HRCenter = np.array([X, Y, Z], dtype = np.float64) #Calculate ARCenter and ARNorm with wedge and alpha and thickness: ARCenter = HRCenter\ - (Thickness + .5 * np.tan(Wedge) * Diameter) * HRNorm a,b = geometry.basi...
ARr = float(ARr) #prepare for mother initializer HRNorm = np.array([np.sin(Theta)*np.cos(Phi), np.sin(Theta) * np.sin(Phi),
random_line_split
special.py
'''Defines the Special class for theia.''' # Provides: # class Special # __init__ # lines import numpy as np from ..helpers import geometry, settings from ..helpers.units import deg, cm, pi from .optic import Optic class Special(Optic):
*=== Name ===* Special **Note**: the curvature of any surface is positive for a concave surface (coating inside the sphere). Thus kurv*HRNorm/|kurv| always points to the center of the sphere of the surface, as is the convention for the lineSurfInter of geometry module. Same for AR. *...
''' Special class. This class represents general optics, as their actions on R and T are left to the user to input. They are useful for special optics which are neither reflective nor transmissive. Actions: * T on HR: user input * R on HR: user input * T on AR: user input ...
identifier_body
tfjs-backend-wasm-threaded-simd.d.ts
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0
* See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import {BackendWasmModule} from './tfjs-backend-wasm'; export interface BackendWasmThreadedSimdModule extends BackendWasmModule ...
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
random_line_split
macros.rs
//macro_rules! batch { //($name : ident, [ $($parts: ident : $pty: ty),* ], [$($defid : ident : $val : expr),*]) => { //impl<T, V> $name<T, V> //where T: EndOffset, //V:Batch + BatchIterator + Act { //#[inline] //pub fn new($( $parts : $pty ),*) -> $name<T, V> { //$name{ $( $parts: $parts ),*, $($defid : $val),* } //}...
batch!{$name, [$($parts:$pty),*], []} } } macro_rules! act { () => { #[inline] fn act(&mut self) { self.parent.act(); } #[inline] fn done(&mut self) { self.parent.done(); } #[inline] fn send_q(&mut self, port: &Pa...
}; ($name: ident, [ $($parts: ident : $pty: ty),* ]) => {
random_line_split
coupler_ring.py
from typing import Optional import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.components.bend_euler import bend_euler from gdsfactory.components.coupler90 import coupler90 as coupler90function from gdsfactory.components.coupler_straight import ( coupler_straight as coupler_straight...
( gap: float = 0.2, radius: float = 5.0, length_x: float = 4.0, coupler90: ComponentFactory = coupler90function, bend: Optional[ComponentFactory] = None, coupler_straight: ComponentFactory = coupler_straight_function, cross_section: CrossSectionFactory = strip, bend_cross_section: Option...
coupler_ring
identifier_name
coupler_ring.py
from typing import Optional import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.components.bend_euler import bend_euler from gdsfactory.components.coupler90 import coupler90 as coupler90function from gdsfactory.components.coupler_straight import ( coupler_straight as coupler_straight...
""" bend = bend or bend_euler c = Component() assert_on_2nm_grid(gap) # define subcells coupler90_component = ( coupler90( gap=gap, radius=radius, bend=bend, cross_section=cross_section, bend_cross_section=bend_cross_section...
r"""Coupler for ring. Args: gap: spacing between parallel coupled straight waveguides. radius: of the bends. length_x: length of the parallel coupled straight waveguides. coupler90: straight coupled to a 90deg bend. bend: factory for bend coupler_straight: two parall...
identifier_body
coupler_ring.py
from typing import Optional import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.components.bend_euler import bend_euler from gdsfactory.components.coupler90 import coupler90 as coupler90function from gdsfactory.components.coupler_straight import ( coupler_straight as coupler_straight...
c = coupler_ring(width=1, layer=(2, 0)) c.show(show_subports=True)
conditional_block
coupler_ring.py
from typing import Optional import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.components.bend_euler import bend_euler from gdsfactory.components.coupler90 import coupler90 as coupler90function from gdsfactory.components.coupler_straight import ( coupler_straight as coupler_straight...
from gdsfactory.snap import assert_on_2nm_grid from gdsfactory.types import ComponentFactory, CrossSectionFactory @gf.cell def coupler_ring( gap: float = 0.2, radius: float = 5.0, length_x: float = 4.0, coupler90: ComponentFactory = coupler90function, bend: Optional[ComponentFactory] = None, c...
) from gdsfactory.cross_section import strip
random_line_split
unify.rs
table. marker: marker::CovariantType<K>, snapshot: sv::Snapshot, } /** * Internal type used to represent the result of a `get()` operation. * Conveys the current root and value of the key. */ pub struct Node<K,V> { pub key: K, pub value: V, pub rank: uint, } pub struct Delegate; // We can't u...
{ /*! * Sets the value of the key `a_id` to `b`. Because * simple keys do not have any subtyping relationships, * if `a_id` already has a value, it must be the same as * `b`. */ let tcx = self.tcx; let table = UnifyKey::unification_table(self); ...
identifier_body
unify.rs
Also * removes any keys that have been created since then. */ pub fn rollback_to(&mut self, snapshot: Snapshot<K>) { debug!("{}: rollback_to()", UnifyKey::tag(None::<K>)); self.values.rollback_to(snapshot.snapshot); } /** * Commits all changes since the last snapshot. Of cou...
from_index
identifier_name
unify.rs
fcx: &'v InferCtxt) -> &'v RefCell<UnificationTable<Self,V>>; fn tag(k: Option<Self>) -> &'static str; } /** * Trait for valid types that a type variable can be set to. Note that * this is typically not the end type that the value will take on, but * rather an `Option` wrapper (whe...
b_t: V) -> ures { if a_is_expected { Err(SimplyUnifiable::to_type_err( ty::expected_found {expected: a_t, found: b_t})) } else { Err(SimplyUnifiable::to_type_err( ty::expected_found {expected: b_t, found: a_t})) ...
a_t: V,
random_line_split
sv.js
"An unknown error has occurred" : "Ett okänt fel uppstod", "Uploading …" : "Laddar upp ..", "{loadedSize} of {totalSize} ({bitrate})" : "{loadedSize} av {totalSize} ({bitrate})", "Uploading that item is not supported" : "Uppladdning av det här objektet stöds inte", "Target folder does not exist any ...
"…" : "...", "Unable to upload {filename} as it is a directory or has 0 bytes" : "Kan inte ladda upp {filename} eftersom den antingen är en mapp eller har 0 bytes.", "Not enough free space, you are uploading {size1} but only {size2} is left" : "Inte tillräckligt med ledigt utrymme, du laddar upp {size1} men...
random_line_split
ddp_model.py
# Copyright The PyTorch Lightning team. # # 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 i...
elif args.trainer_method == "fit_test": trainer.fit(model, datamodule=dm) result = trainer.test(model, datamodule=dm) else: raise ValueError(f"Unsupported: {args.trainer_method}") result_ext = {"status": "complete", "method": args.trainer_method, "result": result} file_path = o...
result = trainer.test(model, datamodule=dm)
conditional_block
ddp_model.py
# Copyright The PyTorch Lightning team. # # 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 i...
elif args.trainer_method == "fit_test": trainer.fit(model, datamodule=dm) result = trainer.test(model, datamodule=dm) else: raise ValueError(f"Unsupported: {args.trainer_method}") result_ext = {"status": "complete", "method": args.trainer_method, "result": result} file_path = os...
seed_everything(4321) parser = ArgumentParser(add_help=False) parser = Trainer.add_argparse_args(parser) parser.add_argument("--trainer_method", default="fit") parser.add_argument("--tmpdir") parser.add_argument("--workdir") parser.set_defaults(gpus=2) parser.set_defaults(accelerator="ddp")...
identifier_body
ddp_model.py
# Copyright The PyTorch Lightning team. # # 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 i...
(): seed_everything(4321) parser = ArgumentParser(add_help=False) parser = Trainer.add_argparse_args(parser) parser.add_argument("--trainer_method", default="fit") parser.add_argument("--tmpdir") parser.add_argument("--workdir") parser.set_defaults(gpus=2) parser.set_defaults(accelerato...
main
identifier_name
ddp_model.py
# Copyright The PyTorch Lightning team. # # 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 i...
if __name__ == "__main__": main()
torch.save(result_ext, file_path)
random_line_split
adjacentAngles.js
/* * Copyright (c) 2002-2020 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j 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 ...
p = start return extendStart } else { runs.push({ start, end }) p = end return scanForDensePair } } var tooDense = function(start, end) { const run = { start, end } return AngleList.angle(run) < An...
const candidateStart = AngleList.wrapIndex(p - 1) if (tooDense(candidateStart, end) && candidateStart !== end) { start = candidateStart
random_line_split
adjacentAngles.js
/* * Copyright (c) 2002-2020 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j 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 ...
(AngleList, minSeparation) { let p = 0 let start = 0 let end = 0 const runs = [] const minStart = function() { if (runs.length === 0) { return 0 } else { return runs[0].start } } var scanForDensePair = function() { start = p end = AngleList.wrap...
findRuns
identifier_name
adjacentAngles.js
/* * Copyright (c) 2002-2020 "Neo4j," * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j 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 ...
if (tooDense(start, end)) { return extendEnd } else { return scanForDensePair } } } var extendEnd = function() { if (p === minStart()) { return 'done' } else if (tooDense(start, AngleList.wrapIndex(p + 1))) { end = AngleList.wrapInde...
{ let p = 0 let start = 0 let end = 0 const runs = [] const minStart = function() { if (runs.length === 0) { return 0 } else { return runs[0].start } } var scanForDensePair = function() { start = p end = AngleList.wrapIndex(p + 1) if (end ...
identifier_body
ConfigDB_Longest_8.py
HOST = "wfSciwoncWiki:enw1989@172.31.29.101:27001,172.31.29.102:27001,172.31.29.103:27001,172.31.29.104:27001,172.31.29.105:27001,172.31.29.106:27001,172.31.29.107:27001,172.31.29.108:27001,172.31.29.109:27001/?authSource=admin" PORT = "" USER = "" PASSWORD = "" DATABASE = "wiki" READ_PREFERENCE = "primary"
COLLECTION_OUTPUT = "top_sessions" PREFIX_COLUMN = "w_" ATTRIBUTES = ["duration", "start time", "end time", "contributor_username", "edition_counts"] SORT = ["duration", "end time"] OPERATION_TYPE = "GROUP_BY_FIXED_WINDOW" COLUMN = "end time" VALUE = [(1236381526, 1238973525),(1238973526, 1241565525),(124156552...
COLLECTION_INPUT = "user_sessions"
random_line_split
comprehension.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, traceback, Ice, threading, time, os import IceStorm # Ctrl+c handling import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # Qt interface from PySide.QtCore import * from PySide.QtGui import * from PySide.QtSvg import * # Check that RoboComp has been ...
self.commandTopic.newCommand(command) else: print 'Comando vacio?' def mode(self, text): print 'Nos llega por la interfaz ASRComprehension', text class ASRPublishTopicI (RoboCompASRPublish.ASRPublish): def __init__(self, _handler): self.handler = _handler def newText(self, text, current=None): self.ha...
print 'Action', command.action
random_line_split
comprehension.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, traceback, Ice, threading, time, os import IceStorm # Ctrl+c handling import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # Qt interface from PySide.QtCore import * from PySide.QtGui import * from PySide.QtSvg import * # Check that RoboComp has been ...
(self, text, current=None): print 'Nos ha llegado', text command = RoboCompASRCommand.Command() partes = text.split() if len(partes) > 0: command.action = partes[0] if len(partes) > 1: command.complements = partes[1:] print 'Action', command.action, '(', command.complements,')' else: print ...
newText
identifier_name
comprehension.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, traceback, Ice, threading, time, os import IceStorm # Ctrl+c handling import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # Qt interface from PySide.QtCore import * from PySide.QtGui import * from PySide.QtSvg import * # Check that RoboComp has been ...
def mode(self, text): print 'Nos llega por la interfaz ASRComprehension', text class ASRPublishTopicI (RoboCompASRPublish.ASRPublish): def __init__(self, _handler): self.handler = _handler def newText(self, text, current=None): self.handler.newText(text) class ASRComprehensionI (RoboCompASRComprehension.ASR...
print 'Comando vacio?'
conditional_block
comprehension.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, traceback, Ice, threading, time, os import IceStorm # Ctrl+c handling import signal signal.signal(signal.SIGINT, signal.SIG_DFL) # Qt interface from PySide.QtCore import * from PySide.QtGui import * from PySide.QtSvg import * # Check that RoboComp has been ...
class ASRComprehensionI (RoboCompASRComprehension.ASRComprehension): def __init__(self, _handler): self.handler = _handler def mode(self, text, current=None): self.handler.mode(text) class Server (Ice.Application): def run (self, argv): status = 0 try: # Proxy to publish ASRCommand proxy = self.comm...
def __init__(self, _handler): self.handler = _handler def newText(self, text, current=None): self.handler.newText(text)
identifier_body
borrowck-loan-blocks-move-cc.rs
// Copyright 2012 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 ...
() { }
main
identifier_name
borrowck-loan-blocks-move-cc.rs
// Copyright 2012 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 ...
{ }
identifier_body
borrowck-loan-blocks-move-cc.rs
// Copyright 2012 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
use std::thread::Thread; fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) { f(v); } fn box_imm() { let v = box 3; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move `v` into closure }); } fn box_imm_explicit() { let v = box 3; let _w = &...
// <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. #![feature(box_syntax)]
random_line_split
main.rs
#![allow(dead_code)] extern crate libc; extern crate jni; use jni::*; #[test] fn test() { assert!(!mytest().is_err()); } fn
() -> Result<(),jni::Exception> { let opt1 = JavaVMOption::new("-Xcheck:jni"); println!("Opt is {:?}", opt1); let opt2 = JavaVMOption::new("-verbose:jni"); println!("Opt is {:?}", opt2); let args = JavaVMInitArgs::new( jni::JniVersion::JNI_VERSION_1_4, &[/*opt1, JavaVMOption::new("-verbose:jni")*/][..], fa...
mytest
identifier_name
main.rs
#![allow(dead_code)] extern crate libc; extern crate jni; use jni::*; #[test] fn test() { assert!(!mytest().is_err()); } fn mytest() -> Result<(),jni::Exception> { let opt1 = JavaVMOption::new("-Xcheck:jni"); println!("Opt is {:?}", opt1); let opt2 = JavaVMOption::new("-verbose:jni"); println!("Opt is {:?}", o...
fn get_val(&self) -> u64 { self.val } } #[test] fn test() { let parent = Parent::new(1); let child = parent.child(2); let obj1 = child.obj1(3); let obj2 = child.obj2(3); assert!(obj1 == obj2); assert!(obj2 == obj1); let parent2 = Parent::new(1); let child2 = parent2.child(2); let obj12 = child2.obj1(3);...
}
random_line_split
main.rs
#![allow(dead_code)] extern crate libc; extern crate jni; use jni::*; #[test] fn test()
fn mytest() -> Result<(),jni::Exception> { let opt1 = JavaVMOption::new("-Xcheck:jni"); println!("Opt is {:?}", opt1); let opt2 = JavaVMOption::new("-verbose:jni"); println!("Opt is {:?}", opt2); let args = JavaVMInitArgs::new( jni::JniVersion::JNI_VERSION_1_4, &[/*opt1, JavaVMOption::new("-verbose:jni")*/...
{ assert!(!mytest().is_err()); }
identifier_body
animated_properties.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use style::properties::animated_properties::{Animatable, IntermediateRGBA}; fn interpolate_r...
RGBA::new(154, 0, 0, 77)); } #[test] fn test_rgba_color_interepolation_out_of_range_2() { assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6), RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5), RGBA::new(0, 154, 0, 77)); } #[test] fn test_rgba_...
RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5),
random_line_split
animated_properties.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use style::properties::animated_properties::{Animatable, IntermediateRGBA}; fn
(from: RGBA, to: RGBA, progress: f64) -> RGBA { let from: IntermediateRGBA = from.into(); let to: IntermediateRGBA = to.into(); from.interpolate(&to, progress).unwrap().into() } #[test] fn test_rgba_color_interepolation_preserves_transparent() { assert_eq!(interpolate_rgba(RGBA::transparent(), ...
interpolate_rgba
identifier_name
animated_properties.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; use style::properties::animated_properties::{Animatable, IntermediateRGBA}; fn interpolate_r...
#[test] fn test_rgba_color_interepolation_out_of_range_2() { assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6), RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5), RGBA::new(0, 154, 0, 77)); } #[test] fn test_rgba_color_interepolation_out_of_range_clamped_1...
{ // Some cubic-bezier functions produce values that are out of range [0, 1]. // Unclamped cases. assert_eq!(interpolate_rgba(RGBA::from_floats(0.3, 0.0, 0.0, 0.4), RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5), RGBA::new(154, 0, 0, 77)); }
identifier_body
synth.py
Experiment(description='Synthetic data sets of interest', data_dir='../data/synth/', max_depth=9, random_order=False, k=1, debug=False, local_computation=False, n_rand=9,
sd=2, jitter_sd=0.1, max_jobs=300, verbose=False, make_predictions=False, skip_complete=False, results_dir='../results/synth/', iters=250, base_kernels='SE,Per,Lin,Const,Noise', random_seed=1, peri...
random_line_split
bootstrap-table-af-ZA.min.js
/** * bootstrap-table - An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3). *
* @version v1.14.1 * @homepage https://bootstrap-table.com * @author wenzhixin <wenzhixin2010@gmail.com> (http://wenzhixin.net.cn/) * @license MIT */ (function(a,b){if('function'==typeof define&&define.amd)define([],b);else if('undefined'!=typeof exports)b();else{b(),a.bootstrapTableAfZA={exports:{}}.exports...
random_line_split
bootstrap-table-af-ZA.min.js
/** * bootstrap-table - An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3). * * @version v1.14.1 * @homepage https://bootstrap-table.com * @author wenzhixin <wenzhixin2010@gmail.com> (http://wenzhixin.net.cn/) * @license MIT ...
})(this,function(){'use strict';(function(a){a.fn.bootstrapTable.locales['af-ZA']={formatLoadingMessage:function(){return'Besig om te laai, wag asseblief ...'},formatRecordsPerPage:function(a){return a+' rekords per bladsy'},formatShowingRows:function(a,b,c){return'Resultate '+a+' tot '+b+' van '+c+' rye'},formatSearch...
{b(),a.bootstrapTableAfZA={exports:{}}.exports}
conditional_block
tabview.ts
,Component,ElementRef,OnDestroy,Input,Output,EventEmitter,HostListener,AfterContentInit, ContentChildren,ContentChild,QueryList,TemplateRef,EmbeddedViewRef,ViewContainerRef} from '@angular/core'; import {CommonModule} from '@angular/common'; import {SharedModule,PrimeTemplate} from '../common/shared'; import {B...
break; } } return index; } getBlockableElement(): HTMLElement { return this.el.nativeElement.children[0]; } @Input() get activeIndex(): number { return this._activeIndex; } set activeIndex(val:number) { this._activeIn...
if(this.tabs[i] == tab) { index = i;
random_line_split
tabview.ts
,Component,ElementRef,OnDestroy,Input,Output,EventEmitter,HostListener,AfterContentInit, ContentChildren,ContentChild,QueryList,TemplateRef,EmbeddedViewRef,ViewContainerRef} from '@angular/core'; import {CommonModule} from '@angular/common'; import {SharedModule,PrimeTemplate} from '../common/shared'; import {B...
(): HTMLElement { return this.el.nativeElement.children[0]; } @Input() get activeIndex(): number { return this._activeIndex; } set activeIndex(val:number) { this._activeIndex = val; if(this.tabs && this.tabs.length && this._activeIndex != null && this.tabs....
getBlockableElement
identifier_name
tabview.ts
,Component,ElementRef,OnDestroy,Input,Output,EventEmitter,HostListener,AfterContentInit, ContentChildren,ContentChild,QueryList,TemplateRef,EmbeddedViewRef,ViewContainerRef} from '@angular/core'; import {CommonModule} from '@angular/common'; import {SharedModule,PrimeTemplate} from '../common/shared'; import {B...
findSelectedTab() { for(let i = 0; i < this.tabs.length; i++) { if(this.tabs[i].selected) { return this.tabs[i]; } } return null; } findTabIndex(tab: TabPanel) { let index = -1; for(let i = 0; i < this.tabs.length; i+...
{ if(tab.selected) { tab.selected = false; for(let i = 0; i < this.tabs.length; i++) { let tabPanel = this.tabs[i]; if(!tabPanel.closed&&!tab.disabled) { tabPanel.selected = true; break; } ...
identifier_body
tabview.ts
Component,ElementRef,OnDestroy,Input,Output,EventEmitter,HostListener,AfterContentInit, ContentChildren,ContentChild,QueryList,TemplateRef,EmbeddedViewRef,ViewContainerRef} from '@angular/core'; import {CommonModule} from '@angular/common'; import {SharedModule,PrimeTemplate} from '../common/shared'; import {Bl...
} return null; } findTabIndex(tab: TabPanel) { let index = -1; for(let i = 0; i < this.tabs.length; i++) { if(this.tabs[i] == tab) { index = i; break; } } return index; } getBlockableElemen...
{ return this.tabs[i]; }
conditional_block
server.spec.js
var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var expect = chai.expect; var Promise = require('bluebird'); var messages = require('../server/messages'); var Chat = require('../server/database.js'); describe('Chat Timing', function() { before(function(done) {...
done(); }); });
random_line_split
multihash.rs
size of the digest in bytes (not the allocated size). size: u8, /// The digest. #[cfg_attr(feature = "serde-codec", serde(with = "BigArray"))] digest: [u8; S], } impl<const S: usize> Default for Multihash<S> { fn default() -> Self { Self { code: 0, size: 0, ...
read_u64
identifier_name
multihash.rs
``` /// use multihash::{Code, MultihashDigest, MultihashGeneric}; /// /// let hash = Code::Sha3_256.digest(b"Hello world!"); /// let large_hash: MultihashGeneric<32> = hash.resize().unwrap(); /// ``` pub fn resize<const R: usize>(&self) -> Result<Multihash<R>, Error> { let size = self.s...
{ let mh = Multihash::<32>::default(); let bytes = serde_json::to_string(&mh).unwrap(); let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap(); assert_eq!(mh, mh2); }
identifier_body
multihash.rs
0, 0x64, 0x4b, 0xcc, 0x7e, 0x56, 0x43, 0x73, 0x04, 0x09, 0x99, 0xaa, 0xc8, 0x9e, /// 0x76, 0x22, 0xf3, 0xca, 0x71, 0xfb, 0xa1, 0xd9, 0x72, 0xfd, 0x94, 0xa3, 0x1c, 0x3b, 0xfb, /// 0xf2, 0x4e, 0x39, 0x38, /// ]; /// let mh = Multihash::from_bytes(&digest_bytes).unwrap(); /// assert_eq!(mh.code(), Sha3_256); /// a...
return Err(Error::InvalidSize(bytes.len().try_into().expect( "Currently the maximum size is 255, therefore always fits into usize", ))); } Ok(result) } /// Writes a multihash to a byte stream. pub fn write<W: io::Write>(&self, w: W) -> Result<(), Err...
random_line_split
multihash.rs
, 0x64, 0x4b, 0xcc, 0x7e, 0x56, 0x43, 0x73, 0x04, 0x09, 0x99, 0xaa, 0xc8, 0x9e, /// 0x76, 0x22, 0xf3, 0xca, 0x71, 0xfb, 0xa1, 0xd9, 0x72, 0xfd, 0x94, 0xa3, 0x1c, 0x3b, 0xfb, /// 0xf2, 0x4e, 0x39, 0x38, /// ]; /// let mh = Multihash::from_bytes(&digest_bytes).unwrap(); /// assert_eq!(mh.code(), Sha3_256); /// as...
Ok(result) } /// Writes a multihash to a byte stream. pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> { write_multihash(w, self.code(), self.size(), self.digest()) } #[cfg(feature = "alloc")] /// Returns the bytes of a multihash. pub fn to_bytes(&self) -> Vec...
{ return Err(Error::InvalidSize(bytes.len().try_into().expect( "Currently the maximum size is 255, therefore always fits into usize", ))); }
conditional_block
ip_configuration_py3.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.etag = etag
random_line_split
ip_configuration_py3.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, *, id: str=None, private_ip_address: str=None, private_ip_allocation_method=None, subnet=None, public_ip_address=None, provisioning_state: str=None, name: str=None, etag: str=None, **kwargs) -> None: super(IPConfiguration, self).__init__(id=id, **kwargs) self.private_ip_address = private_ip_addre...
__init__
identifier_name
ip_configuration_py3.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 ...
super(IPConfiguration, self).__init__(id=id, **kwargs) self.private_ip_address = private_ip_address self.private_ip_allocation_method = private_ip_allocation_method self.subnet = subnet self.public_ip_address = public_ip_address self.provisioning_state = provisioning_state ...
identifier_body
purchase_order_line.py
# -*- coding: utf-8 -*- # Copyright 2019 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields, api class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.multi @api.depends( "product_id", ) def...
(self): _super = super(PurchaseOrderLine, self) result = _super.onchange_product_id( self.order_id.pricelist_id.id, self.product_id.id, self.product_qty, self.product_uom.id, self.order_id.partner_id.id, self.order_id.date_order, ...
onchange_product_id_new_api
identifier_name
purchase_order_line.py
# -*- coding: utf-8 -*- # Copyright 2019 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields, api class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.multi @api.depends( "product_id", ) def...
allowed_purchase_uom_ids = fields.Many2many( string="Allowed Invoices", comodel_name="product.uom", compute="_compute_allowed_purchase_uom_ids", store=False, ) @api.onchange( "product_id", "product_uom", "product_qty", ) @api.depends( ...
if document.product_id.limit_product_uom_selection: allowed_purchase_uom_ids =\ document.product_id.allowed_purchase_uom_ids.ids if uom_po.id not in allowed_purchase_uom_ids: allowed_purchase_uom_ids.append(uom_po.id) ...
conditional_block
purchase_order_line.py
# -*- coding: utf-8 -*- # Copyright 2019 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields, api class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.multi @api.depends( "product_id", ) def...
criteria = [ ("category_id", "=", category_id) ] document.allowed_purchase_uom_ids =\ obj_product_uom.search(criteria) allowed_purchase_uom_ids = fields.Many2many( string="Allowed Invoices", ...
else: category_id =\ uom_po.category_id.id
random_line_split
purchase_order_line.py
# -*- coding: utf-8 -*- # Copyright 2019 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import models, fields, api class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" @api.multi @api.depends( "product_id", ) def...
_super = super(PurchaseOrderLine, self) result = _super.onchange_product_id( self.order_id.pricelist_id.id, self.product_id.id, self.product_qty, self.product_uom.id, self.order_id.partner_id.id, self.order_id.date_order, self.o...
identifier_body
jquery.flot.selection.js
displayed. When customizing this value, the fact that it refers to pixels, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 pixel. Note also that s...
(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) ...
extractRange
identifier_name
jquery.flot.selection.js
displayed. When customizing this value, the fact that it refers to pixels, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 pixel. Note also that s...
function onMouseDown(e) { if (e.which != 1) // only accept left-click return; // cancel out any text selections document.body.focus(); // prevent text selection and drag in old-school browsers if (document.onselectstart !== undefine...
updateSelection(e); plot.getPlaceholder().trigger("plotselecting", [getSelection()]); } }
random_line_split
jquery.flot.selection.js
displayed. When customizing this value, the fact that it refers to pixels, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 pixel. Note also that s...
setSelectionPos(selection.first, e); selection.active = true; // this is a bit silly, but we have to use a closure to be // able to whack the same handler again mouseUpHandler = function (e) { onMouseUp(e); }; $(doc...
{ savedhandlers.ondrag = document.ondrag; document.ondrag = function () { return false; }; }
conditional_block
jquery.flot.selection.js
displayed. When customizing this value, the fact that it refers to pixels, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 pixel. Note also that s...
function setSelectionPos(pos, e) { var o = plot.getOptions(); var offset = plot.getPlaceholder().offset(); var plotOffset = plot.getPlotOffset(); pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width()); pos.y = clamp(0, e.pageY - offs...
{ return value < min ? min : (value > max ? max : value); }
identifier_body
setup.py
. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABIL...
setuptools.config.ConfigOptionsHandler = ShimConfigOptionsHandler else: """This is a shim for setuptools<required.""" import functools import io import json import sys import warnings try: import setuptools.config def filter_out_unknown_section(i): def chi...
find_kwargs = super( ShimConfigOptionsHandler, self ).parse_section_packages__find(section_options) return stringify_dict_contents(find_kwargs)
identifier_body
setup.py
. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABIL...
(s): @functools.wraps(s) def sw(**attrs): try: validate_required_python_or_fail(attrs.get('python_requires')) except RuntimeError as re: sys.exit('{} {!s}'.format(attrs['name'], re)) return s(**attrs) return sw setuptools.s...
verify_required_python_runtime
identifier_name
setup.py
. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABIL...
return ''.join(descs) def cfg_val_to_list(v): """Turn config val to list and filter out empty lines.""" return list(filter(bool, map(str.strip, str(v).strip().splitlines()))) def cfg_val_to_dict(v): """Turn config val to dict and filter out empty lines.""" return dict(...
with io.open(fname, encoding='utf-8') as f: descs.append(f.read())
conditional_block
setup.py
Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ...
) ver = tuple(map(int, raw_ver)) yield op_func, ver break def validate_required_python_or_fail(python_requires=None): if python_requires is None: return python_version = sys.version_info preds = parse_predicates(py...
raw_ver = itertools.takewhile( is_decimal, c[len(op_sign):].strip().split('.'),
random_line_split
WikipediaDataCommand.py
import os, sys basePlugPath = os.path.join("..", "..") sys.path.insert(0, os.path.join(basePlugPath, "api")) sys.path.insert(0, os.path.join(basePlugPath, "external")) # TODO - know difference between module import vs package import? import drawingboard from pattern.web import Wikipedia import pprint pp = pprint.Pr...
return article.title def main(): wp = WikipediaDataCommand(dummy="dummy") wp.start(en="english") res = wp.execute(search="Like of Pi") #for k in res: # print "key={0}".format(k) pp.pprint(res) if __name__ == '__main__': main()
print s.title.upper() print print s.content print
conditional_block
WikipediaDataCommand.py
import os, sys basePlugPath = os.path.join("..", "..") sys.path.insert(0, os.path.join(basePlugPath, "api")) sys.path.insert(0, os.path.join(basePlugPath, "external")) # TODO - know difference between module import vs package import? import drawingboard from pattern.web import Wikipedia import pprint pp = pprint.Pr...
def set_params(self, **kwargs): pass def get_params(self, **kwargs): pass #def submit_command(self, port, **commandArgs): def execute(self, **commandArgs): searchString = commandArgs.get("search", "life of pi") #from:decebel (from:username is also supported) print("searching for {0}: ").format(s...
"""Configures the command. - sets the display name of the command - sets initial status string - sets a default icon - NO. Default Icon setup should happen well before this stage. Maybe a load api. - sets is_initialized to return true, once all is well. TODO: Should we check for a net connection? Note: al...
identifier_body
WikipediaDataCommand.py
import os, sys basePlugPath = os.path.join("..", "..") sys.path.insert(0, os.path.join(basePlugPath, "api")) sys.path.insert(0, os.path.join(basePlugPath, "external")) # TODO - know difference between module import vs package import? import drawingboard from pattern.web import Wikipedia import pprint pp = pprint.Pre...
#for k in res: # print "key={0}".format(k) pp.pprint(res) if __name__ == '__main__': main()
def main(): wp = WikipediaDataCommand(dummy="dummy") wp.start(en="english") res = wp.execute(search="Like of Pi")
random_line_split
WikipediaDataCommand.py
import os, sys basePlugPath = os.path.join("..", "..") sys.path.insert(0, os.path.join(basePlugPath, "api")) sys.path.insert(0, os.path.join(basePlugPath, "external")) # TODO - know difference between module import vs package import? import drawingboard from pattern.web import Wikipedia import pprint pp = pprint.Pr...
(self, **kwargs): drawingboard.DataCommand.__init__(self, **kwargs) print "init called " #self.drawingboard.DataCommand self.args = {} def load_resources(self, **kwargs): """sets initial status of loading icon. then loads the icon. then sets various other things and as it does this, it will keep calling ...
__init__
identifier_name
test_memorizingfile.py
#!/usr/bin/env python # # Copyright 2009, 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...
(self, memorizing_file, num_read, expected_list): for unused in range(num_read): memorizing_file.readline() actual_list = memorizing_file.get_memorized_lines() self.assertEqual(len(expected_list), len(actual_list)) for expected, actual in zip(expected_list, actual_list): ...
check
identifier_name
test_memorizingfile.py
#!/usr/bin/env python # # Copyright 2009, 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...
# vi:sts=4 sw=4 et
unittest.main()
conditional_block
test_memorizingfile.py
#!/usr/bin/env python # # Copyright 2009, 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...
# vi:sts=4 sw=4 et
unittest.main()
random_line_split
test_memorizingfile.py
#!/usr/bin/env python # # Copyright 2009, 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...
def test_get_memorized_lines_limit_memorized_lines(self): memorizing_file = memorizingfile.MemorizingFile(StringIO.StringIO( 'Hello\nWorld\nWelcome'), 2) self.check(memorizing_file, 3, ['Hello\n', 'World\n']) def test_get_memorized_lines_empty_file(self): memorizing_fi...
memorizing_file = memorizingfile.MemorizingFile(StringIO.StringIO( 'Hello\nWorld\nWelcome')) self.check(memorizing_file, 3, ['Hello\n', 'World\n', 'Welcome'])
identifier_body
auth.js
// import jwtUtils from './jsonwebtoken'; const store = global.localStorage; const document = global.document; const fetchFromStore = (key) => { // load any stored value from sessionStorage let initValue = store && store.getItem(key); if (typeof initValue !== 'undefined') { try { initValue = JSON.pars...
let userProfile; const decodeUserFromJwt = (jwt) => { const decoded = jwtUtils.decode(jwt, { complete: true }); userProfile = decoded.payload.profile; return userProfile; }; const decodeAllJwt = (jwt) => { const decoded = jwtUtils.decode(jwt, { complete: true }); const { payload } = decoded; return paylo...
const eraseCookie = (name) => { storeCookie(name, '', -1); };
random_line_split
auth.js
// import jwtUtils from './jsonwebtoken'; const store = global.localStorage; const document = global.document; const fetchFromStore = (key) => { // load any stored value from sessionStorage let initValue = store && store.getItem(key); if (typeof initValue !== 'undefined') { try { initValue = JSON.pars...
function clearPolicy() { eraseCookie('CloudFront-Policy', ''); eraseCookie('CloudFront-Key-Pair-Id', ''); eraseCookie('CloudFront-Signature', ''); } // Init JWT from session store let sessionJwt = fetchFromStore('jwt'); if (sessionJwt) { storeJwt({ jwt: sessionJwt }); } function readOnlyJwt() { return fet...
{ const { policy, signature } = data; const keyId = data.key_id; storeCookie('CloudFront-Policy', policy); storeCookie('CloudFront-Key-Pair-Id', keyId); storeCookie('CloudFront-Signature', signature); }
identifier_body
auth.js
// import jwtUtils from './jsonwebtoken'; const store = global.localStorage; const document = global.document; const fetchFromStore = (key) => { // load any stored value from sessionStorage let initValue = store && store.getItem(key); if (typeof initValue !== 'undefined') { try { initValue = JSON.pars...
} return null; } function readOnlyUserData() { sessionJwt = fetchFromStore('jwt'); if (sessionJwt) { if (sessionJwt === 'undefined') { storeValue('jwt', null); } else { return decodeAllJwt(sessionJwt); } } return null; } function logout() { // clear JWT storeValue('jwt', null...
{ return decodeUserFromJwt(sessionJwt); }
conditional_block
auth.js
// import jwtUtils from './jsonwebtoken'; const store = global.localStorage; const document = global.document; const fetchFromStore = (key) => { // load any stored value from sessionStorage let initValue = store && store.getItem(key); if (typeof initValue !== 'undefined') { try { initValue = JSON.pars...
(data, refreshJwt) { if (data.jwt && data.jwt !== 'undefined') { // store raw jwt storeValue('jwt', data.jwt); // decode and store mapUserId decodeUserFromJwt(data.jwt); } if (typeof refreshJwt === 'function') { clearInterval(refreshJwtTimerId); refreshJwtTimerId = setInterval(refreshJwt...
storeJwt
identifier_name
index.js
function solve(params)
} } var sum = min + max; result.push(sum); } console.log(result.join(',')); //print answer } var test1 = ['4', '2', '1 3 1 8'], test2 = ['5', '3', '7 7 8 9 10']; console.log(solve(test1)); console.log(solve(test2));
{ var N = parseInt(params[0]), K = parseInt(params[1]), numbersAsString = params[2]; var numbers = numbersAsString.split(' ').map(Number); var result = []; for (var i = 0; i < N; i += 1) { if(i+K-1 === N) { break; } var min = 1000000000, ...
identifier_body
index.js
function solve(params) { var N = parseInt(params[0]), K = parseInt(params[1]), numbersAsString = params[2]; var numbers = numbersAsString.split(' ').map(Number); var result = []; for (var i = 0; i < N; i += 1)
console.log(result.join(',')); //print answer } var test1 = ['4', '2', '1 3 1 8'], test2 = ['5', '3', '7 7 8 9 10']; console.log(solve(test1)); console.log(solve(test2));
{ if(i+K-1 === N) { break; } var min = 1000000000, max = -1000000000; for (var j = 0; j < K; j += 1) { if(numbers[i+j] > max) { max = numbers[j+i]; } if(numbers[i+j] < min) { min = numbers[j+i]; ...
conditional_block
index.js
function solve(params) { var N = parseInt(params[0]), K = parseInt(params[1]), numbersAsString = params[2]; var numbers = numbersAsString.split(' ').map(Number); var result = []; for (var i = 0; i < N; i += 1) { if(i+K-1 === N) { break;
max = -1000000000; for (var j = 0; j < K; j += 1) { if(numbers[i+j] > max) { max = numbers[j+i]; } if(numbers[i+j] < min) { min = numbers[j+i]; } } var sum = min + max; result.push(sum); } ...
} var min = 1000000000,
random_line_split
index.js
function
(params) { var N = parseInt(params[0]), K = parseInt(params[1]), numbersAsString = params[2]; var numbers = numbersAsString.split(' ').map(Number); var result = []; for (var i = 0; i < N; i += 1) { if(i+K-1 === N) { break; } var min = 1000000000, ...
solve
identifier_name
clear_bits_geq.rs
use word::{Word, ToWord, UnsignedWord}; /// Clears all bits of `x` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: bzhi. /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8); /// assert_...
impl<T: Word> ClearBitsGeq for T { #[inline] fn clear_bits_geq<U: UnsignedWord>(self, n: U) -> Self { clear_bits_geq(self, n) } }
random_line_split
clear_bits_geq.rs
use word::{Word, ToWord, UnsignedWord}; /// Clears all bits of `x` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: bzhi. /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8); /// assert_...
<U: UnsignedWord>(self, n: U) -> Self { clear_bits_geq(self, n) } }
clear_bits_geq
identifier_name