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
state.test.ts
import * as assert from 'assert'; import 'mocha'; import { ExtensionContext, extensions } from 'vscode'; suite('vscode API - globalState / workspaceState', () => { let extensionContext: ExtensionContext; suiteSetup(async () => { // Trigger extension activation and grab the context as some tests depend on it awa...
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
random_line_split
tkwindow.py
# -*- coding: utf-8 *-* # made for python3! from tkinter import * from tkinter.ttk import * class TkWindow(): registers = {}
self.parent = parent #Tk or toplevel self.w = width self.h = height self.make_gui(title) self.loaded() def loaded(self): pass # overload me """register another window to receive a signal""" @classmethod def register(cls, target, signame): if not ...
def __init__(self, parent, title, width=400, height=300):
random_line_split
tkwindow.py
# -*- coding: utf-8 *-* # made for python3! from tkinter import * from tkinter.ttk import * class TkWindow(): registers = {} def __init__(self, parent, title, width=400, height=300): self.parent = parent #Tk or toplevel self.w = width self.h = height self.make_gui(ti...
entry = Entry(parent, **options) if width: entry.config(width=width) entry.grid(row=erow, column=ecol, sticky=W) return entry def setentryvalue(self, entry, value): entry.delete(0,END) entry.insert(0, value) def settextvalue(self, entr...
Label(parent, text=caption).grid(row=lrow, column=lcol, sticky=E)
conditional_block
tkwindow.py
# -*- coding: utf-8 *-* # made for python3! from tkinter import * from tkinter.ttk import * class TkWindow(): registers = {} def __init__(self, parent, title, width=400, height=300): self.parent = parent #Tk or toplevel self.w = width self.h = height self.make_gui(ti...
"""send a signal to all registered windows""" def send(self, signame, data=None): cls = self.__class__ for targ, sigs in cls.registers.items(): if sigs != None: if signame in sigs: targ.receive(self, signame, data) """receive...
if not target in cls.registers: cls.registers[target] = [] cls.registers[target].append(signame)
identifier_body
tkwindow.py
# -*- coding: utf-8 *-* # made for python3! from tkinter import * from tkinter.ttk import * class TkWindow(): registers = {} def __init__(self, parent, title, width=400, height=300): self.parent = parent #Tk or toplevel self.w = width self.h = height self.make_gui(ti...
(self, title): self.parent.title(title) Style().configure("TFrame", padding=5) self.frame = Frame(self.parent, width=self.w, height=self.h) def makelabel(self, parent, lcol=0, lrow=0, caption='', **options): entry = Label(parent, text=caption, **options).gr...
make_gui
identifier_name
widgetController.ts
/// <reference path="../../_all.ts" /> module common { export class userMenuWidgetController { static $inject = ['config', '$mdPanel', 'loginQueryService', '$rootScope', '$scope']; constructor( private config: common.config, private $mdPanel: angular.material.IPanelService...
{ this.loginService.logOut(); this.closeMenu(); if (!this.estaEnHome) window.location.href = '../home/index.html'; } closeMenu(): void { this.mdPanelRef.close(); } seleccionarItem(item: menuItem): void { window...
Out()
identifier_name
widgetController.ts
/// <reference path="../../_all.ts" /> module common { export class userMenuWidgetController { static $inject = ['config', '$mdPanel', 'loginQueryService', '$rootScope', '$scope']; constructor( private config: common.config, private $mdPanel: angular.material.IPanelService...
}); this.verificarLogueo(); this.$scope.$on(this.config.eventIndex.usuarios.perfilActualizado, (e, args: common.perfilActualizado) => { if (this.estaLogueado && this.usuario === args.usuario) { this.nombreParaMostrar = args...
this.$rootScope.$on(this.config.eventIndex.login.loggedOut, (e, args) => { this.verificarLogueo();
random_line_split
widgetController.ts
/// <reference path="../../_all.ts" /> module common { export class userMenuWidgetController { static $inject = ['config', '$mdPanel', 'loginQueryService', '$rootScope', '$scope']; constructor( private config: common.config, private $mdPanel: angular.material.IPanelService...
} class panelMenuController { static $inject = ['mdPanelRef', 'loginService', 'config']; private estaEnHome: boolean; constructor( private mdPanelRef: angular.material.IPanelRef, private loginService: login.loginService, private config: common.config ...
var result = this.loginQueryService.tryGetLocalLoginInfo(); if (result !== undefined && result.loginExitoso) { // verificar si no hay una peticion para que se desloguee this.estaLogueado = true; this.usuario = result.usuario; ...
identifier_body
widgetController.ts
/// <reference path="../../_all.ts" /> module common { export class userMenuWidgetController { static $inject = ['config', '$mdPanel', 'loginQueryService', '$rootScope', '$scope']; constructor( private config: common.config, private $mdPanel: angular.material.IPanelService...
else { this.estaLogueado = false; } } } class panelMenuController { static $inject = ['mdPanelRef', 'loginService', 'config']; private estaEnHome: boolean; constructor( private mdPanelRef: angular.material.IPanelRef, ...
// verificar si no hay una peticion para que se desloguee this.estaLogueado = true; this.usuario = result.usuario; this.nombreParaMostrar = result.nombreParaMostrar; this.avatarUrl = result.avatarUrl; ...
conditional_block
particle-test.js
import { describe, it } from 'mocha'; import { expect } from 'chai'; import { particle } from '../js/particle'; import { vector } from '../js/vector'; describe('Particle Library', () => { describe('Can create create vectors', () => { const p1 = particle.create(1, 2, 30, Math.PI / 6, 20); it('sets the X valu...
const y = p2.position.getY() - p1.position.getY(); const x = p2.position.getX() - p1.position.getX(); const expected = Math.sqrt((x * x) + (y * y)); expect(result).to.equal(expected); }); it('updates the velocity and position with gravity', () => { const p1 = particle.create(4, 4...
random_line_split
documentContext.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
for (let folder of workspaceFolders) { let folderURI = folder.uri; if (!endsWith(folderURI, '/')) { folderURI = folderURI + '/'; } if (startsWith(documentUri, folderURI)) { return folderURI; } } return void 0; } return { resolveReference: (ref, base = documentUri) => { if (ref[0] ==...
function getRootFolder(): string | undefined {
random_line_split
documentContext.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return folderUri + ref.substr(1); } } } return url.resolve(base, ref); }, }; }
{ function getRootFolder(): string | undefined { for (let folder of workspaceFolders) { let folderURI = folder.uri; if (!endsWith(folderURI, '/')) { folderURI = folderURI + '/'; } if (startsWith(documentUri, folderURI)) { return folderURI; } } return void 0; } return { resolveReferenc...
identifier_body
documentContext.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} } return url.resolve(base, ref); }, }; }
{ return folderUri + ref.substr(1); }
conditional_block
documentContext.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(documentUri: string, workspaceFolders: WorkspaceFolder[]): DocumentContext { function getRootFolder(): string | undefined { for (let folder of workspaceFolders) { let folderURI = folder.uri; if (!endsWith(folderURI, '/')) { folderURI = folderURI + '/'; } if (startsWith(documentUri, folderURI)) { ...
getDocumentContext
identifier_name
yield-while-local-borrowed.rs
// Copyright 2017 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 ...
unsafe fn borrow_local() { // Not OK to yield with a borrow of a temporary. // // (This error occurs because the region shows up in the type of // `b` and gets extended by region inference.) let mut b = move || { let a = 3; { let b = &a; //~^ ERROR borrow ma...
{ // No error here -- `a` is not in scope at the point of `yield`. let mut b = move || { { let a = &mut 3; } yield(); }; b.resume(); }
identifier_body
yield-while-local-borrowed.rs
// Copyright 2017 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 ...
b.resume(); } unsafe fn borrow_local() { // Not OK to yield with a borrow of a temporary. // // (This error occurs because the region shows up in the type of // `b` and gets extended by region inference.) let mut b = move || { let a = 3; { let b = &a; //~...
yield(); };
random_line_split
yield-while-local-borrowed.rs
// Copyright 2017 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 ...
() { // Not OK to yield with a borrow of a temporary. // // (This error occurs because the region shows up in the type of // `b` and gets extended by region inference.) let mut b = move || { let a = &mut 3; //~^ ERROR borrow may still be in use when generator yields (Ast) //~...
borrow_local_inline
identifier_name
thread_pool.rs
use std::sync::mpsc; use std::sync::Arc; use std::sync::Mutex; use std::thread; enum Message { NewJob(Job), Terminate, } pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Message>, } trait FnBox { fn call_box(self: Box<Self>); } impl<F: FnOnce()> FnBox for F { fn call_box(se...
(&mut self) { println!("Sending terminate message to all workers."); for _ in &mut self.workers { self.sender.send(Message::Terminate).unwrap(); } println!("Shutting down all workers."); for worker in &mut self.workers { println!("Shutting down worker {...
drop
identifier_name
thread_pool.rs
use std::sync::mpsc; use std::sync::Arc; use std::sync::Mutex; use std::thread; enum Message { NewJob(Job), Terminate, } pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Message>, } trait FnBox { fn call_box(self: Box<Self>); } impl<F: FnOnce()> FnBox for F { fn call_box(se...
Message::Terminate => { break; } } }); Worker { id, thread: Some(thread), } } }
{ job.call_box(); }
conditional_block
thread_pool.rs
use std::sync::mpsc; use std::sync::Arc;
enum Message { NewJob(Job), Terminate, } pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Message>, } trait FnBox { fn call_box(self: Box<Self>); } impl<F: FnOnce()> FnBox for F { fn call_box(self: Box<F>) { (*self)() } } type Job = Box<dyn FnBox + Send + 'stati...
use std::sync::Mutex; use std::thread;
random_line_split
thread_pool.rs
use std::sync::mpsc; use std::sync::Arc; use std::sync::Mutex; use std::thread; enum Message { NewJob(Job), Terminate, } pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Message>, } trait FnBox { fn call_box(self: Box<Self>); } impl<F: FnOnce()> FnBox for F { fn call_box(se...
pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(Message::NewJob(job)).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { println!("Sending terminate message to all workers."); for _ i...
{ assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { work...
identifier_body
with_position.rs
use std::iter::{Fuse,Peekable}; /// An iterator adaptor that wraps each element in an [`Position`](../enum.Position.html). /// /// Iterator element type is `Position<I::Item>`. /// /// See [`.with_position()`](../trait.Itertools.html#method.with_position) for more information. #[must_use = "iterator adaptors are lazy ...
/// A value yielded by `WithPosition`. /// Indicates the position of this element in the iterator results. /// /// See [`.with_position()`](trait.Itertools.html#method.with_position) for more information. #[derive(Copy, Clone, Debug, PartialEq)] pub enum Position<T> { /// This is the first element. First(T), ...
{ WithPosition { handled_first: false, peekable: iter.fuse().peekable(), } }
identifier_body
with_position.rs
use std::iter::{Fuse,Peekable}; /// An iterator adaptor that wraps each element in an [`Position`](../enum.Position.html). /// /// Iterator element type is `Position<I::Item>`. /// /// See [`.with_position()`](../trait.Itertools.html#method.with_position) for more information. #[must_use = "iterator adaptors are lazy ...
} } fn size_hint(&self) -> (usize, Option<usize>) { self.peekable.size_hint() } } impl<I> ExactSizeIterator for WithPosition<I> where I: ExactSizeIterator, { }
// Iterator is finished. None => None,
random_line_split
with_position.rs
use std::iter::{Fuse,Peekable}; /// An iterator adaptor that wraps each element in an [`Position`](../enum.Position.html). /// /// Iterator element type is `Position<I::Item>`. /// /// See [`.with_position()`](../trait.Itertools.html#method.with_position) for more information. #[must_use = "iterator adaptors are lazy ...
(&self) -> (usize, Option<usize>) { self.peekable.size_hint() } } impl<I> ExactSizeIterator for WithPosition<I> where I: ExactSizeIterator, { }
size_hint
identifier_name
type_of.rs
_argument in tupled_arguments.iter() { result.push(tupled_argument); } } _ => { ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \ is neither a tuple nor unit") } } result } pub fn type_of_rust_fn<'a...
} } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // ...
random_line_split
type_of.rs
Type::i1(cx) } else { type_of(cx, t) } } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // It i...
llvm_type_name
identifier_name
type_of.rs
in tupled_arguments.iter() { result.push(tupled_argument); } } _ => { ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \ is neither a tuple nor unit") } } result } pub fn type_of_rust_fn<'a, 'tcx>(c...
Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty); assert!(!t.has_escaping_regions()); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are de...
{ fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { // It is possible to end up here with a sized type. This happens with a // struct which might be unsized, but is monomorphised to a sized type. // In this case we'll fake a fat pointer with no unsize info ...
identifier_body
type_of.rs
in tupled_arguments.iter() { result.push(tupled_argument); } } _ => { ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \ is neither a tuple nor unit") } } result } pub fn type_of_rust_fn<'a, 'tcx>(c...
ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty,...
{ cx.sess().bug(&format!("trying to take the sizing type of {}, an unsized type", ppaux::ty_to_string(cx.tcx(), t))[]) }
conditional_block
VRWindow.ts
import { app, BrowserWindow, nativeImage, NativeImage } from 'electron'; import vr from 'node-openvr'; import ZephyrNotification from '../models/ZephyrNotification'; import EventUtils from '../utils/EventUtils'; import LogUtils from '../utils/LogUtils'; import VROverlay from './VROverlay'; app.disableHardwareAccelerat...
({ key, name = 'Zephyr', fps = 60, iconPath, system = null }): void { this.vrSystem = system ?? vr.system.VR_Init(vr.EVRApplicationType.VRApplication_Overlay); this.overlay = new VROverlay({ system: this.vrSystem, key: key, name: name, iconPath: iconPath }); this.webContents.setFrameRate(fps); this.ov...
setupOverlay
identifier_name
VRWindow.ts
import { app, BrowserWindow, nativeImage, NativeImage } from 'electron'; import vr from 'node-openvr'; import ZephyrNotification from '../models/ZephyrNotification'; import EventUtils from '../utils/EventUtils'; import LogUtils from '../utils/LogUtils'; import VROverlay from './VROverlay'; app.disableHardwareAccelerat...
this.webContents.on('paint', (..._) => { this.vrDraw(); }); this.webContents.on('dom-ready', () => { this.overlay.show(); this.vrDraw(); setTimeout(() => { this.vrDraw(); }, 1000); }); EventUtils.getInstance().on('vr-show-notification', (payload: any) => { ...
random_line_split
VRWindow.ts
import { app, BrowserWindow, nativeImage, NativeImage } from 'electron'; import vr from 'node-openvr'; import ZephyrNotification from '../models/ZephyrNotification'; import EventUtils from '../utils/EventUtils'; import LogUtils from '../utils/LogUtils'; import VROverlay from './VROverlay'; app.disableHardwareAccelerat...
}); } vrDraw (force = false): void { this.webContents.capturePage().then((image: NativeImage) => { const buf = image.toBitmap(); if (!force && buf.length === 0) { return; } this.overlay.setTextureFromBuffer(buf, { ...image.getSize() }); }).catch((error: any) => { ...
{ LogUtils.verbose('VRWindow', `Creating notification: ${String(JSON.stringify(notification))}`); const iconImg = nativeImage.createFromDataURL(`data:image/png;base64, ${String(notification.icon)}`); const iconBuf = iconImg.toBitmap(); this.overlay.createNotification(`${String(notifica...
conditional_block
VRWindow.ts
import { app, BrowserWindow, nativeImage, NativeImage } from 'electron'; import vr from 'node-openvr'; import ZephyrNotification from '../models/ZephyrNotification'; import EventUtils from '../utils/EventUtils'; import LogUtils from '../utils/LogUtils'; import VROverlay from './VROverlay'; app.disableHardwareAccelerat...
}
{ this.webContents.capturePage().then((image: NativeImage) => { const buf = image.toBitmap(); if (!force && buf.length === 0) { return; } this.overlay.setTextureFromBuffer(buf, { ...image.getSize() }); }).catch((error: any) => { LogUtils.error('VRWindow', `Error when capt...
identifier_body
backuptool.py
import tarfile import time import os import json class BackupTool(object): """Simple backup utility.""" def __init__(self): pass @staticmethod def backup(openbazaar_installation_path, backup_folder_path, on_success_callback=None, on_error_callback...
(json.JSONEncoder): """ A (meant to be immutable) POPO to represent a backup. So that we can tell our Web client about the backups available. """ def __init__(self, file_name=None, full_file_path=None, created_timestamp_millis=None, ...
Backup
identifier_name
backuptool.py
import tarfile import time import os import json class BackupTool(object): """Simple backup utility.""" def __init__(self): pass @staticmethod def backup(openbazaar_installation_path, backup_folder_path, on_success_callback=None, on_error_callback...
return o.to_dict()
conditional_block
backuptool.py
import tarfile
class BackupTool(object): """Simple backup utility.""" def __init__(self): pass @staticmethod def backup(openbazaar_installation_path, backup_folder_path, on_success_callback=None, on_error_callback=None): """ Creates an 'openbazaar-...
import time import os import json
random_line_split
backuptool.py
import tarfile import time import os import json class BackupTool(object): """Simple backup utility.""" def __init__(self): pass @staticmethod def backup(openbazaar_installation_path, backup_folder_path, on_success_callback=None, on_error_callback...
def to_dict(self): """Return a dictionary with attributes of self.""" return { "file_name": self.file_name, "full_file_path": self.full_file_path, "created_timestamp_millis": self.created_timestamp_millis, "size_in_bytes": self.size_in_bytes ...
super(Backup, self).__init__() self.file_name = file_name self.full_file_path = full_file_path self.created_timestamp_millis = created_timestamp_millis self.size_in_bytes = size_in_bytes
identifier_body
svn_fetch.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, wr...
random_line_split
svn_fetch.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
with pkg.stage: try: spack.insecure = secure pkg.do_stage() finally: spack.insecure = False with working_dir(pkg.stage.source_path): assert h() == t.revision file_path = join_path(pkg.stage.source_path, t.file) assert ...
"""Tries to: 1. Fetch the repo using a fetch strategy constructed with supplied args (they depend on type_of_test). 2. Check if the test_file is in the checked out repository. 3. Assert that the repository is at the revision supplied. 4. Add and remove some files, then reset the repo, and ...
identifier_body
svn_fetch.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
( type_of_test, secure, mock_svn_repository, config, refresh_builtin_mock ): """Tries to: 1. Fetch the repo using a fetch strategy constructed with supplied args (they depend on type_of_test). 2. Check if the test_file is in the checked out repository. 3. ...
test_fetch
identifier_name
regress-349653.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-349653.js...
{ enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); void ({y: true ? [1 for (x in [2])] : 3 }) reportCompare(expect, actual, summary); let (a) true ? [2 for each (z in function(id) { return id })] : 3; reportCompare(expect, actual, summary); exitFunc ('test'); }
identifier_body
regress-349653.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-349653.js...
() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); void ({y: true ? [1 for (x in [2])] : 3 }) reportCompare(expect, actual, summary); let (a) true ? [2 for each (z in function(id) { return id })] : 3; reportCompare(expect, actual, summary); exitFunc ('test'); }
test
identifier_name
regress-349653.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-349653.js...
void ({y: true ? [1 for (x in [2])] : 3 }) reportCompare(expect, actual, summary); let (a) true ? [2 for each (z in function(id) { return id })] : 3; reportCompare(expect, actual, summary); exitFunc ('test'); }
random_line_split
app.js
/** * Copyright (C) 2016 Steven Bartels * * 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...
'ngCookies', // 3rd-Party 'ngBonita', 'ngStorage', // Config/Directive/Service 'ProcessDataOpModule', 'CookieConfModule', // Controller 'ReviewRequestControllerModule', ...
[ // Angular 'ngAnimate', 'ngRoute', 'ngResource',
random_line_split
gst010.py
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Pub...
pipeline = \ 'dv1394src guid=%s ! dvdemux name=demux .video ! fakesink' % guid d = do_element_check(pipeline, 'demux', do_check) def errbackResult(failure): log.debug('check', 'returning failed Result, %r' % failure) m = None if failure.check(errors.GStreamerGstError): ...
pad = demux.get_pad('video') if not pad or pad.get_negotiated_caps() == None: raise errors.GStreamerError('Pipeline failed to negotiate?') caps = pad.get_negotiated_caps() s = caps.get_structure(0) w = s['width'] h = s['height'] par = s['pixel-aspect-ratio']...
identifier_body
gst010.py
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Pub...
self.pipeline.set_state(gst.STATE_NULL) self.pipeline = None def do_element_check(pipeline_str, element_name, check_proc, state=None, set_state_deferred=False): """ Parse the given pipeline and set it to the given state. When the bin reaches that state, perform the given check...
self.pipeline.get_bus().remove_signal_watch() self.pipeline.get_bus().disconnect(self.signal_id) self.signal_id = None
conditional_block
gst010.py
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Pub...
(mid, guid): """ Probe the firewire device. Return a deferred firing a result. The result is either: - succesful, with a None value: no device found - succesful, with a dictionary of width, height, and par as a num/den pair - failed @param mid: the id to set on the message. @pa...
check1394
identifier_name
gst010.py
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Pub...
def errbackResult(failure): log.debug('check', 'returning failed Result, %r' % failure) m = None if failure.check(errors.GStreamerGstError): source, gerror, debug = failure.value.args log.debug('check', 'GStreamer GError: %s (debug: %s)' % ( gerror.me...
d = do_element_check(pipeline, 'demux', do_check)
random_line_split
sim.py
""" Pymulator simulation objects """ import json import datetime from .serialize import PandasNumpyEncoderMixIn, hook def importmodel(s): """ Import model from string s specifying a callable. The string has the following structure: package[.package]*.model[:function] For example: ...
'timestamp': str(self.timestamp), 'outputs': self.outputs } if hasattr(self, 'results'): d['results'] = self.results if hasattr(self, 'seed'): d['seed'] = self.seed if hasattr(self, 'state'): d['state'] = self.state retu...
random_line_split
sim.py
""" Pymulator simulation objects """ import json import datetime from .serialize import PandasNumpyEncoderMixIn, hook def importmodel(s): """ Import model from string s specifying a callable. The string has the following structure: package[.package]*.model[:function] For example: ...
return d def dumps(self): return json.dumps(self.todict(), cls=PandasNumpyEncoderMixIn, indent=4) def dump(self, path): with open(path, 'w') as f: f.write(self.dumps()) def loads(self, s): return json.loads(s, hook=hook) def load(self, path): with...
d['state'] = self.state
conditional_block
sim.py
""" Pymulator simulation objects """ import json import datetime from .serialize import PandasNumpyEncoderMixIn, hook def importmodel(s): """ Import model from string s specifying a callable. The string has the following structure: package[.package]*.model[:function] For example: ...
(self, other): def _(obj): d = dict(obj.__dict__) return (d, d.pop('results', None), d.pop('state', None)) return all(map(all, _(self), _(other))) def _getspans(self): return dict(self._spans) def _setspans(self, spans): if not hasattr(self, '_spans'): ...
__eq__
identifier_name
sim.py
""" Pymulator simulation objects """ import json import datetime from .serialize import PandasNumpyEncoderMixIn, hook def importmodel(s): """ Import model from string s specifying a callable. The string has the following structure: package[.package]*.model[:function] For example: ...
def _setspans(self, spans): if not hasattr(self, '_spans'): self._spans= {} for argument, vals_or_range in spans.items(): self._spans[str(argument)] = list(vals_or_range) def _delspans(self): self._spans.clear() spans = property(_getspans, _setspans, _dels...
return dict(self._spans)
identifier_body
mutekitimer.js
/** * MutekiTimer: 0.3.4 */ "use strict"; var window = {}; // __BEGIN__ var MutekiTimer = (function() { var MutekiTimer = function() { initialize.apply(this, arguments); }, $this = MutekiTimer.prototype; var TIMER_PATH = (function() { var BlobBuilder, URL, builder; BlobBuild...
this._ugly_patch = 0; } } else if (this._timerId !== 0) { window.clearInterval(this._timerId); this._timerId = 0; } }; return MutekiTimer; }()); // __END__
window.clearInterval(this._ugly_patch);
random_line_split
mutekitimer.js
/** * MutekiTimer: 0.3.4 */ "use strict"; var window = {}; // __BEGIN__ var MutekiTimer = (function() { var MutekiTimer = function() { initialize.apply(this, arguments); }, $this = MutekiTimer.prototype; var TIMER_PATH = (function() { var BlobBuilder, URL, builder; BlobBuild...
else if (this._timerId !== 0) { window.clearInterval(this._timerId); this._timerId = 0; } }; return MutekiTimer; }()); // __END__
{ this._timer.postMessage(0); if (this._ugly_patch) { window.clearInterval(this._ugly_patch); this._ugly_patch = 0; } }
conditional_block
reflector.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 syntax::ast; use syntax::ast::MetaItem; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtx...
}
random_line_split
reflector.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 syntax::ast; use syntax::ast::MetaItem; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtx...
impl_item.map(|it| push(Annotatable::Item(it))) }, // Or just call it on the first field (supertype). None => { let field_name = def.fields[0].node.ident(); let impl_item = quote_item!(cx, ...
{ if let &Annotatable::Item(ref item) = annotatable { if let ast::ItemStruct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time match def.fields.iter().find( ...
identifier_body
reflector.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 syntax::ast; use syntax::ast::MetaItem; use syntax::codemap::Span; use syntax::ext::base::{Annotatable, ExtCtx...
(cx: &mut ExtCtxt, span: Span, _: &MetaItem, annotatable: &Annotatable, push: &mut FnMut(Annotatable)) { if let &Annotatable::Item(ref item) = annotatable { if let ast::ItemStruct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be h...
expand_reflector
identifier_name
models.py
from django.db import models from django.contrib.auth.models import User from albaproject.settings import MEDIA_ROOT import pdb def _upload_to_generic(prefix_path=None, instance=None, field=None, filename=None): #pdb.set_trace() if not instance.pk: # generate DB PK if not present instance...
return '{0}/{1}/job_{2}/{3}'.format(prefix_path, instance.user.username, instance.pk, field) class Job(models.Model): def __unicode__(self): return str(self.id) def save(self, *args, **kwargs): #pdb.set_trace() _input = self.file_input _job = self...
if not filename: return '{0}/job_{1}/{2}'.format(instance.user.username, instance.pk, field) return '{0}/job_{1}/{2}/{3}'.format(instance.user.username, instance.pk, field, filename)
conditional_block
models.py
from django.db import models from django.contrib.auth.models import User from albaproject.settings import MEDIA_ROOT import pdb def _upload_to_generic(prefix_path=None, instance=None, field=None, filename=None): #pdb.set_trace() if not instance.pk: # generate DB PK if not present instance...
def mapred_dest(self, filename): return _upload_to_generic(None, self, 'mapred', filename) def output_dest(self, filename): return _upload_to_generic(None, self, 'output', filename) def output_path(self): return _upload_to_generic(MEDIA_ROOT, self, 'output', None) ...
random_line_split
models.py
from django.db import models from django.contrib.auth.models import User from albaproject.settings import MEDIA_ROOT import pdb def _upload_to_generic(prefix_path=None, instance=None, field=None, filename=None): #pdb.set_trace() if not instance.pk: # generate DB PK if not present instance...
(models.Model): def __unicode__(self): return str(self.id) def save(self, *args, **kwargs): #pdb.set_trace() _input = self.file_input _job = self.mapred_job _output = self.file_output self.file_input = None self.mapred_job = None self.fil...
Job
identifier_name
models.py
from django.db import models from django.contrib.auth.models import User from albaproject.settings import MEDIA_ROOT import pdb def _upload_to_generic(prefix_path=None, instance=None, field=None, filename=None): #pdb.set_trace() if not instance.pk: # generate DB PK if not present instance...
def output_dest(self, filename): return _upload_to_generic(None, self, 'output', filename) def output_path(self): return _upload_to_generic(MEDIA_ROOT, self, 'output', None) user = models.ForeignKey(User) file_input = models.FileField(upload_to=input_dest, null=Tr...
return _upload_to_generic(None, self, 'mapred', filename)
identifier_body
windowCount.d.ts
import { Observable } from 'rxjs'; /** * Branch out the source Observable values as a nested Observable with each * nested Observable emitting at most `windowSize` values. * * <span class="informal">It's like {@link bufferCount}, but emits a nested * Observable instead of an array.</span> * * <img src="./img/win...
* .map(win => win.skip(1)) // skip first of every 3 clicks * .mergeAll(); // flatten the Observable-of-Observables * result.subscribe(x => console.log(x)); * * @example <caption>Ignore every 3rd click event, starting from the third one</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * va...
random_line_split
ub-nonnull.rs
// Copyright 2018 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
ub-nonnull.rs
// Copyright 2018 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 ...
struct RestrictedRange1(u32); const BAD_RANGE1: RestrictedRange1 = unsafe { RestrictedRange1(42) }; //~^ ERROR it is undefined behavior to use this value #[rustc_layout_scalar_valid_range_start(30)] #[rustc_layout_scalar_valid_range_end(10)] struct RestrictedRange2(u32); const BAD_RANGE2: RestrictedRange2 = unsafe { R...
#[rustc_layout_scalar_valid_range_end(30)]
random_line_split
ub-nonnull.rs
// Copyright 2018 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 ...
(u32); const BAD_RANGE1: RestrictedRange1 = unsafe { RestrictedRange1(42) }; //~^ ERROR it is undefined behavior to use this value #[rustc_layout_scalar_valid_range_start(30)] #[rustc_layout_scalar_valid_range_end(10)] struct RestrictedRange2(u32); const BAD_RANGE2: RestrictedRange2 = unsafe { RestrictedRange2(20) }; ...
RestrictedRange1
identifier_name
ElementAddress.ts
import { Arr, Fun, Optional } from '@ephox/katamari'; import * as Compare from '../dom/Compare'; import { SugarElement } from '../node/SugarElement'; import * as PredicateFind from './PredicateFind'; import * as SelectorFilter from './SelectorFilter'; import * as SelectorFind from './SelectorFind'; import * as Travers...
parent, children, element, index }); const childOf = (element: SugarElement<Node>, ancestor: SugarElement<Node>): Optional<SugarElement<Node>> => PredicateFind.closest(element, (elem) => Traverse.parent(elem).exists((parent) => Compare.eq(parent, ancestor))); const indexInParent = <E extends Node> (elem...
const inParent = <P, C, E>(parent: SugarElement<P>, children: SugarElement<C>[], element: SugarElement<E>, index: number): AddressInParent<P, C, E> => ({
random_line_split
lib.rs
#[derive(Debug, PartialEq)] pub enum
{ InvalidInputBase, InvalidOutputBase, InvalidDigit(u32), } /// /// Convert a number between two bases. /// /// A number is any slice of digits. /// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize). /// Bases are specified as unsigned integers. /// /// Return an `Err(.)` if the conversio...
Error
identifier_name
lib.rs
#[derive(Debug, PartialEq)] pub enum Error { InvalidInputBase, InvalidOutputBase, InvalidDigit(u32), } /// /// Convert a number between two bases. /// /// A number is any slice of digits. /// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize). /// Bases are specified as unsigned integers. /...
/// Input /// number: &[4, 2] /// from_base: 10 /// to_base: 2 /// Result /// Ok(vec![1, 0, 1, 0, 1, 0]) /// /// The example corresponds to converting the number 42 from decimal /// which is equivalent to 101010 in binary. /// /// /// Notes: /// * The empty slice ( "[]" ) is equal to the number 0. /// * Never...
/// /// Example:
random_line_split
friend_request.js
OW_FriendRequest = function( itemKey, params ) { var listLoaded = false; var model = OW.Console.getData(itemKey); var list = OW.Console.getItem(itemKey); var counter = new OW_DataModel(); counter.addObserver(this); this.onDataChange = function( data ) { var newCount = data.get('n...
c["all"] = counter.get("all") - 1; counter.set(c); list.removeItem(item); return this; }; this.send = function( command, data ) { var request = $.ajax({ url: params.rsp, type: "POST", data: { "command": command,...
{ c["new"] = counter.get("new") - 1; }
conditional_block
friend_request.js
OW_FriendRequest = function( itemKey, params ) { var listLoaded = false; var model = OW.Console.getData(itemKey); var list = OW.Console.getItem(itemKey); var counter = new OW_DataModel(); counter.addObserver(this); this.onDataChange = function( data ) { var newCount = data.get('ne...
} OW.FriendRequest = null;
random_line_split
05_menus.py
import Tkinter as tk root = tk.Tk() def noop():
menubar = tk.Menu(root) # create a pulldown menu, and add it to the menu bar filemenu = tk.Menu(menubar) filemenu.add_command(label="Open", command=noop) filemenu.add_command(label="Save", command=noop) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="File", m...
pass
identifier_body
05_menus.py
import Tkinter as tk root = tk.Tk() def noop(): pass menubar = tk.Menu(root) # create a pulldown menu, and add it to the menu bar filemenu = tk.Menu(menubar) filemenu.add_command(label="Open", command=noop) filemenu.add_command(label="Save", command=noop) filemenu.add_separator() filemenu.add_command(label="Exit", ...
root.mainloop()
# display the menu root.config(menu=menubar)
random_line_split
05_menus.py
import Tkinter as tk root = tk.Tk() def
(): pass menubar = tk.Menu(root) # create a pulldown menu, and add it to the menu bar filemenu = tk.Menu(menubar) filemenu.add_command(label="Open", command=noop) filemenu.add_command(label="Save", command=noop) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="...
noop
identifier_name
keyframes.rs
Percentage { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= ...
&self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } /// Parse a keyframe selector from CSS input. pub fn parse(input: &mut Parser) -> ...
pub fn percentages(&self) -> &[KeyframePercentage] {
random_line_split
keyframes.rs
Percentage { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= ...
_ => false, }; KeyframesStep { start_percentage: percentage, value: value, declared_timing_function: declared_timing_function, } } /// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'. ...
{ block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| { match *prop_decl { PropertyDeclaration::AnimationTimingFunction(..) => true, _ => false, } }) }
conditional_block
keyframes.rs
Percentage { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= ...
<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.selector.percentages().iter(); try!(iter.next().unwrap().to_css(dest)); for percentage in iter { try!(write!(dest, ", ")); try!(percentage.to_css(dest)); ...
to_css
identifier_name
keyframes.rs
Percentage { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= ...
} /// A keyframes selector is a list of percentages or from/to symbols, which are /// converted at parse time to percentages. #[derive(Debug, PartialEq)] pub struct KeyframeSelector(Vec<KeyframePercentage>); impl KeyframeSelector { /// Return the list of percentages this selector contains. #[inline] pub f...
{ let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() { KeyframePercentage::new(0.) } else if input.try(|input| input.expect_ident_matching("to")).is_ok() { KeyframePercentage::new(1.) } else { let percentage = try!(input.expect_...
identifier_body
fuzzy_logic_defuzzifier.py
# COPYRIGHT: Robosub Club of the Palouse under the GPL v3 import argparse import time import os import sys from copy import deepcopy from random import random sys.path.append(os.path.abspath("../..")) from util.communication.grapevine import Communicator # TODO: This module should take the fuzzy sets produced by # mo...
def commandline(): parser = argparse.ArgumentParser(description='Mock module.') parser.add_argument('-e', '--epoch', type=float, default=0.05, help='Sleep time per cycle.') return parser.parse_args() if __name__ == '__main__': args = commandline() main(args)
time.sleep(args.epoch)
random_line_split
fuzzy_logic_defuzzifier.py
# COPYRIGHT: Robosub Club of the Palouse under the GPL v3 import argparse import time import os import sys from copy import deepcopy from random import random sys.path.append(os.path.abspath("../..")) from util.communication.grapevine import Communicator # TODO: This module should take the fuzzy sets produced by # mo...
time.sleep(args.epoch) def commandline(): parser = argparse.ArgumentParser(description='Mock module.') parser.add_argument('-e', '--epoch', type=float, default=0.05, help='Sleep time per cycle.') return parser.parse_args() if __name__ == '__main__': args = commandline...
last_packet_time = rx_packet['timestamp'] tx_packet = { 'vector': rx_packet['vector'], 'rotation': rx_packet['rotation']} com.publish_message(tx_packet)
conditional_block
fuzzy_logic_defuzzifier.py
# COPYRIGHT: Robosub Club of the Palouse under the GPL v3 import argparse import time import os import sys from copy import deepcopy from random import random sys.path.append(os.path.abspath("../..")) from util.communication.grapevine import Communicator # TODO: This module should take the fuzzy sets produced by # mo...
(args): com = Communicator("movement/physical") last_packet_time = 0.0 while True: rx_packet = com.get_last_message("movement/stabilization") if rx_packet and rx_packet['timestamp'] > last_packet_time: last_packet_time = rx_packet['timestamp'] tx_packet = { ...
main
identifier_name
fuzzy_logic_defuzzifier.py
# COPYRIGHT: Robosub Club of the Palouse under the GPL v3 import argparse import time import os import sys from copy import deepcopy from random import random sys.path.append(os.path.abspath("../..")) from util.communication.grapevine import Communicator # TODO: This module should take the fuzzy sets produced by # mo...
def commandline(): parser = argparse.ArgumentParser(description='Mock module.') parser.add_argument('-e', '--epoch', type=float, default=0.05, help='Sleep time per cycle.') return parser.parse_args() if __name__ == '__main__': args = commandline() main(args)
com = Communicator("movement/physical") last_packet_time = 0.0 while True: rx_packet = com.get_last_message("movement/stabilization") if rx_packet and rx_packet['timestamp'] > last_packet_time: last_packet_time = rx_packet['timestamp'] tx_packet = { '...
identifier_body
TextGeometryDescriptor.js
import * as THREE from 'three'; import PropTypes from 'prop-types'; import GeometryDescriptorBase from './GeometryDescriptorBase'; class TextGeometryDescriptor extends GeometryDescriptorBase { constructor(react3RendererInstance)
type: PropTypes.number, update: this.triggerRemount, default: 50, }); this.hasProp('curveSegments', { type: PropTypes.number, update: this.triggerRemount, default: 12, }); this.hasProp('bevelEnabled', { type: PropTypes.bool, update: this.tri...
{ super(react3RendererInstance); this.hasProp('text', { type: PropTypes.string.isRequired, update: this.triggerRemount, default: 'TEXT MISSING', }); this.hasProp('font', { type: PropTypes.instanceOf(THREE.Font).isRequired, update: this.triggerRemount, }); ...
identifier_body
TextGeometryDescriptor.js
import * as THREE from 'three'; import PropTypes from 'prop-types'; import GeometryDescriptorBase from './GeometryDescriptorBase'; class TextGeometryDescriptor extends GeometryDescriptorBase {
(react3RendererInstance) { super(react3RendererInstance); this.hasProp('text', { type: PropTypes.string.isRequired, update: this.triggerRemount, default: 'TEXT MISSING', }); this.hasProp('font', { type: PropTypes.instanceOf(THREE.Font).isRequired, update: this....
constructor
identifier_name
TextGeometryDescriptor.js
import * as THREE from 'three'; import PropTypes from 'prop-types'; import GeometryDescriptorBase from './GeometryDescriptorBase'; class TextGeometryDescriptor extends GeometryDescriptorBase { constructor(react3RendererInstance) { super(react3RendererInstance); this.hasProp('text', { type...
} } module.exports = TextGeometryDescriptor;
curveSegments, bevelEnabled, bevelThickness, bevelSize, });
random_line_split
merge_csv.py
import sqlite3 import csv def csv_to_arr(csv_file, start=1, has_header=True): arr = [] with open(csv_file, 'rU') as f: reader = csv.reader(f) arr = list(reader) if arr == []: return header = "" if has_header: header = ','.join(arr[0]) arr = arr[start:] return header, arr else: return arr[start:...
(): # Register the adapter # sqlite3.register_adapter(decimal.Decimal, adapt_decimal) # Register the converter # sqlite3.register_converter("DECTEXT", convert_decimal) conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES) conn.row_factory = sqlite3.Row cur = conn.cursor() return conn, cur d...
db_cur
identifier_name
merge_csv.py
import sqlite3 import csv def csv_to_arr(csv_file, start=1, has_header=True): arr = [] with open(csv_file, 'rU') as f: reader = csv.reader(f) arr = list(reader) if arr == []: return header = "" if has_header: header = ','.join(arr[0]) arr = arr[start:] return header, arr else: return arr[start:]...
create_tbl(cur, "new", new_header, new_arr) create_tbl(cur, "old", old_header, old_arr) # print new_header cur.execute("""select new.TRADEID,new.PORTFOLIOID,new.BROKEREXCHANGEID,new.MIC,new.USERID,new.IMSID,new.ORDERID,new.WAY,new.QUANTITY,new.PRICE,new.TIMESTAMP,new.IMSUSERID,new.USERDATA,old.MARKETDATA,new.EXECUTION...
random_line_split
merge_csv.py
import sqlite3 import csv def csv_to_arr(csv_file, start=1, has_header=True): arr = [] with open(csv_file, 'rU') as f: reader = csv.reader(f) arr = list(reader) if arr == []: return header = "" if has_header: header = ','.join(arr[0]) arr = arr[start:] return header, arr else: return arr[start:...
if arr is not None: cur.executemany("INSERT INTO " + tbl_name + " VALUES ("+question_marks(header)+")", arr) return def arr_to_csv(file_name, header, data_arr): csv_file = open(file_name, 'wb') wr = csv.writer(csv_file) wr.writerow(header.split(',')) for data_row in data_arr: line = [] for ele in dat...
cur.execute("CREATE TABLE " + tbl_name + " (" + header.replace("id,", "id PRIMARY KEY,") + " );") if index_arr is not None: for index in index_arr: cur.execute("CREATE INDEX " + tbl_name + "_" + index + " ON " + tbl_name + " (" + index + ");")
conditional_block
merge_csv.py
import sqlite3 import csv def csv_to_arr(csv_file, start=1, has_header=True): arr = [] with open(csv_file, 'rU') as f: reader = csv.reader(f) arr = list(reader) if arr == []: return header = "" if has_header: header = ','.join(arr[0]) arr = arr[start:] return header, arr else: return arr[start:...
new_header, new_arr = csv_to_arr("HORIZON_cash_execs_20170427.csv") old_header, old_arr = csv_to_arr("HORIZON_cash_execs_20170427_old.csv") conn, cur = db_cur() create_tbl(cur, "new", new_header, new_arr) create_tbl(cur, "old", old_header, old_arr) # print new_header cur.execute("""select new.TRADEID,new.PORTFOLIO...
question_marks = '?' for i in range(0, len(st.split(','))-1): question_marks = question_marks + ",?" return question_marks
identifier_body
frame.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 euclid::size::TypedSize2D; use msg::constellation_msg::{FrameId, PipelineId}; use pipeline::Pipeline; use scri...
None => { warn!("Frame {:?} iterated after closure.", frame_id); continue; }, }; let pipeline = match self.pipelines.get(&frame.pipeline_id) { Some(pipeline) => pipeline, None => { ...
random_line_split
frame.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 euclid::size::TypedSize2D; use msg::constellation_msg::{FrameId, PipelineId}; use pipeline::Pipeline; use scri...
{ /// The frame id. pub id: FrameId, /// The size of the frame. pub size: Option<TypedSize2D<f32, CSSPixel>>, /// The timestamp for the current session history entry. pub instant: Instant, /// The pipeline for the current session history entry. pub pipeline_id: PipelineId, /// T...
Frame
identifier_name
common.js
$(function() { // 共通の変数は`NS`名前空間をスコープにします。 var NS = NS || {}; // ブレイクポイントを定数で管理します。 NS.BREAK_POINT_SM = 400; NS.BREAK_POINT_MD = 768; NS.BREAK_POINT_LG = 1000; NS.BREAK_POINT_XL = 1200; // `NS.viewportWidth`に現在のviewportの横幅を格納する。 NS.viewportWidth = window.innerWidth; $(window).on('resize', debounce...
{ var $targetClass = $('.js-scroll-top'); var speed = 500; // アニメーションスピード(ms) var animation = 'linear'; // 'linear' or 'swing' $targetClass.on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: 0}, speed, animation); }); } navScrollTop(); });
navScrollTop()
identifier_name
common.js
$(function() { // 共通の変数は`NS`名前空間をスコープにします。 var NS = NS || {}; // ブレイクポイントを定数で管理します。 NS.BREAK_POINT_SM = 400; NS.BREAK_POINT_MD = 768; NS.BREAK_POINT_LG = 1000; NS.BREAK_POINT_XL = 1200; // `NS.viewportWidth`に現在のviewportの横幅を格納する。 NS.viewportWidth = window.innerWidth; $(window).on('resize', debounce...
identifier_body
common.js
$(function() { // 共通の変数は`NS`名前空間をスコープにします。 var NS = NS || {}; // ブレイクポイントを定数で管理します。 NS.BREAK_POINT_SM = 400; NS.BREAK_POINT_MD = 768; NS.BREAK_POINT_LG = 1000; NS.BREAK_POINT_XL = 1200; // `NS.viewportWidth`に現在のviewportの横幅を格納する。 NS.viewportWidth = window.innerWidth; $(window).on('resize', debounce...
html, body').animate({ scrollTop: 0}, speed, animation); }); } navScrollTop(); });
'; // 'linear' or 'swing' $targetClass.on('click', function(e) { e.preventDefault(); $('
conditional_block
common.js
$(function() { // 共通の変数は`NS`名前空間をスコープにします。 var NS = NS || {}; // ブレイクポイントを定数で管理します。 NS.BREAK_POINT_SM = 400; NS.BREAK_POINT_MD = 768; NS.BREAK_POINT_LG = 1000; NS.BREAK_POINT_XL = 1200; // `NS.viewportWidth`に現在のviewportの横幅を格納する。 NS.viewportWidth = window.innerWidth; $(window).on('resize', debounce...
function navScrollTop() { var $targetClass = $('.js-scroll-top'); var speed = 500; // アニメーションスピード(ms) var animation = 'linear'; // 'linear' or 'swing' $targetClass.on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: 0}, speed, animation); }); } navScr...
random_line_split
controllers.py
# -*- coding: utf-8 -*- # Copyright © 2011 Varyant, LLC import re from wsgiref.util import request_uri from wack.http.errors import HttpMethodNotAllowed, HttpNotFound from wack.http.request import Request from wack.http.response import Response class Controllers(object): """ WSGI application that maps URLs ...
def mount(self, regex_str, method_list, controller): """ Mount the controller function on the URL tree at the path specified by the regular expression. The controller will only be invoked for the given http methods. :param regex_str: regular expression of URL path :p...
return body raise HttpNotFound({'uri': request_uri(environ, 0)})
random_line_split
controllers.py
# -*- coding: utf-8 -*- # Copyright © 2011 Varyant, LLC import re from wsgiref.util import request_uri from wack.http.errors import HttpMethodNotAllowed, HttpNotFound from wack.http.request import Request from wack.http.response import Response class Controllers(object): """ WSGI application that maps URLs ...
self, environ, start_response): path_info = environ['PATH_INFO'] script_name = environ['SCRIPT_NAME'] request_method = environ['REQUEST_METHOD'] for regex, method_list, controller in self.mappings: match = regex.match(path_info) if not match: conti...
_call__(
identifier_name
controllers.py
# -*- coding: utf-8 -*- # Copyright © 2011 Varyant, LLC import re from wsgiref.util import request_uri from wack.http.errors import HttpMethodNotAllowed, HttpNotFound from wack.http.request import Request from wack.http.response import Response class Controllers(object): """ WSGI application that maps URLs ...
def __call__(self, environ, start_response): path_info = environ['PATH_INFO'] script_name = environ['SCRIPT_NAME'] request_method = environ['REQUEST_METHOD'] for regex, method_list, controller in self.mappings: match = regex.match(path_info) if not match: ...
elf.mappings = []
identifier_body
controllers.py
# -*- coding: utf-8 -*- # Copyright © 2011 Varyant, LLC import re from wsgiref.util import request_uri from wack.http.errors import HttpMethodNotAllowed, HttpNotFound from wack.http.request import Request from wack.http.response import Response class Controllers(object): """ WSGI application that maps URLs ...
if request_method not in method_list: raise HttpMethodNotAllowed({'uri': request_uri(environ, 0), 'method': request_method}) environ['PATH_INFO'] = '' environ['SCRIPT_NAME'] = script_name + path_info request = Re...
ontinue
conditional_block
URLParser.ts
/* * Copyright 2018 Google 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in w...
(routeProps: RouteComponentProps) { this._routeProps = routeProps; this._paramMap = new URLSearchParams(routeProps.location.search); } public get(key: QUERY_PARAMS): string | null { return this._paramMap.get(key); } public set(key: QUERY_PARAMS, value: string): void { if (value) { this._...
constructor
identifier_name
URLParser.ts
/* * Copyright 2018 Google 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in w...
public set(key: QUERY_PARAMS, value: string): void { if (value) { this._paramMap.set(key, value); } else { this._paramMap.delete(key); } this._update(); } public push(key: QUERY_PARAMS, value: string): void { if (value) { this._paramMap.set(key, value); } else { ...
{ return this._paramMap.get(key); }
identifier_body
URLParser.ts
/* * Copyright 2018 Google 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in w...
} }
{ this._routeProps.history.push({ search: this._paramMap.toString() }); }
conditional_block