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
android-platform-livesync-service.ts
import {PlatformLiveSyncServiceBase} from "./platform-livesync-service-base"; class AndroidPlatformLiveSyncService extends PlatformLiveSyncServiceBase { constructor(_liveSyncData: ILiveSyncData, protected $devicesService: Mobile.IDevicesService, protected $mobileHelper: Mobile.IMobileHelper, protected $logger: ...
if (postAction) { this.finishLivesync(deviceAppData).wait(); return postAction(deviceAppData, localToDevicePaths).wait(); } afterSyncAction().wait(); this.finishLivesync(deviceAppData).wait(); }).future<void>()(); }; this.$devicesService.execute(action, canExecute).wait(); ...
{ this.transferFiles(deviceAppData, localToDevicePaths, this.liveSyncData.projectFilesPath, true).wait(); afterSyncAction = () => this.refreshApplication(deviceAppData, localToDevicePaths); }
conditional_block
android-platform-livesync-service.ts
import {PlatformLiveSyncServiceBase} from "./platform-livesync-service-base"; class AndroidPlatformLiveSyncService extends PlatformLiveSyncServiceBase { constructor(_liveSyncData: ILiveSyncData, protected $devicesService: Mobile.IDevicesService, protected $mobileHelper: Mobile.IMobileHelper, protected $logger: ...
} else { this.transferFiles(deviceAppData, localToDevicePaths, this.liveSyncData.projectFilesPath, true).wait(); afterSyncAction = () => this.refreshApplication(deviceAppData, localToDevicePaths); } if (postAction) { this.finishLivesync(deviceAppData).wait(); return postAction(de...
let afterSyncAction: () => IFuture<void>; if (installed) { deviceLiveSyncService.afterInstallApplicationAction(deviceAppData, localToDevicePaths).wait(); afterSyncAction = () => device.applicationManager.tryStartApplication(deviceAppData.appIdentifier);
random_line_split
android-platform-livesync-service.ts
import {PlatformLiveSyncServiceBase} from "./platform-livesync-service-base"; class
extends PlatformLiveSyncServiceBase { constructor(_liveSyncData: ILiveSyncData, protected $devicesService: Mobile.IDevicesService, protected $mobileHelper: Mobile.IMobileHelper, protected $logger: ILogger, protected $options: IOptions, protected $deviceAppDataFactory: Mobile.IDeviceAppDataFactory, protect...
AndroidPlatformLiveSyncService
identifier_name
android-platform-livesync-service.ts
import {PlatformLiveSyncServiceBase} from "./platform-livesync-service-base"; class AndroidPlatformLiveSyncService extends PlatformLiveSyncServiceBase { constructor(_liveSyncData: ILiveSyncData, protected $devicesService: Mobile.IDevicesService, protected $mobileHelper: Mobile.IMobileHelper, protected $logger: ...
} else { this.transferFiles(deviceAppData, localToDevicePaths, this.liveSyncData.projectFilesPath, true).wait(); afterSyncAction = () => this.refreshApplication(deviceAppData, localToDevicePaths); } if (postAction) { this.finishLivesync(deviceAppData).wait(); return postAction(de...
{ return (() => { let appIdentifier = this.liveSyncData.appIdentifier; let platform = this.liveSyncData.platform; let projectFilesPath = this.liveSyncData.projectFilesPath; let canExecute = this.getCanExecuteAction(platform, appIdentifier); let action = (device: Mobile.IDevice): IFuture<void> => { ...
identifier_body
Dataset.py
import math import random import onmt from torch.autograd import Variable class Dataset(object): def __init__(self, srcData, tgtData, batchSize, cuda, volatile=False): self.src = srcData if tgtData: self.tgt = tgtData assert(len(self.src) == len(self.tgt)) else: ...
else: tgtBatch = None return srcBatch, tgtBatch def __len__(self): return self.numBatches def shuffle(self): zipped = list(zip(self.src, self.tgt)) random.shuffle(zipped) self.src, self.tgt = [x[0] for x in zipped], [x[1] for x in zipped]
tgtBatch = self._batchify( self.tgt[index*self.batchSize:(index+1)*self.batchSize])
conditional_block
Dataset.py
import math import random import onmt from torch.autograd import Variable class Dataset(object): def __init__(self, srcData, tgtData, batchSize, cuda, volatile=False): self.src = srcData if tgtData: self.tgt = tgtData assert(len(self.src) == len(self.tgt)) else: ...
(self, index): assert index < self.numBatches, "%d > %d" % (index, self.numBatches) srcBatch = self._batchify( self.src[index*self.batchSize:(index+1)*self.batchSize], align_right=True) if self.tgt: tgtBatch = self._batchify( self.tgt[index*self.batchSize...
__getitem__
identifier_name
Dataset.py
import math import random import onmt from torch.autograd import Variable class Dataset(object): def __init__(self, srcData, tgtData, batchSize, cuda, volatile=False): self.src = srcData if tgtData: self.tgt = tgtData assert(len(self.src) == len(self.tgt)) else: ...
self.src[index*self.batchSize:(index+1)*self.batchSize], align_right=True) if self.tgt: tgtBatch = self._batchify( self.tgt[index*self.batchSize:(index+1)*self.batchSize]) else: tgtBatch = None return srcBatch, tgtBatch def __len__(self)...
def __getitem__(self, index): assert index < self.numBatches, "%d > %d" % (index, self.numBatches) srcBatch = self._batchify(
random_line_split
Dataset.py
import math import random import onmt from torch.autograd import Variable class Dataset(object): def __init__(self, srcData, tgtData, batchSize, cuda, volatile=False):
def _batchify(self, data, align_right=False): max_length = max(x.size(0) for x in data) out = data[0].new(len(data), max_length).fill_(onmt.Constants.PAD) for i in range(len(data)): data_length = data[i].size(0) offset = max_length - data_length if align_right else ...
self.src = srcData if tgtData: self.tgt = tgtData assert(len(self.src) == len(self.tgt)) else: self.tgt = None self.cuda = cuda self.batchSize = batchSize self.numBatches = math.ceil(len(self.src)/batchSize) self.volatile = volatile
identifier_body
assignment-visitor.js
'use strict'; var _require = require('./parseProps'), parsePropTypes = _require.parsePropTypes, parseDefaultProps = _require.parseDefaultProps, resolveToValue = require('./util/resolveToValue'); module.exports = function (state) { var json = state.result, components = state.seen; var isAssignin...
} }; };
}
random_line_split
naoqi_microphone.py
#!/usr/bin/env python # Copyright (C) 2014 Aldebaran Robotics # # 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 applic...
(self): r=rospy.Rate(2) while self.is_looping(): if self.pub_audio_.get_num_connections() == 0: if self.isSubscribed: rospy.loginfo('Unsubscribing from audio bridge as nobody listens to the topics.') self.release() conti...
run
identifier_name
naoqi_microphone.py
#!/usr/bin/env python # Copyright (C) 2014 Aldebaran Robotics # # 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 applic...
rospy.logwarn(str(e)) rospy.logwarn("Microphone channel map might not be accurate.") def returnNone(): return None self.config = defaultdict(returnNone) rospy.loginfo('channel = %s'%self.config['channel']) # ROS publishers self.pub_audio_ = ro...
def __init__(self, name): NaoqiNode.__init__(self, name) self.myBroker = ALBroker("pythonBroker", "0.0.0.0", 0, self.pip, self.pport) ALModule.__init__(self, name) self.isSubscribed = False self.microVersion = 0 # Create a proxy to ALAudioDevice try: ...
identifier_body
naoqi_microphone.py
#!/usr/bin/env python # Copyright (C) 2014 Aldebaran Robotics # # 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 applic...
else: channels = [self.config['channel']] audio_msg.channelMap = channels audio_msg.data = mictmp self.pub_audio_.publish(audio_msg)
channels = [3,5,0,2]
conditional_block
naoqi_microphone.py
#!/usr/bin/env python # Copyright (C) 2014 Aldebaran Robotics # # 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 applic...
audio_msg = AudioBuffer() # Deal with the sound # get data directly with the _getInputBuffer() function because inputBuff is corrupted in python mictmp = [] for i in range (0,len(inputBuff)/2) : mictmp.append(ord(inputBuff[2*i])+ord(inputBuff[2*i+1])*256) # ...
def processRemote(self, nbOfInputChannels, fNbOfInputSamples, timeStamp, inputBuff):
random_line_split
jquery.jvectormap.init.js
/** * Theme: Simple Admin Template * Author: Coderthemes * VectorMap */ ! function($) { "use strict"; var VectorMap = function() { }; VectorMap.prototype.init = function() { //various examples $('#world-map-markers').vectorMap({ map : 'world_mill_en', scaleColors : ['#4bd396', '#4bd396'], normal...
}, { latLng : [-8.51, 179.21], name : 'Tuvalu' }, { latLng : [43.93, 12.46], name : 'San Marino' }, { latLng : [47.14, 9.52], name : 'Liechtenstein' }, { latLng : [7.11, 171.06], name : 'Marshall Islands' }, { latLng : [17.3, -62.73], name : 'Saint Kitts and Nevis'...
}, { latLng : [-0.52, 166.93], name : 'Nauru'
random_line_split
capability.js
'use strict'; var CAPABILITY_RESPONSE = 0x6C; module.exports = function () { return { cmd: CAPABILITY_RESPONSE, handle: function (cmd, data, board) { var supportedModes = 0; function
(modesArray, mode) { if (supportedModes & (1 << board.MODES[mode])) { modesArray.push(board.MODES[mode]); } } // Only create pins if none have been previously created on the instance. if (!board.pins.length) { for (var i = 0, n = 0; i < data.length; i++) { ...
pushModes
identifier_name
capability.js
'use strict'; var CAPABILITY_RESPONSE = 0x6C; module.exports = function () { return { cmd: CAPABILITY_RESPONSE, handle: function (cmd, data, board) { var supportedModes = 0; function pushModes(modesArray, mode) { if (supportedModes & (1 << board.MODES[mode])) { modesArray.pu...
n ^= 1; } } board.emit("capability-query"); } } };
{ supportedModes |= (1 << data[i]); }
conditional_block
capability.js
'use strict';
module.exports = function () { return { cmd: CAPABILITY_RESPONSE, handle: function (cmd, data, board) { var supportedModes = 0; function pushModes(modesArray, mode) { if (supportedModes & (1 << board.MODES[mode])) { modesArray.push(board.MODES[mode]); } } ...
var CAPABILITY_RESPONSE = 0x6C;
random_line_split
capability.js
'use strict'; var CAPABILITY_RESPONSE = 0x6C; module.exports = function () { return { cmd: CAPABILITY_RESPONSE, handle: function (cmd, data, board) { var supportedModes = 0; function pushModes(modesArray, mode)
// Only create pins if none have been previously created on the instance. if (!board.pins.length) { for (var i = 0, n = 0; i < data.length; i++) { if (data[i] === 127) { var modesArray = []; Object.keys(board.MODES).forEach(pushModes.bind(null, modesArray)); ...
{ if (supportedModes & (1 << board.MODES[mode])) { modesArray.push(board.MODES[mode]); } }
identifier_body
test_del_disk.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
command = "show machine --machine ut3c1n3" out = self.commandtest(command.split(" ")) self.matchclean(out, "Disk: c0d0", command) # This should now list the 34 GB disk that was added previously... def testverifycatut3c1n3disk(self): command = "cat --machine ut3c1n3" out ...
def testverifydelut3c1n3sdb(self):
random_line_split
test_del_disk.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
(self): self.noouttest(["del", "disk", "--machine", "ut3c1n3", "--controller", "scsi", "--size", "68"]) def testdelut3c1n3sdb(self): self.noouttest(["del", "disk", "--machine", "ut3c1n3", "--disk", "c0d0"]) def testverifydelut3c1n3sda(self): command = "show mach...
testdelut3c1n3sda
identifier_name
test_del_disk.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
from brokertest import TestBrokerCommand class TestDelDisk(TestBrokerCommand): def testdelut3c1n3sda(self): self.noouttest(["del", "disk", "--machine", "ut3c1n3", "--controller", "scsi", "--size", "68"]) def testdelut3c1n3sdb(self): self.noouttest(["del", "disk", "--machine", "...
import utils utils.import_depends()
conditional_block
test_del_disk.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
command = "cat --machine ut3c1n3" out = self.commandtest(command.split(" ")) self.matchclean(out, "harddisks", command) def testfaildelunknowntype(self): command = ["del", "disk", "--machine", "ut3c1n3", "--type", "type-does-not-exist"] out = self.badreque...
def testdelut3c1n3sda(self): self.noouttest(["del", "disk", "--machine", "ut3c1n3", "--controller", "scsi", "--size", "68"]) def testdelut3c1n3sdb(self): self.noouttest(["del", "disk", "--machine", "ut3c1n3", "--disk", "c0d0"]) def testverifydelut3c1n3sda(self): ...
identifier_body
app.js
(function () { 'use strict'; var dccModul = angular.module('workinghours', ['dcc.controller', 'dcc.factories', 'dcc.filter', 'ngCookies', 'ngRoute']); dccModul.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) { $routeProvider.when('/duration/new', { ...
templateUrl: '/partials/durationNew.html', controller: 'DurationController' }); $routeProvider.when('/login', {templateUrl: '/partials/login.html', controller: 'LoginController'}); $routeProvider.when('/adminoverview', { templateUrl: '/partials/adminoverview.h...
random_line_split
vec.rs
use std::vec::IntoIter; use std::marker::PhantomData; use super::{Set, SetManager}; use super::sort::SortManager; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Error { IndexOutOfRange { index: usize, total: usize }, } pub struct VecSetIter<T, E> { iter: Option<IntoIter<T>>, _marker: PhantomData<E>...
} #[cfg(test)] mod tests { use super::{Error, Manager}; use super::super::{Set, SetManager}; fn run_basic<S>(mut set: S) where S: Set<T = u8, E = Error> { assert_eq!(set.size(), 0); assert_eq!(set.add(0), Ok(())); assert_eq!(set.size(), 1); assert_eq!(set.add(1), Ok(())); ...
random_line_split
vec.rs
use std::vec::IntoIter; use std::marker::PhantomData; use super::{Set, SetManager}; use super::sort::SortManager; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Error { IndexOutOfRange { index: usize, total: usize }, } pub struct VecSetIter<T, E> { iter: Option<IntoIter<T>>, _marker: PhantomData<E>...
<T> { _marker: PhantomData<T>, } impl<T> Manager<T> { pub fn new() -> Manager<T> { Manager { _marker: PhantomData, } } } impl<T> SetManager for Manager<T> { type S = Vec<T>; type E = (); fn make_set(&mut self, size_hint: Option<usize>) -> Result<Self::S, Self::E> {...
Manager
identifier_name
vec.rs
use std::vec::IntoIter; use std::marker::PhantomData; use super::{Set, SetManager}; use super::sort::SortManager; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Error { IndexOutOfRange { index: usize, total: usize }, } pub struct VecSetIter<T, E> { iter: Option<IntoIter<T>>, _marker: PhantomData<E>...
else { Ordering::Greater }); Ok(()) } } #[cfg(test)] mod tests { use super::{Error, Manager}; use super::super::{Set, SetManager}; fn run_basic<S>(mut set: S) where S: Set<T = u8, E = Error> { assert_eq!(set.size(), 0); assert_eq!(set.add(0), Ok(())); ...
{ Ordering::Less }
conditional_block
pinsrb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pinsrb_1() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EB...
() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: N...
pinsrb_4
identifier_name
pinsrb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pinsrb_1() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EB...
}
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }...
random_line_split
pinsrb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pinsrb_1() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EB...
fn pinsrb_4() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None,...
{ run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(Direct(EDI)), operand3: Some(Literal8(12)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 239, 12], OperandSize::Qword) }
identifier_body
aiplatform_v1_generated_job_service_delete_model_deployment_monitoring_job_async.py
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): # Create a client client = aiplatform_v1.JobServiceAsyncClient() # Initialize request argument(s) request = aiplatform_v1.DeleteModelDeploymentMonitoringJobRequest( name="name_value", ) # Make the request operation = client.delete_model_deployment_monitoring_job(request=request...
sample_delete_model_deployment_monitoring_job
identifier_name
aiplatform_v1_generated_job_service_delete_model_deployment_monitoring_job_async.py
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END aiplatform_v1_generated_JobService_DeleteModelDeploymentMonitoringJob_async]
client = aiplatform_v1.JobServiceAsyncClient() # Initialize request argument(s) request = aiplatform_v1.DeleteModelDeploymentMonitoringJobRequest( name="name_value", ) # Make the request operation = client.delete_model_deployment_monitoring_job(request=request) print("Waiting for oper...
identifier_body
aiplatform_v1_generated_job_service_delete_model_deployment_monitoring_job_async.py
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Initialize request argument(s) request = aiplatform_v1.DeleteModelDeploymentMonitoringJobRequest( name="name_value", ) # Make the request operation = client.delete_model_deployment_monitoring_job(request=request) print("Waiting for operation to complete...") response = await ope...
async def sample_delete_model_deployment_monitoring_job(): # Create a client client = aiplatform_v1.JobServiceAsyncClient()
random_line_split
racetrackview.py
import kivy kivy.require('1.9.1') from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.scatter import Scatter from kivy.app import Builder from kivy.metrics import dp from kivy.graphics import Color, Line from autosportlabs.racecapture.geo.geopoint i...
def add_map_path(self, key, path, color): self.ids.trackmap.add_path(key, path, color) def remove_map_path(self, key): self.ids.trackmap.remove_path(key) def add_heat_values(self, key, heat_values): self.ids.trackmap.add_heat_values(key, heat_values) def remove_heat_values(se...
self.ids.trackmap.update_marker(key, geo_point)
random_line_split
racetrackview.py
import kivy kivy.require('1.9.1') from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.scatter import Scatter from kivy.app import Builder from kivy.metrics import dp from kivy.graphics import Color, Line from autosportlabs.racecapture.geo.geopoint i...
def update_reference_mark(self, key, geo_point): self.ids.trackmap.update_marker(key, geo_point) def add_map_path(self, key, path, color): self.ids.trackmap.add_path(key, path, color) def remove_map_path(self, key): self.ids.trackmap.remove_path(key) def add_heat_values(self...
trackmap.add_marker(key, color)
conditional_block
racetrackview.py
import kivy kivy.require('1.9.1') from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.scatter import Scatter from kivy.app import Builder from kivy.metrics import dp from kivy.graphics import Color, Line from autosportlabs.racecapture.geo.geopoint i...
(self, track): self.ids.trackmap.setTrackPoints(track.map_points) def remove_reference_mark(self, key): self.ids.trackmap.remove_marker(key) def add_reference_mark(self, key, color): trackmap = self.ids.trackmap if trackmap.get_marker(key) is None: trackmap.add_mark...
initMap
identifier_name
racetrackview.py
import kivy kivy.require('1.9.1') from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.scatter import Scatter from kivy.app import Builder from kivy.metrics import dp from kivy.graphics import Color, Line from autosportlabs.racecapture.geo.geopoint i...
def remove_heat_values(self, key): self.ids.trackmap.remove_heat_values(key)
self.ids.trackmap.add_heat_values(key, heat_values)
identifier_body
stream_server.js
Meteor._StreamServer = function () { var self = this; self.registration_callbacks = []; self.open_sockets = []; // unique id for this instantiation of the server. If this changes // between client reconnects, the client will reload. In production, // we might want to make this the bundle id, so that if run...
self.server.on('connection', function (socket) { socket.send = function (data) { socket.write(data); }; socket.on('close', function () { self.open_sockets = _.without(self.open_sockets, socket); }); self.open_sockets.push(socket); // Send a welcome message with the server_id. Cli...
random_line_split
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use clidispatch::io::IO; use cpython::*; use cpython_ext::wrap_pyio; pub fn init_module(py: Python, package...
( _py: Python, args: Vec<String>, fin: PyObject, fout: PyObject, ferr: Option<PyObject>, ) -> PyResult<i32> { let fin = wrap_pyio(fin); let fout = wrap_pyio(fout); let ferr = ferr.map(wrap_pyio); let mut io = IO::new(fin, fout, ferr); Ok(hgcommands::run_command(args, &mut io)) }...
run_py
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use clidispatch::io::IO; use cpython::*; use cpython_ext::wrap_pyio; pub fn init_module(py: Python, package...
{ let fin = wrap_pyio(fin); let fout = wrap_pyio(fout); let ferr = ferr.map(wrap_pyio); let mut io = IO::new(fin, fout, ferr); Ok(hgcommands::run_command(args, &mut io)) }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)]
let name = [package, "commands"].join("."); let m = PyModule::new(py, &name)?; m.add( py, "run", py_fn!( py, run_py( args: Vec<String>, fin: PyObject, fout: PyObject, ferr: Option<PyObject> = None...
use clidispatch::io::IO; use cpython::*; use cpython_ext::wrap_pyio; pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
random_line_split
server.js
let express = require('express'); let config = require('./config/main'); let path = require('path'); // providing route prefixing for express Router express.application.prefix = express.Router.prefix = function (path, configure) { let router = express.Router(); this.use(path, router); configure(router); ...
case "PROD": mongodbURL = config.db.connection; console.log("environment = " + mongodbURL); break; default: console.log("env_value is not correct: " + env_value); return -1; } // Set the public folder app.set('public', path.join(__dirname, 'public')); app.set("config",...
case "DEV": mongodbURL = config.localDB.connection; console.log("environment = " + mongodbURL); break;
random_line_split
server.js
let express = require('express'); let config = require('./config/main'); let path = require('path'); // providing route prefixing for express Router express.application.prefix = express.Router.prefix = function (path, configure) { let router = express.Router(); this.use(path, router); configure(router); ...
// Default env value is DEV if (typeof env_value === "undefined") { console.log("env_value is not set , Default env is DEV"); env_value = "DEV"; } switch (env_value) { case "DEV": mongodbURL = config.localDB.connection; console.log("environment = " + mongodbURL); break; case ...
{ console.log("port string: " + port_string); config.port_number = port_string; }
conditional_block
syslog_broker.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redis...
(self, modconf): BaseModule.__init__(self, modconf) # A service check have just arrived, we UPDATE data info with this def manage_log_brok(self, b): data = b.data syslog.syslog(data['log'].encode('UTF-8'))
__init__
identifier_name
syslog_broker.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redis...
# A service check have just arrived, we UPDATE data info with this def manage_log_brok(self, b): data = b.data syslog.syslog(data['log'].encode('UTF-8'))
BaseModule.__init__(self, modconf)
identifier_body
syslog_broker.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redis...
#path = plugin.path instance = Syslog_broker(plugin) return instance # Class for the Merlindb Broker # Get broks and puts them in merlin database class Syslog_broker(BaseModule): def __init__(self, modconf): BaseModule.__init__(self, modconf) # A service check have just arrived, we UPDATE...
#Catch errors
random_line_split
second.js
var Ringpop = require('ringpop'); var TChannel = require('TChannel'); var express = require('express'); var NodeCache = require('node-cache'); var cache = new NodeCache(); var host = '127.0.0.1'; // not recommended for production var httpPort = process.env.PORT || 8080; var port = httpPort - 5080; var bootstrapNodes =...
// This is how you wire up a handler for forwarded requests ringpop.on('request', handleReq); }); var server = express(); server.get('/*', onReq); server.listen(httpPort, function onListen() { console.log('Server is listening on ' + httpPort); }); function extractKey(req) { var urlParts = req.url.split(...
console.log('Ringpop ' + ringpop.whoami() + ' has bootstrapped!'); });
random_line_split
second.js
var Ringpop = require('ringpop'); var TChannel = require('TChannel'); var express = require('express'); var NodeCache = require('node-cache'); var cache = new NodeCache(); var host = '127.0.0.1'; // not recommended for production var httpPort = process.env.PORT || 8080; var port = httpPort - 5080; var bootstrapNodes =...
(req, res) { var key = extractKey(req); if (ringpop.handleOrProxy(key, req, res)) { handleReq(req, res); } } function handleReq(req, res) { cache.get(req.url, function(err, value) { if (value == undefined) { var key = extractKey(req); var result = host + ':' + port + ' is responsible for...
onReq
identifier_name
second.js
var Ringpop = require('ringpop'); var TChannel = require('TChannel'); var express = require('express'); var NodeCache = require('node-cache'); var cache = new NodeCache(); var host = '127.0.0.1'; // not recommended for production var httpPort = process.env.PORT || 8080; var port = httpPort - 5080; var bootstrapNodes =...
function onReq(req, res) { var key = extractKey(req); if (ringpop.handleOrProxy(key, req, res)) { handleReq(req, res); } } function handleReq(req, res) { cache.get(req.url, function(err, value) { if (value == undefined) { var key = extractKey(req); var result = host + ':' + port + ' is ...
{ var urlParts = req.url.split('/'); if (urlParts.length < 3) return ''; // URL does not have 2 parts... return urlParts[1]; }
identifier_body
second.js
var Ringpop = require('ringpop'); var TChannel = require('TChannel'); var express = require('express'); var NodeCache = require('node-cache'); var cache = new NodeCache(); var host = '127.0.0.1'; // not recommended for production var httpPort = process.env.PORT || 8080; var port = httpPort - 5080; var bootstrapNodes =...
} function handleReq(req, res) { cache.get(req.url, function(err, value) { if (value == undefined) { var key = extractKey(req); var result = host + ':' + port + ' is responsible for ' + key; cache.set(req.url, result, function(err, success) { if (!err && success) { res.end(result + ' NOT CACH...
{ handleReq(req, res); }
conditional_block
part.d.ts
/** * @license * Copyright (c) 2018 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors ma...
*/ export declare const nothing: {}; //# sourceMappingURL=part.d.ts.map
random_line_split
resultset.py
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
that it's quite fast and efficient but it makes some things rather difficult. You can pass in, as the marker_elem parameter, a list of tuples. Each tuple contains a string as the first element which represents the XML element that the resultset needs to be on the lookout for and a Python class...
I'm using the standard SAX parser that comes with Python. The good news is
random_line_split
resultset.py
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
(self, marker_elem=None): self.status = True self.request_id = None self.box_usage = None def __repr__(self): if self.status: return 'True' else: return 'False' def __nonzero__(self): return self.status def startElement(self, name, a...
__init__
identifier_name
resultset.py
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
def to_boolean(self, value, true_value='true'): if value == true_value: return True else: return False def endElement(self, name, value, connection): if name == 'IsTruncated': self.is_truncated = self.to_boolean(value) elif name == 'Marker':...
for t in self.markers: if name == t[0]: obj = t[1](connection) self.append(obj) return obj if name == 'Owner': # Makes owner available for get_service and # perhaps other lists where not handled by # another element....
identifier_body
resultset.py
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
elif name == 'StatusCode': self.status = self.to_boolean(value, 'Success') elif name == 'ItemName': self.append(value) elif name == 'NextToken': self.next_token = value elif name == 'nextToken': self.next_token = value # Code e...
self.status = self.to_boolean(value)
conditional_block
dom_html_paragraph_element.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; use glib::GString; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerI...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLParagraphElement") } }
fmt
identifier_name
dom_html_paragraph_element.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; use glib::GString; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerI...
fn set_align(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_paragraph_element_set_align(self.as_ref().to_glib_none().0, value.to_glib_none().0); } } fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { uns...
{ unsafe { from_glib_full(webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_align(self.as_ref().to_glib_none().0)) } }
identifier_body
dom_html_paragraph_element.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; use glib::GString; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerI...
unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) + 'static>(this: *mut webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer) where P: IsA<DOMHTMLParagraphElement> { let f: &F = &*(f as *const F); f(&D...
fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
random_line_split
test_support.py
enabled" % resource raise ResourceDenied(msg) def bind_port(sock, host='', preferred_port=54321): """Try to bind the sock to a port. If we are running multiple tests and we don't try multiple ports, the test can fails. This makes the test more robust.""" import socket, errno # Find som...
_Dummy
identifier_name
test_support.py
): if msg is None: msg = "Use of the `%s' resource not enabled" % resource raise ResourceDenied(msg) def bind_port(sock, host='', preferred_port=54321): """Try to bind the sock to a port. If we are running multiple tests and we don't try multiple ports, the test can fails. This ...
# message below is printed, the test that is listening on the port should # be fixed to close the socket at the end of the test. # Another reason why we can't use a port is another process (possibly # another instance of the test suite) is using the same port. for port in [preferred_port, 9907, 1024...
# Find some random ports that hopefully no one is listening on. # Ideally each test would clean up after itself and not continue listening # on any ports. However, this isn't the case. The last port (0) is # a stop-gap that asks the O/S to assign a port. Whenever the warning
random_line_split
test_support.py
WARNING: The filename %r CAN be encoded by the filesystem. ' \ 'Unicode filename tests may not be effective' \ % TESTFN_UNICODE_UNENCODEABLE # Make sure we can write to TESTFN, try in /tmp if we can't fp = None try: fp = open(TESTFN, 'w+') except IOError: TMP_TESTFN = os.path.j...
"""Run tests from unittest.TestCase-derived classes.""" suite = unittest.TestSuite() for cls in classes: if isinstance(cls, (unittest.TestSuite, unittest.TestCase)): suite.addTest(cls) else: suite.addTest(unittest.makeSuite(cls)) if len(classes)==1: testclass ...
identifier_body
test_support.py
TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1") TESTFN_ENCODING = sys.getfilesystemencoding() # TESTFN_UNICODE_UNENCODEABLE is a filename that should *not* be # able to be encoded by *either* the default or filesystem encoding. # This test really only makes sense on Win...
if verbose: sys.stderr.write("Skipping %s because of memory " "constraint\n" % (f.__name__,))
conditional_block
svp_cal.js
var scp; var cal_color; $(document).ready(function(){ scp = angular.element('.main').scope(); $("#div_point").toggle(); //Set default values cal_color = defaults.cal_color; //Setup plugins $("#cal_color").spectrum({ preferredFormat: "hex", showInput: true, color: cal_color, change: setColor...
function startCalibration(){ scp.makeRequest(); }
random_line_split
svp_cal.js
var scp; var cal_color; $(document).ready(function(){ scp = angular.element('.main').scope(); $("#div_point").toggle(); //Set default values cal_color = defaults.cal_color; //Setup plugins $("#cal_color").spectrum({ preferredFormat: "hex", showInput: true, color: cal_color, change: setColor...
(){ //Configuration modal close callback $(".main").css("cursor","none"); setup(); } function calibrationFinished(){ $(".main").css("cursor","pointer"); $("#text").html("Calibration completed"); $( "#div_point" ).fadeOut( "slow", function(){ $("#div_text" ).fadeIn( "slow", function() { setTimeout(function(...
closeCallback
identifier_name
svp_cal.js
var scp; var cal_color; $(document).ready(function(){ scp = angular.element('.main').scope(); $("#div_point").toggle(); //Set default values cal_color = defaults.cal_color; //Setup plugins $("#cal_color").spectrum({ preferredFormat: "hex", showInput: true, color: cal_color, change: setColor...
function calibrationFinished(){ $(".main").css("cursor","pointer"); $("#text").html("Calibration completed"); $( "#div_point" ).fadeOut( "slow", function(){ $("#div_text" ).fadeIn( "slow", function() { setTimeout(function() { window.history.back(); }, 2500); }); }); } function startCalibrat...
{ //Configuration modal close callback $(".main").css("cursor","none"); setup(); }
identifier_body
startpage.js
import React from 'react'; import {Link} from 'react-router'; import {getRandomScrap} from '../server'; import {hashHistory} from 'react-router'; export default class
extends React.Component { handleFindScrapToFinish(e){ e.stopPropagation(); getRandomScrap((scrapData)=>{ hashHistory.push("scraps/" + scrapData._id + "/finish-scrap"); }); } render(){ var start = this; return ( <div className="container text-center"> <Link to="/scraps-cr...
StartPage
identifier_name
startpage.js
import React from 'react'; import {Link} from 'react-router'; import {getRandomScrap} from '../server'; import {hashHistory} from 'react-router'; export default class StartPage extends React.Component { handleFindScrapToFinish(e){ e.stopPropagation(); getRandomScrap((scrapData)=>{ hashHistory.push("sc...
}
{ var start = this; return ( <div className="container text-center"> <Link to="/scraps-create" className="btn btn-default btn-block startpage-btn"> <h1 className="cover-heading">Make a Scrap</h1> <br />Start half an idea for someone to finish. </Link> <br/> ...
identifier_body
startpage.js
import React from 'react'; import {Link} from 'react-router'; import {getRandomScrap} from '../server';
import {hashHistory} from 'react-router'; export default class StartPage extends React.Component { handleFindScrapToFinish(e){ e.stopPropagation(); getRandomScrap((scrapData)=>{ hashHistory.push("scraps/" + scrapData._id + "/finish-scrap"); }); } render(){ var start = this; return ( ...
random_line_split
playlist.component.ts
/* * Angular 2 decorators and services */ import { Component, Input, Output, EventEmitter } from '@angular/core'; import { CardComponent } from './../common/card/card.component'; import {DynamicOutlet} from './../dynamicOutlet/dynamicOutlet.component'; import { EditVariationFormComponent } from './../editVariationFo...
font-weight: 300; margin: 0 0 0.5em 0; } `], template: `<div class="wrapper"> <h2 class="title">{{variationData.name}}</h2> <div class="playground-card"> <cb-edit-button [size]="24" (click)="toggleModal()"></cb-edit-button> <cb-delete-button [size]="24" (click)="deleteV...
} .title { font-size: 1.5em;
random_line_split
playlist.component.ts
/* * Angular 2 decorators and services */ import { Component, Input, Output, EventEmitter } from '@angular/core'; import { CardComponent } from './../common/card/card.component'; import {DynamicOutlet} from './../dynamicOutlet/dynamicOutlet.component'; import { EditVariationFormComponent } from './../editVariationFo...
{ @Input() basePath: string; @Input() bundle: string; @Input() component: any; @Input() componentPath: string; @Input() variationData: any; @Input() inputsCustomMeta: any; @Output() onChanged = new EventEmitter(); @Output() onDeleted = new EventEmitter(); showModal: boolean = false...
Playlist
identifier_name
playlist.component.ts
/* * Angular 2 decorators and services */ import { Component, Input, Output, EventEmitter } from '@angular/core'; import { CardComponent } from './../common/card/card.component'; import {DynamicOutlet} from './../dynamicOutlet/dynamicOutlet.component'; import { EditVariationFormComponent } from './../editVariationFo...
persistVariation(variationData) { this.onChanged.emit({ name: this.variationData.name, data: variationData }); } deleteVariation() { this.onDeleted.emit(this.variationData); } }
{ this.showModal = !this.showModal; }
identifier_body
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
} } /// Asks the user to select a file from the filesystem, starting at directory `path`. /// /// Requires a function that produces the command as `cmd`, because commands aren't cloneable. pub fn pick_file<C>(cmd: C, path: PathBuf) -> io::Result<PathBuf> where C: Fn() -> Option<Command> { let mut curpath = pa...
random_line_split
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
else { return Ok(newpath); } } } } /// Returns the user's preferred menu program from the `MENU` environment variable if it exists. /// /// Use `.as_mut()` on the returned value to turn in into an `Option<&mut Command>`. pub fn default_menu_cmd() -> Option<Command> { env::...
{ curpath = newpath; }
conditional_block
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
{ env::var_os("MENU").map(|s| Command::new(s)) }
identifier_body
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
<T: AsRef<str>>(items: &[T], prompt: &str) -> io::Result<String> { let mut tty = try!(OpenOptions::new().read(true).write(true).open("/dev/tty")); let pad_len = ((items.len() as f32).log10().floor() + 1.0) as usize; for (i, item) in items.iter().enumerate() { try!(tty.write_all(format!("{1:0$}. {2}\...
pick_from_list_internal
identifier_name
set_mongo_profiling.py
#!/usr/bin/python import pymongo import string import sys from argparse import ArgumentParser def get_args(): parser = ArgumentParser(description='Run health checks of mongo and mtools systems') parser.add_argument('-a', '--action', dest='action', required=True, help='action to take...
'default local,test', metavar='EXCLUDE_LIST', default='local,test') args = parser.parse_args() if args.action not in ['enable', 'disable']: print("Unknown action %s" % args.action) sys.exit(1) return args if __name__ == '__main__': ...
help='comma separated list of databases to exclude - '
random_line_split
set_mongo_profiling.py
#!/usr/bin/python import pymongo import string import sys from argparse import ArgumentParser def get_args():
if args.action not in ['enable', 'disable']: print("Unknown action %s" % args.action) sys.exit(1) return args if __name__ == '__main__': args = get_args() try: client = pymongo.MongoClient(args.hostname, args.port) db_names = client.database_names() ...
parser = ArgumentParser(description='Run health checks of mongo and mtools systems') parser.add_argument('-a', '--action', dest='action', required=True, help='action to take (enable|disable)', metavar='(enable|disable)') parser.add_argument('-n', '--hostname', de...
identifier_body
set_mongo_profiling.py
#!/usr/bin/python import pymongo import string import sys from argparse import ArgumentParser def get_args(): parser = ArgumentParser(description='Run health checks of mongo and mtools systems') parser.add_argument('-a', '--action', dest='action', required=True, help='action to take...
client.close() except pymongo.errors.PyMongoError as e: print(e) sys.exit(1)
db.drop_collection('system.profile')
conditional_block
set_mongo_profiling.py
#!/usr/bin/python import pymongo import string import sys from argparse import ArgumentParser def
(): parser = ArgumentParser(description='Run health checks of mongo and mtools systems') parser.add_argument('-a', '--action', dest='action', required=True, help='action to take (enable|disable)', metavar='(enable|disable)') parser.add_argument('-n', '--hostn...
get_args
identifier_name
test_tasks.py
from ddt import ddt, data from django.test import TestCase from six.moves import mock from waldur_core.core import utils from waldur_core.structure import tasks from waldur_core.structure.tests import factories, models class TestDetectVMCoordinatesTask(TestCase): @mock.patch('requests.get') def test_task_se...
@ddt class ThrottleProvisionTaskTest(TestCase): @data( dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT + 1, retried=True), dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT - 1, retried=False), ) def test_if_limit_is_reached_provisioning_is_delayed(self, params): link = fac...
instance = factories.TestNewInstanceFactory() mock_request_get.return_value.ok = False tasks.detect_vm_coordinates(utils.serialize_instance(instance)) instance.refresh_from_db() self.assertIsNone(instance.latitude) self.assertIsNone(instance.longitude)
identifier_body
test_tasks.py
from ddt import ddt, data from django.test import TestCase from six.moves import mock from waldur_core.core import utils from waldur_core.structure import tasks from waldur_core.structure.tests import factories, models class TestDetectVMCoordinatesTask(TestCase): @mock.patch('requests.get')
ip_address = "127.0.0.1" expected_latitude = 20 expected_longitude = 20 instance = factories.TestNewInstanceFactory() mock_request_get.return_value.ok = True response = {"ip": ip_address, "latitude": expected_latitude, "longitude": expected_longitude} mock_reques...
def test_task_sets_coordinates(self, mock_request_get):
random_line_split
test_tasks.py
from ddt import ddt, data from django.test import TestCase from six.moves import mock from waldur_core.core import utils from waldur_core.structure import tasks from waldur_core.structure.tests import factories, models class
(TestCase): @mock.patch('requests.get') def test_task_sets_coordinates(self, mock_request_get): ip_address = "127.0.0.1" expected_latitude = 20 expected_longitude = 20 instance = factories.TestNewInstanceFactory() mock_request_get.return_value.ok = True response...
TestDetectVMCoordinatesTask
identifier_name
whitespace.rs
use nom::multispace; named!(comment<&str, &str>, delimited!( tag!("/*"), take_until!("*/"), tag!("*/") )); named!(space_or_comment<&str, &str>, alt!( multispace | comment )); named!(pub space<&str, ()>, fold_many1!( space_or_comment, (), |_, _| () )); named!(pub opt_space<&str, ()>, fold...
#[test] fn test_opt_space() { named!(test_parser<&str, &str>, do_parse!( tag!("(") >> opt_space >> res: take_while!(is_good) >> opt_space >> tag!(")") >> (res) ))...
{ named!(test_parser<&str, Vec<&str>>, wsc!(many0!( take_while!(is_good) ))); let input = "a /* b */ c / * d /**/ e "; assert_done!(test_parser(input), vec!["a", "c", "/", "*", "d", "e"]); }
identifier_body
whitespace.rs
use nom::multispace; named!(comment<&str, &str>, delimited!( tag!("/*"), take_until!("*/"), tag!("*/") )); named!(space_or_comment<&str, &str>, alt!( multispace | comment )); named!(pub space<&str, ()>, fold_many1!( space_or_comment, (), |_, _| () )); named!(pub opt_space<&str, ()>, fold...
() { named!(test_parser<&str, &str>, do_parse!( tag!("(") >> opt_space >> res: take_while!(is_good) >> opt_space >> tag!(")") >> (res) )); let input1 = "( a )"; ...
test_opt_space
identifier_name
whitespace.rs
use nom::multispace; named!(comment<&str, &str>, delimited!( tag!("/*"), take_until!("*/"), tag!("*/") )); named!(space_or_comment<&str, &str>, alt!( multispace | comment
named!(pub space<&str, ()>, fold_many1!( space_or_comment, (), |_, _| () )); named!(pub opt_space<&str, ()>, fold_many0!( space_or_comment, (), |_, _| () )); /// Transforms a parser to automatically consume whitespace and comments /// between each token. macro_rules! wsc( ($i:expr, $($arg...
));
random_line_split
ReactViewInitializer.tsx
import * as React from 'react' import { render } from 'react-dom' import { compose, createStore, applyMiddleware } from 'redux' import { Provider,ElementClass } from 'react-redux' import App from '../containers/TodoApp' import { devTools, persistState } from 'redux-devtools'; import { DebugPanel, DevTools, LogMonitor }...
<P>(reducer,component : React.ReactElement<P>, initialState:any){ // const finalCreateStore = compose( // // Enables your middleware: // applyMiddleware(), // any Redux middleware, e.g. redux-thunk // // Provides support for DevTools: // devTools(), // // Lets you write ?debug_session=<name> in address bar ...
GetRenderElement
identifier_name
ReactViewInitializer.tsx
import * as React from 'react' import { render } from 'react-dom' import { compose, createStore, applyMiddleware } from 'redux' import { Provider,ElementClass } from 'react-redux' import App from '../containers/TodoApp' import { devTools, persistState } from 'redux-devtools'; import { DebugPanel, DevTools, LogMonitor }...
<Provider store={store}> {component} </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> </div>, Store: store } return result; }
{ // const finalCreateStore = compose( // // Enables your middleware: // applyMiddleware(), // any Redux middleware, e.g. redux-thunk // // Provides support for DevTools: // devTools(), // // Lets you write ?debug_session=<name> in address bar to persist debug sessions // persistState(window.location.href...
identifier_body
ReactViewInitializer.tsx
import * as React from 'react' import { render } from 'react-dom' import { compose, createStore, applyMiddleware } from 'redux' import { Provider,ElementClass } from 'react-redux' import App from '../containers/TodoApp' import { devTools, persistState } from 'redux-devtools'; import { DebugPanel, DevTools, LogMonitor }...
<Provider store={store}> {component} </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> </div>, Store: store } return result; }
var result = { Element :<div>
random_line_split
gulpfile.js
var gulp = require('gulp'); var browserify = require('browserify'); //transform jsx to js var reactify = require('reactify'); //convert to stream var source = require('vinyl-source-stream'); var nodemon = require('gulp-nodemon'); gulp.task('browserify', function() { //source browserify('./src/js/main.js') ...
}); }); gulp.task('default', ['browserify', 'copy', 'nodemon'], function() { return gulp.watch('src/**/*.*', ['browserify', 'copy']); });
{ called = true; cb(); }
conditional_block
gulpfile.js
var gulp = require('gulp'); var browserify = require('browserify'); //transform jsx to js var reactify = require('reactify'); //convert to stream var source = require('vinyl-source-stream'); var nodemon = require('gulp-nodemon'); gulp.task('browserify', function() { //source browserify('./src/js/main.js') ...
}).on('start', function() { if (!called) { called = true; cb(); } }); }); gulp.task('default', ['browserify', 'copy', 'nodemon'], function() { return gulp.watch('src/**/*.*', ['browserify', 'copy']); });
gulp.task('nodemon', function(cb) { var called = false; return nodemon({ script: 'server.js'
random_line_split
view.js
var MusicView = React.createClass({ getInitialState: function() { return {album: null} }, render: function() { if (this.state.album){ return ( <div className="musicView" > <h2 className="musicName"> {this.st...
} })
{ return ( <h2>Click an item to see details</h2> ) }
conditional_block
view.js
var MusicView = React.createClass({ getInitialState: function() { return {album: null} },
render: function() { if (this.state.album){ return ( <div className="musicView" > <h2 className="musicName"> {this.state.album.name} </h2> <h3 className="musicAuthor"> ...
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate sdl2; mod yuv; mod sdlui; use std::process::exit; use sdlui::{Channel, SdlUi, ViewFrame}; pub fn main()
}); let height: u32 = matches .value_of("HEIGHT") .unwrap() .parse() .unwrap_or_else(|e| { eprintln!("Invalid height: {}", e); exit(1) }); let multiplier: u32 = matches .value_of("MULTIPLIER") .unwrap_or("5") .pars...
{ let matches = clap_app!(yuvdiff => (version: "0.1") (about: "Diff YUV files") (@arg WIDTH: -w --width +takes_value +required "Width") (@arg HEIGHT: -h --height +takes_value +required "Height") (@arg CHANNEL: -c --channel +takes_value "Channel (y, u, v, c)") (@arg VI...
identifier_body
main.rs
#[macro_use] extern crate clap; extern crate sdl2; mod yuv; mod sdlui; use std::process::exit; use sdlui::{Channel, SdlUi, ViewFrame}; pub fn main() { let matches = clap_app!(yuvdiff => (version: "0.1") (about: "Diff YUV files") (@arg WIDTH: -w --width +takes_value +required "Width") ...
.unwrap_or("5") .parse() .unwrap_or_else(|e| { eprintln!("Invalid multiplier: {}", e); exit(1) }); let view: ViewFrame = matches .value_of("VIEW") .unwrap_or("a") .parse() .unwrap_or_else(|e| { eprintln!("Invalid fr...
exit(1) }); let multiplier: u32 = matches .value_of("MULTIPLIER")
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate sdl2; mod yuv; mod sdlui; use std::process::exit; use sdlui::{Channel, SdlUi, ViewFrame}; pub fn
() { let matches = clap_app!(yuvdiff => (version: "0.1") (about: "Diff YUV files") (@arg WIDTH: -w --width +takes_value +required "Width") (@arg HEIGHT: -h --height +takes_value +required "Height") (@arg CHANNEL: -c --channel +takes_value "Channel (y, u, v, c)") (@arg...
main
identifier_name
interfaceNameRuleTests.ts
/* * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
* 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. * See the License for the specific language governing permissions and * limitations under the License....
* You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 *
random_line_split
Buffalo.js
{ "metadata" : { "formatVersion" : 3.1, "sourceFile" : "Buffalo.obj", "generatedBy" : "OBJConverter", "vertices" : 2202, "faces" : 4134, "normals" : 2113, "uvs" : 0, "materials" : 4 }, "materials": [ ...
{ "DbgColor" : 60928, "DbgIndex" : 2, "DbgName" : "horse_body", "colorDiffuse" : [0.098968, 0.055305, 0.002045], "colorSpecular" : [0.0, 0.0, 0.0], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }, { "DbgColor" : 238, "DbgIndex" : 3, "DbgName" : "tail", "colorD...
},
random_line_split
wdio.conf.js
const debug = process.env.DEBUG; exports.config = { host: "127.0.0.1", port: 4444, specs: [ "./dist/e2e/**/*.spec.js" ], maxInstances: debug ? 1 : 5, capabilities: [ { maxInstances: debug ? 1 : 5, browserName: "chrome" } ], sync: true, logLevel: "silent", coloredLogs...
framework: "jasmine", reporters: [ "spec" ], execArgv: debug ? [ "--inspect" ] : undefined, // Options to be passed to Jasmine. jasmineNodeOpts: { defaultTimeoutInterval: debug ? (60 * 60 * 1000) : (30 * 1000), expectationResultHandler: function(passed, assertion) { if (p...
random_line_split
wdio.conf.js
const debug = process.env.DEBUG; exports.config = { host: "127.0.0.1", port: 4444, specs: [ "./dist/e2e/**/*.spec.js" ], maxInstances: debug ? 1 : 5, capabilities: [ { maxInstances: debug ? 1 : 5, browserName: "chrome" } ], sync: true, logLevel: "silent", coloredLogs...
browser.saveScreenshot( "dist/wdio/assertionError_" + assertion.error.message + ".png" ); } } };
{ return; }
conditional_block
parser.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/. */ //! The context within which CSS code is parsed. use context::QuirksMode; use cssparser::{Parser, SourceLocation,...
UnicodeRange::parse(input).map_err(|e| e.into()) } }
} impl Parse for UnicodeRange { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
random_line_split
parser.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/. */ //! The context within which CSS code is parsed. use context::QuirksMode; use cssparser::{Parser, SourceLocation,...
impl Parse for UnicodeRange { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { UnicodeRange::parse(input).map_err(|e| e.into()) } }
<T as OneOrMoreSeparated>::S::parse(input, |i| T::parse(context, i)) } }
identifier_body