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
worker.rs
{ pub title: String, pub action: BuildAction, } pub enum BuildAction { Empty, Exec(CommandInfo, Vec<String>), Compilation(Arc<dyn Toolchain>, CompilationTask), } pub struct BuildResult<'a> { // Completed task pub task: &'a BuildTask, // Worker number pub worker: usize, // Buil...
#[cfg(test)] mod test { use std::sync::{Arc, Mutex}; use crate::compiler::SharedState; use crate::config::Config; use super::*; #[test] fn test_execute_graph_empty() { let state = SharedState::new(&Config::defaults().unwrap()).unwrap(); let graph = BuildGraph::new(); ...
{ match &task.action { BuildAction::Empty => Ok(OutputInfo { status: Some(0), stderr: Vec::new(), stdout: Vec::new(), }), BuildAction::Exec(ref command, ref args) => state.wrap_slow(|| { command .to_command() .ar...
identifier_body
worker.rs
{ pub title: String, pub action: BuildAction, } pub enum BuildAction { Empty, Exec(CommandInfo, Vec<String>), Compilation(Arc<dyn Toolchain>, CompilationTask), } pub struct BuildResult<'a> { // Completed task pub task: &'a BuildTask, // Worker number pub worker: usize, // Buil...
let (tx_result, rx_result) = crossbeam::channel::unbounded::<ResultMessage>(); let (tx_task, rx_task) = crossbeam::channel::unbounded::<TaskMessage>(); let num_cpus = max(1, min(process_limit, graph.node_count())); crossbeam::scope(|scope| { for worker_id in 0..num_cpus { let local...
{ let task = &graph.raw_nodes()[0].weight; let result = execute_compiler(state, task); update_progress(BuildResult { worker: 0, completed: 1, total: 1, result: &result, task, })?; return result.map(|output| output.status...
conditional_block
worker.rs
Task { pub title: String, pub action: BuildAction, } pub enum BuildAction { Empty, Exec(CommandInfo, Vec<String>), Compilation(Arc<dyn Toolchain>, CompilationTask), } pub struct BuildResult<'a> { // Completed task pub task: &'a BuildTask, // Worker number pub worker: usize, // ...
while i < queue.len() { let index = queue[i]; if (!completed[index.index()]) && (is_ready(&graph, &completed, index)) { completed[index.index()] = true; for neighbor in graph.neighbors_directed(index, EdgeDirection::Incoming) { queue.push(neighbor); ...
random_line_split
worker.rs
Task { pub title: String, pub action: BuildAction, } pub enum BuildAction { Empty, Exec(CommandInfo, Vec<String>), Compilation(Arc<dyn Toolchain>, CompilationTask), } pub struct BuildResult<'a> { // Completed task pub task: &'a BuildTask, // Worker number pub worker: usize, // ...
(&self) -> Cow<str> { match self { BuildAction::Empty => Cow::Borrowed(""), BuildAction::Exec(_, ref args) => Cow::Owned(format!("{:?}", args)), BuildAction::Compilation(_, ref task) => { Cow::Borrowed(task.input_source.to_str().unwrap_or("")) } ...
title
identifier_name
feature_fee_estimation.py
1), OP_EQUAL]) P2SH_2 = CScript([OP_HASH160, hash160(REDEEM_SCRIPT_2), OP_EQUAL]) # Associated ScriptSig's to spend satisfy P2SH_1 and P2SH_2 SCRIPT_SIG = [CScript([OP_TRUE, REDEEM_SCRIPT_1]), CScript([OP_TRUE, REDEEM_SCRIPT_2])] def small_txpuzzle_randfee(from_node, conflist, unconflist, amount, min_fee, fee_increme...
def skip_test_if_missing_module(self): self.skip_if_no_wallet() def setup_network(self): """ We'll setup the network to have 3 nodes that all mine with different parameters. But first we need to use one node to create a lot of outputs which we will use to generate our ...
self.num_nodes = 3
identifier_body
feature_fee_estimation.py
160, hash160(REDEEM_SCRIPT_2), OP_EQUAL]) # Associated ScriptSig's to spend satisfy P2SH_1 and P2SH_2 SCRIPT_SIG = [CScript([OP_TRUE, REDEEM_SCRIPT_1]), CScript([OP_TRUE, REDEEM_SCRIPT_2])] def small_txpuzzle_randfee(from_node, conflist, unconflist, amount, min_fee, fee_increment): """Create and send a transactio...
self.start_node(0) self.txouts = [] self.txouts2 = [] # Split a coinbase into two transaction puzzle outputs
random_line_split
feature_fee_estimation.py
, REDEEM_SCRIPT_2])] def small_txpuzzle_randfee(from_node, conflist, unconflist, amount, min_fee, fee_increment): """Create and send a transaction with a random fee. The transaction pays to a trivial P2SH script, and assumes that its inputs are of the same form. The function takes a list of confirmed ...
self.nodes[0].generate(1)
conditional_block
feature_fee_estimation.py
1), OP_EQUAL]) P2SH_2 = CScript([OP_HASH160, hash160(REDEEM_SCRIPT_2), OP_EQUAL]) # Associated ScriptSig's to spend satisfy P2SH_1 and P2SH_2 SCRIPT_SIG = [CScript([OP_TRUE, REDEEM_SCRIPT_1]), CScript([OP_TRUE, REDEEM_SCRIPT_2])] def small_txpuzzle_randfee(from_node, conflist, unconflist, amount, min_fee, fee_increme...
(from_node, txins, txouts, initial_split=False): """Generate a lot of inputs so we can generate a ton of transactions. This function takes an input from txins, and creates and sends a transaction which splits the value into 2 outputs which are appended to txouts. Previously this was designed to be smal...
split_inputs
identifier_name
nsiqcppstyle_rulemanager.py
# modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditio...
(self, lexer, filename, dirname): """ Run rules which runs at the end of files. """ for fileEndRule in self.fileEndRules : data = lexer.Backup() fileEndRule(lexer, filename, dirname) lexer.Restore(data) def RunFileStartRule(self, lexer, filename, dirname): ...
RunFileEndRule
identifier_name
nsiqcppstyle_rulemanager.py
# modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditio...
def RunTypeScopeRule(self, lexer, contextStack): """ Run rules which runs in the type blocks """ for typeScopeRule in self.typeScopeRules : data = lexer.Backup() typeScopeRule(lexer, contextStack) lexer.Restore(data) def RunRule(self, lexer, contextStack): ...
data = lexer.Backup() typeNameRule(lexer, typeName, typeFullName, decl, contextStack, typeContext) lexer.Restore(data)
conditional_block
nsiqcppstyle_rulemanager.py
# modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditio...
def AddFunctionNameRule(self, functionRule): """ Add rule on the function name place""" self.functionNameRules.append(functionRule) def AddLineRule(self, lineRule): """ Add rule on the each line """ self.lineRules.append(lineRule) def AddRule(self, rule): """ Add...
""" Add rule which runs in function scope """ self.functionScopeRules.append(functionScopeRule)
identifier_body
nsiqcppstyle_rulemanager.py
# modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditi...
Add rule on the project Added Rule should be function with following prototype "def RunRule(targetName)" targetName is the analysis target directory. """ self.projectRules.append(projectRule) class RollbackImporter: def __init__(self): "Creates an instance and instal...
def AddProjectRules(self, projectRule): """
random_line_split
SBDraft2WorkflowStepOutputModel.ts
import {WorkflowStepOutputModel} from "../generic/WorkflowStepOutputModel"; import {WorkflowStepOutput} from "../../mappings/d2sb/WorkflowStepOutput"; import {SBDraft2StepModel} from "./SBDraft2StepModel"; import {spreadSelectProps} from "../helpers/utils"; import {StepModel} from "../generic/StepModel"; import {STEP_O...
this.secondaryFiles = attr["secondaryFiles"]; if (!this.type) this.type = new ParameterTypeModel(null); this.type.hasMapType = true; spreadSelectProps(attr, this.customProps, serializedKeys); } constructor(output?: WorkflowStepOutput, parentStep?: SBDraft2StepModel, loc?: strin...
random_line_split
SBDraft2WorkflowStepOutputModel.ts
import {WorkflowStepOutputModel} from "../generic/WorkflowStepOutputModel"; import {WorkflowStepOutput} from "../../mappings/d2sb/WorkflowStepOutput"; import {SBDraft2StepModel} from "./SBDraft2StepModel"; import {spreadSelectProps} from "../helpers/utils"; import {StepModel} from "../generic/StepModel"; import {STEP_O...
(attr: WorkflowStepOutput): void { const serializedKeys = ["id", "sbg:fileTypes"]; this._id = attr.id.split(".")[1]; // properties that will not be serialized on the step.out, // but are necessary for internal functions this.fileTypes = attr["fileTypes"]; this...
deserialize
identifier_name
SBDraft2WorkflowStepOutputModel.ts
import {WorkflowStepOutputModel} from "../generic/WorkflowStepOutputModel"; import {WorkflowStepOutput} from "../../mappings/d2sb/WorkflowStepOutput"; import {SBDraft2StepModel} from "./SBDraft2StepModel"; import {spreadSelectProps} from "../helpers/utils"; import {StepModel} from "../generic/StepModel"; import {STEP_O...
deserialize(attr: WorkflowStepOutput): void { const serializedKeys = ["id", "sbg:fileTypes"]; this._id = attr.id.split(".")[1]; // properties that will not be serialized on the step.out, // but are necessary for internal functions this.fileTypes = attr["fileType...
{ return { id: `#${this.parentStep.id}.${this._id}` }; }
identifier_body
mod.rs
//! Public-key signatures //!
//! # Selected primitive //! `crypto::sign::sign` is `ed25519`, a signature scheme specified in //! [Ed25519](http://ed25519.cr.yp.to/). This function is conjectured to meet the //! standard notion of unforgeability for a public-key signature scheme under //! chosen-message attacks. //! //! # Alternate primitives //! /...
//! # Security model //! The `sign()` function is designed to meet the standard //! notion of unforgeability for a public-key signature scheme under //! chosen-message attacks. //!
random_line_split
watch_test_name_pattern_mode.test.js
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use stric...
setEncoding() {} on(evt, callback) { this._callbacks.push(callback); } emit(key) { this._callbacks.forEach(cb => cb(key)); } }
identifier_body
watch_test_name_pattern_mode.test.js
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use stric...
ey) { this._callbacks.forEach(cb => cb(key)); } }
it(k
identifier_name
watch_test_name_pattern_mode.test.js
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use stric...
// globalConfig is updated with the current pattern expect(runJestMock.mock.calls[0][0].globalConfig).toMatchObject({ onlyChanged: false, testNamePattern: 'con *', watch: true, watchAll: false, }); }); it('can select a specific test name from the typeahead results', () => { ...
expect(runJestMock).toBeCalled();
random_line_split
retry.py
import math import time # Retry decorator with exponential backoff def retry(tries, delay=1, backoff=2): """Retries a function or method until it returns True. delay sets the initial delay, and backoff sets how much the delay should lengthen after each failure. backoff must be greater than 1, or else it isn'...
if delay <= 0: raise ValueError("delay must be greater than 0") def deco_retry(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay # make mutable rv = f(*args, **kwargs) # first attempt while mtries > 0: if rv == True or type(rv) == str: # Done on success .. ...
raise ValueError("tries must be 0 or greater")
conditional_block
retry.py
import math import time # Retry decorator with exponential backoff def retry(tries, delay=1, backoff=2): """Retries a function or method until it returns True. delay sets the initial delay, and backoff sets how much the delay should lengthen after each failure. backoff must be greater than 1, or else it isn'...
return deco_retry # @retry(arg[, ...]) -> true decorator
def f_retry(*args, **kwargs): mtries, mdelay = tries, delay # make mutable rv = f(*args, **kwargs) # first attempt while mtries > 0: if rv == True or type(rv) == str: # Done on success .. return rv mtries -= 1 # consume an attempt time.sleep(mdelay) # wait... ...
identifier_body
retry.py
import math import time # Retry decorator with exponential backoff def retry(tries, delay=1, backoff=2): """Retries a function or method until it returns True. delay sets the initial delay, and backoff sets how much the delay should lengthen after each failure. backoff must be greater than 1, or else it isn'...
(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay # make mutable rv = f(*args, **kwargs) # first attempt while mtries > 0: if rv == True or type(rv) == str: # Done on success .. return rv mtries -= 1 # consume an attempt time.sleep(mdelay) # ...
deco_retry
identifier_name
retry.py
import math import time # Retry decorator with exponential backoff def retry(tries, delay=1, backoff=2): """Retries a function or method until it returns True. delay sets the initial delay, and backoff sets how much the delay should lengthen after each failure. backoff must be greater than 1, or else it isn'...
rv = f(*args, **kwargs) # Try again return False # Ran out of tries :-( return f_retry # true decorator -> decorated function return deco_retry # @retry(arg[, ...]) -> true decorator
time.sleep(mdelay) # wait... mdelay *= backoff # make future wait longer
random_line_split
css.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
await app.workbench.settingsEditor.addUserSetting('css.lint.emptyRules', '"error"'); await app.workbench.quickopen.openFile('style.css'); await app.client.type('.foo{}'); let error = await app.client.waitForElement(Problems.getSelectorInEditor(ProblemSeverity.ERROR)); await app.screenCapturer.capture('CSS Er...
await app.workbench.problems.hideProblemsView(); }); it('verifies that warning becomes an error once setting changed', async () => {
random_line_split
index.js
const express = require('express') const session = require('express-session') const MongoStore = require('connect-mongo')(session) const mainRouter = express.Router() const passport = require('../utils/passport') const mongoose = require('../db/index') const userController = require('../controllers/userController') con...
// user const userRouter = express.Router() userRouter.get('/oauth', passport.authenticate('github')) userRouter.get('/oauth/callback', passport.authenticate('github'), userController.oauthCallback) userRouter.get('/logout', authMiddleware, userController.logout) userRouter.get('/checkAuth', userController.checkAuth) ...
random_line_split
index.js
function Controller()
excerpt: jdata.list[key].excerpt }); article.save(); } var articles = Alloy.createCollection("Article"); articles.fetch(); var row_data = []; articles.map(function(article) { var title = artic...
{ function initArticles() { url = "https://getpocket.com/v3/get"; var ajax = Ti.Network.createHTTPClient(); ajax.onerror = function() { alert("Error"); }; ajax.onload = function() { var data = this.responseText; var jdata = JSON.parse(data)...
identifier_body
index.js
function Controller() { function
() { url = "https://getpocket.com/v3/get"; var ajax = Ti.Network.createHTTPClient(); ajax.onerror = function() { alert("Error"); }; ajax.onload = function() { var data = this.responseText; var jdata = JSON.parse(data); var articles ...
initArticles
identifier_name
index.js
function Controller() { function initArticles() { url = "https://getpocket.com/v3/get"; var ajax = Ti.Network.createHTTPClient(); ajax.onerror = function() { alert("Error"); }; ajax.onload = function() { var data = this.responseText; var jd...
url: url }; var row = Alloy.createController("article_row", article_data).getView(); row_data.push(row); }); $.table.setData(row_data); }; ajax.open("POST", url); ajax.send({ consumer_key: "18...
var article_data = { title: title,
random_line_split
interface-gen.js
// generates an interface file given an eni file // you can generate an eni file using the aws-cli // example: // aws ec2 describe-network-interfaces --network-interface-ids eni-2492676c > eni-7290653a.json var ENI_FILE = "json/eni-651e2c2c.json"; // the interface you want to configure var INTERFACE = "eth1"; // po...
else { console.log("Generated networking config and saved it to " + INTERFACE + ".cfg."); } }); fs.writeFile("./cfg/" + INTERFACE + "-squid.cfg", squidConfig, function(err) { if(err) { console.log(err); } else { console.log("Generated squid config and saved it to " + INTE...
{ console.log(err); }
conditional_block
interface-gen.js
// generates an interface file given an eni file // you can generate an eni file using the aws-cli // example: // aws ec2 describe-network-interfaces --network-interface-ids eni-2492676c > eni-7290653a.json var ENI_FILE = "json/eni-651e2c2c.json"; // the interface you want to configure var INTERFACE = "eth1"; // por...
fs.writeFile("./cfg/" + INTERFACE + "-squid.cfg", squidConfig, function(err) { if(err) { console.log(err); } else { console.log("Generated squid config and saved it to " + INTERFACE + ".cfg."); } }); fs.writeFile("./cfg/" + INTERFACE + "-rt_tables.cfg", rtTables, function(err) ...
random_line_split
publish-docker.ts
import { cd, exec } from 'shelljs'; import * as inquirer from 'inquirer'; import * as semver from 'semver'; const prompt = inquirer.createPromptModule(); async function release() { cd(`${__dirname}/docker`); const { channel } = await prompt([{ type: 'list', name: 'channel', message: '...
console.log(`Last version on channel ${channel} is ${version}`); exec(`docker build --rm --no-cache --build-arg VAULTAGE_CHANNEL=${channel} --tag hmil/vaultage:${version} .`); exec(`docker tag hmil/vaultage:${version} hmil/vaultage:${channel}`); exec(`docker push hmil/vaultage:${channel}`); exec...
{ throw new Error(`Invalid version: ${version}`) }
conditional_block
publish-docker.ts
import { cd, exec } from 'shelljs'; import * as inquirer from 'inquirer'; import * as semver from 'semver'; const prompt = inquirer.createPromptModule(); async function
() { cd(`${__dirname}/docker`); const { channel } = await prompt([{ type: 'list', name: 'channel', message: 'To which channel would you like to release?', choices: ['dev', 'next', 'latest'], filter: function(val) { return val.toLowerCase(); } }]);...
release
identifier_name
publish-docker.ts
import { cd, exec } from 'shelljs'; import * as inquirer from 'inquirer'; import * as semver from 'semver';
cd(`${__dirname}/docker`); const { channel } = await prompt([{ type: 'list', name: 'channel', message: 'To which channel would you like to release?', choices: ['dev', 'next', 'latest'], filter: function(val) { return val.toLowerCase(); } }]); ...
const prompt = inquirer.createPromptModule(); async function release() {
random_line_split
publish-docker.ts
import { cd, exec } from 'shelljs'; import * as inquirer from 'inquirer'; import * as semver from 'semver'; const prompt = inquirer.createPromptModule(); async function release()
} console.log(`Last version on channel ${channel} is ${version}`); exec(`docker build --rm --no-cache --build-arg VAULTAGE_CHANNEL=${channel} --tag hmil/vaultage:${version} .`); exec(`docker tag hmil/vaultage:${version} hmil/vaultage:${channel}`); exec(`docker push hmil/vaultage:${channel}`); ...
{ cd(`${__dirname}/docker`); const { channel } = await prompt([{ type: 'list', name: 'channel', message: 'To which channel would you like to release?', choices: ['dev', 'next', 'latest'], filter: function(val) { return val.toLowerCase(); } }]); ...
identifier_body
list.spec.tsx
import { mount } from 'enzyme'; import { IKayentaAction } from 'kayenta/actions/creators'; import * as React from 'react'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import { IUpdateListPayload, List, ListAction, updateListReducer } from './list';
describe('Reducer: updateListReducer', () => { const createAction = (payload: IUpdateListPayload): IKayentaAction<IUpdateListPayload> => ({ type: 'update_list', payload, }); const reducer = updateListReducer('defaultValue'); it('adds', () => { expect( reducer( [], createActio...
import { rootReducer } from '../reducers';
random_line_split
hrtb-parse.rs
// run-pass // Test that we can parse all the various places that a `for` keyword // can appear representing universal quantification. // pretty-expanded FIXME #23616 #![allow(unused_variables)] #![allow(dead_code)] trait Get<A,R> { fn get(&self, arg: A) -> R; } // Parse HRTB with explicit `for` in a where-clau...
}
fn foo23(t: for<'a> unsafe extern "C" fn(i32) -> i32) { } fn main() {
random_line_split
hrtb-parse.rs
// run-pass // Test that we can parse all the various places that a `for` keyword // can appear representing universal quantification. // pretty-expanded FIXME #23616 #![allow(unused_variables)] #![allow(dead_code)] trait Get<A,R> { fn get(&self, arg: A) -> R; } // Parse HRTB with explicit `for` in a where-clau...
fn foo01<T: for<'a> Get<&'a i32, &'a i32>>(t: T) { } // Parse HRTB with explicit `for` in various sorts of types: fn foo10(t: Box<dyn for<'a> Get<i32, i32>>) { } fn foo11(t: Box<dyn for<'a> Fn(i32) -> i32>) { } fn foo20(t: for<'a> fn(i32) -> i32) { } fn foo21(t: for<'a> unsafe fn(i32) -> i32) { } fn foo22(t: for<'...
{ }
identifier_body
hrtb-parse.rs
// run-pass // Test that we can parse all the various places that a `for` keyword // can appear representing universal quantification. // pretty-expanded FIXME #23616 #![allow(unused_variables)] #![allow(dead_code)] trait Get<A,R> { fn get(&self, arg: A) -> R; } // Parse HRTB with explicit `for` in a where-clau...
() { }
main
identifier_name
nlri.py
import array import struct import socket from odict import OrderedDict as OD class NLRI: def __init__(self, afi, safi, val): self.afi = afi self.safi = safi self.val = val def encode(self): return self.val class vpnv4(NLRI): def __init__(self, labels, rd, prefix): ...
elif masklen > 0: return 1 return 0 def pip(pi, masklen): pi += '\x00\x00\x00\x00' return '%s/%s' % (socket.inet_ntoa(pi[:4]), masklen) def parse(bytes, afi=1, safi=0): rv = [] if afi==1 and safi==128: klass = vpnv4 else: klass = ipv4 idx = 0 while idx <...
return 2
conditional_block
nlri.py
import array import struct import socket from odict import OrderedDict as OD class NLRI: def __init__(self, afi, safi, val): self.afi = afi self.safi = safi self.val = val def encode(self): return self.val class vpnv4(NLRI): def __init__(self, labels, rd, prefix): ...
def pip(pi, masklen): pi += '\x00\x00\x00\x00' return '%s/%s' % (socket.inet_ntoa(pi[:4]), masklen) def parse(bytes, afi=1, safi=0): rv = [] if afi==1 and safi==128: klass = vpnv4 else: klass = ipv4 idx = 0 while idx < len(bytes): plen, = struct.unpack_from('B',...
if masklen > 24: return 4 elif masklen > 16: return 3 elif masklen > 8: return 2 elif masklen > 0: return 1 return 0
identifier_body
nlri.py
import array import struct import socket from odict import OrderedDict as OD class NLRI: def
(self, afi, safi, val): self.afi = afi self.safi = safi self.val = val def encode(self): return self.val class vpnv4(NLRI): def __init__(self, labels, rd, prefix): self.labels = labels self.rd = rd self.prefix = prefix def __repr__(self): if...
__init__
identifier_name
nlri.py
import array import struct import socket from odict import OrderedDict as OD class NLRI: def __init__(self, afi, safi, val): self.afi = afi self.safi = safi self.val = val def encode(self): return self.val class vpnv4(NLRI): def __init__(self, labels, rd, prefix): ...
return '%s:%s' % (self.rd, self.prefix) def __cmp__(self, other): if isinstance(other, vpnv4): return cmp( (self.labels, self.rd, self.prefix), (other.labels, other.rd, other.prefix), ) return -1 def encode(self):...
def __str__(self):
random_line_split
py_func.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
if not arg_is_tensor[arg_number]: raise ValueError( 'argument %d was used with MatchDType and must be a tf.Tensor, but ' 'was %s instead' % (arg_number, type(arg))) return arg.dtype if return_dtypes: if isinstance(return_dtypes, MatchDType): return_dtypes = match_arg_dtype...
# Set up return dtypes. def match_arg_dtype(arg_number): arg = args[arg_number]
random_line_split
py_func.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(arg_number): arg = args[arg_number] if not arg_is_tensor[arg_number]: raise ValueError( 'argument %d was used with MatchDType and must be a tf.Tensor, but ' 'was %s instead' % (arg_number, type(arg))) return arg.dtype if return_dtypes: if isinstance(return_dtypes, MatchDTyp...
match_arg_dtype
identifier_name
py_func.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
return arg.dtype if return_dtypes: if isinstance(return_dtypes, MatchDType): return_dtypes = match_arg_dtype(return_dtypes.arg_number) elif isinstance(return_dtypes, (list, tuple)): return_dtypes = tuple( match_arg_dtype(a.arg_number) if isinstance(a, MatchDType) else a f...
raise ValueError( 'argument %d was used with MatchDType and must be a tf.Tensor, but ' 'was %s instead' % (arg_number, type(arg)))
conditional_block
py_func.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
if return_dtypes: if isinstance(return_dtypes, MatchDType): return_dtypes = match_arg_dtype(return_dtypes.arg_number) elif isinstance(return_dtypes, (list, tuple)): return_dtypes = tuple( match_arg_dtype(a.arg_number) if isinstance(a, MatchDType) else a for a in return_dtypes...
arg = args[arg_number] if not arg_is_tensor[arg_number]: raise ValueError( 'argument %d was used with MatchDType and must be a tf.Tensor, but ' 'was %s instead' % (arg_number, type(arg))) return arg.dtype
identifier_body
confParser.py
import string from pyparsing import ( Literal, White, Word, alphanums, CharsNotIn, Forward, Group, SkipTo, Optional, OneOrMore, ZeroOrMore, pythonStyleComment) class Parser(object): left_bracket = Literal("{").suppress() right_bracket = Literal("}").suppress() semicolon = Literal(";").suppress() ...
self.source = source def parse(self): return self.script.parseString(self.source) def as_list(self): return self.parse().asList() class Dumper(object): def __init__(self, blocks, indentation=4): self.blocks = blocks self.indentation = indentation def __iter__...
script = OneOrMore(Group(assignment) | block).ignore(pythonStyleComment) def __init__(self, source):
random_line_split
confParser.py
import string from pyparsing import ( Literal, White, Word, alphanums, CharsNotIn, Forward, Group, SkipTo, Optional, OneOrMore, ZeroOrMore, pythonStyleComment) class Parser(object): left_bracket = Literal("{").suppress() right_bracket = Literal("}").suppress() semicolon = Literal(";").suppress() ...
else: dumped = spacer.join(parameter) + ';' yield spacer * ( current_indent + self.indentation) + dumped yield indentation + '}' else: yield spacer * current_indent + key + space...
dumped = self.__iter__( [parameter], current_indent + self.indentation) for line in dumped: yield line
conditional_block
confParser.py
import string from pyparsing import ( Literal, White, Word, alphanums, CharsNotIn, Forward, Group, SkipTo, Optional, OneOrMore, ZeroOrMore, pythonStyleComment) class Parser(object): left_bracket = Literal("{").suppress() right_bracket = Literal("}").suppress() semicolon = Literal(";").suppress() ...
(self): return '\n'.join(self) def to_file(self, out): for line in self: out.write(line+"\n") out.close() return out def loads(source): return Parser(source).as_list() def load(_file): return loads(_file.read()) def dumps(blocks, indentation=4): return ...
as_string
identifier_name
confParser.py
import string from pyparsing import ( Literal, White, Word, alphanums, CharsNotIn, Forward, Group, SkipTo, Optional, OneOrMore, ZeroOrMore, pythonStyleComment) class Parser(object): left_bracket = Literal("{").suppress() right_bracket = Literal("}").suppress() semicolon = Literal(";").suppress() ...
def as_list(self): return self.parse().asList() class Dumper(object): def __init__(self, blocks, indentation=4): self.blocks = blocks self.indentation = indentation def __iter__(self, blocks=None, current_indent=0, spacer=' '): blocks = blocks or self.blocks for ...
return self.script.parseString(self.source)
identifier_body
vsp_iscsi.py
# Copyright (C) 2016, Hitachi, Ltd. # # 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...
(self, snapshot): """Delete the specified snapshot.""" self.common.delete_snapshot(snapshot) def get_volume_stats(self, refresh=False): """Return properties, capabilities and current states of the driver.""" return self.common.get_volume_stats(refresh) @utils.output_start_end_l...
delete_snapshot
identifier_name
vsp_iscsi.py
# Copyright (C) 2016, Hitachi, Ltd. # # 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...
super(VSPISCSIDriver, self).__init__(*args, **kwargs) self.configuration.append_config_values(common.common_opts) self.configuration.append_config_values(iscsi_opts) self.common = utils.import_object( self.configuration, _DRIVER_INFO, kwargs.get('db')) def check_for_set...
"""iSCSI class for Hitachi VSP Driver. Version history: .. code-block:: none 1.0.0 - Initial driver. """ VERSION = common.VERSION # ThirdPartySystems wiki page CI_WIKI_NAME = "Hitachi_VSP_CI" def __init__(self, *args, **kwargs): """Initialize instance variables.""" ...
identifier_body
vsp_iscsi.py
# Copyright (C) 2016, Hitachi, Ltd. # # 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...
context, volume, image_service, image_id) self.common.discard_zero_page(volume) @utils.output_start_end_log def extend_volume(self, volume, new_size): """Extend the specified volume to the specified size.""" self.common.extend_volume(volume, new_size) @utils.output_star...
@utils.output_start_end_log def copy_image_to_volume(self, context, volume, image_service, image_id): """Fetch the image from image_service and write it to the volume.""" super(VSPISCSIDriver, self).copy_image_to_volume(
random_line_split
index.js
import TestUtils from 'react-dom/test-utils'; import React from 'react'; import ReactDOM from 'react-dom'; import Textarea from '../'; const { findRenderedDOMComponentWithClass, renderIntoDocument, Simulate } = TestUtils; function
() { return () => { return 'fake function'; } } describe('The input textarea', () => { describe('when mounted with no props', () => { let reactComponent; let domNode; let inputNode; beforeEach(() => { reactComponent = renderIntoDocument(<Textarea name='my...
fake
identifier_name
index.js
import TestUtils from 'react-dom/test-utils'; import React from 'react'; import ReactDOM from 'react-dom'; import Textarea from '../'; const { findRenderedDOMComponentWithClass, renderIntoDocument, Simulate } = TestUtils; function fake() { return () => { return 'fake function'; } } describe('The inpu...
}); it('should render an empty textarea', () => { expect(inputNode).toBeDefined(); expect(inputNode.type).toBe('textarea'); expect(inputNode.value).toBe(''); expect(() => findRenderedDOMComponentWithClass(reactComponent, 'label-error')).toThrow('Did not fi...
expect(divMdl.tagName).toBe('DIV'); expect(divMdl.className).toMatch('mdl-textfield mdl-js-textfield'); }); it('should have a material designed textarea', () => { expect(inputNode.getAttribute('class')).toBe('mdl-textfield__input');
random_line_split
index.js
import TestUtils from 'react-dom/test-utils'; import React from 'react'; import ReactDOM from 'react-dom'; import Textarea from '../'; const { findRenderedDOMComponentWithClass, renderIntoDocument, Simulate } = TestUtils; function fake()
describe('The input textarea', () => { describe('when mounted with no props', () => { let reactComponent; let domNode; let inputNode; beforeEach(() => { reactComponent = renderIntoDocument(<Textarea name='myTextArea' onChange={fake} />); domNode = ReactDOM.f...
{ return () => { return 'fake function'; } }
identifier_body
util.d.ts
import { Document } from './index' import { CST } from './parse-cst' import { AST, Pair, Scalar, Schema } from './types' export function findPair(items: any[], key: Scalar | any): Pair | undefined export function parseMap(doc: Document, cst: CST.Map): AST.BlockMap export function parseMap(doc: Document, cst: CST.Flow...
extends YAMLError { name: 'YAMLSemanticError' } export class YAMLSyntaxError extends YAMLError { name: 'YAMLSyntaxError' } export class YAMLWarning extends YAMLError { name: 'YAMLWarning' }
YAMLSemanticError
identifier_name
util.d.ts
import { Document } from './index' import { CST } from './parse-cst' import { AST, Pair, Scalar, Schema } from './types' export function findPair(items: any[], key: Scalar | any): Pair | undefined export function parseMap(doc: Document, cst: CST.Map): AST.BlockMap export function parseMap(doc: Document, cst: CST.Flow...
makePretty(): void } export class YAMLReferenceError extends YAMLError { name: 'YAMLReferenceError' } export class YAMLSemanticError extends YAMLError { name: 'YAMLSemanticError' } export class YAMLSyntaxError extends YAMLError { name: 'YAMLSyntaxError' } export class YAMLWarning extends YAMLError { name:...
/** * Drops `source` and adds `nodeType`, `range` and `linePos`, as well as * adding details to `message`. Run automatically for document errors if * the `prettyErrors` option is set. */
random_line_split
sensor.py
"""Support for the Italian train system using ViaggiaTreno API.""" import asyncio import logging import time import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES im...
CONF_STATION_NAME = "station_name" CONF_TRAIN_ID = "train_id" ARRIVED_STRING = "Arrived" CANCELLED_STRING = "Cancelled" NOT_DEPARTED_STRING = "Not departed yet" NO_INFORMATION_STRING = "No information for this train now" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_TRAIN_ID): cv.string, ...
CONF_NAME = "train_name" CONF_STATION_ID = "station_id"
random_line_split
sensor.py
"""Support for the Italian train system using ViaggiaTreno API.""" import asyncio import logging import time import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES im...
@property def extra_state_attributes(self): """Return extra attributes.""" self._attributes[ATTR_ATTRIBUTION] = ATTRIBUTION return self._attributes @staticmethod def has_departed(data): """Check if the train has actually departed.""" try: first_stat...
"""Return the unit of measurement.""" return self._unit
identifier_body
sensor.py
"""Support for the Italian train system using ViaggiaTreno API.""" import asyncio import logging import time import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES im...
(self): """Return extra attributes.""" self._attributes[ATTR_ATTRIBUTION] = ATTRIBUTION return self._attributes @staticmethod def has_departed(data): """Check if the train has actually departed.""" try: first_station = data["fermate"][0] if data["...
extra_state_attributes
identifier_name
sensor.py
"""Support for the Italian train system using ViaggiaTreno API.""" import asyncio import logging import time import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES im...
async_add_entities([ViaggiaTrenoSensor(train_id, station_id, name)]) async def async_http_request(hass, uri): """Perform actual request.""" try: session = hass.helpers.aiohttp_client.async_get_clientsession(hass) with async_timeout.timeout(REQUEST_TIMEOUT): req = await session...
name = DEFAULT_NAME.format(train_id)
conditional_block
fields.py
import bleach from django.db.models.fields import TextField from django.utils.encoding import smart_text from .widgets import RichTextareaWidget class RichTextarea(TextField): """ """ def to_python(self, value):
'th', 'td', ] ALLOWED_ATTRIBUTES = { } html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, strip=True) return html else: return value def formfield(self, **kwargs): kwa...
""" """ if value: html = value.replace('&nbsp;', ' ') html = smart_text(html.encode('utf-8')) ALLOWED_TAGS = [ 'p', 'br', 'i', 'strong', 'b', 'ul', 'li',...
identifier_body
fields.py
import bleach from django.db.models.fields import TextField from django.utils.encoding import smart_text from .widgets import RichTextareaWidget class RichTextarea(TextField): """ """ def to_python(self, value): """ """ if value: html = value.replace('&nbsp;', ' ') ...
'ul', 'li', 'ol', 'table', 'tr', 'th', 'td', ] ALLOWED_ATTRIBUTES = { } html = bleach.clean(html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, strip=Tr...
'br', 'i', 'strong', 'b',
random_line_split
fields.py
import bleach from django.db.models.fields import TextField from django.utils.encoding import smart_text from .widgets import RichTextareaWidget class RichTextarea(TextField): """ """ def to_python(self, value): """ """ if value: html = value.replace('&nbsp;', ' ') ...
(self, **kwargs): kwargs['widget'] = RichTextareaWidget return super(RichTextarea, self).formfield(**kwargs)
formfield
identifier_name
fields.py
import bleach from django.db.models.fields import TextField from django.utils.encoding import smart_text from .widgets import RichTextareaWidget class RichTextarea(TextField): """ """ def to_python(self, value): """ """ if value: html = value.replace('&nbsp;', ' ') ...
def formfield(self, **kwargs): kwargs['widget'] = RichTextareaWidget return super(RichTextarea, self).formfield(**kwargs)
return value
conditional_block
test_add_group.py
# -*- coding: utf-8 -*- from model.group import Group def test_add_group(app): old_groups = app.group.get_group_list() group = Group(name="hjhj", header="jhjh", footer="jhjjhhj") app.group.create(group) new_groups = app.group.get_group_list() assert len(old_groups) + 1 == len(new_groups) old_...
old_groups = app.group.get_group_list() group = Group(name="", header="", footer="") app.group.create(group) new_groups = app.group.get_group_list() assert len(old_groups) + 1 == len(new_groups) old_groups.append(group) assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Gro...
identifier_body
test_add_group.py
# -*- coding: utf-8 -*- from model.group import Group def
(app): old_groups = app.group.get_group_list() group = Group(name="hjhj", header="jhjh", footer="jhjjhhj") app.group.create(group) new_groups = app.group.get_group_list() assert len(old_groups) + 1 == len(new_groups) old_groups.append(group) assert sorted(old_groups, key=Group.id_or_max) == ...
test_add_group
identifier_name
test_add_group.py
# -*- coding: utf-8 -*- from model.group import Group
def test_add_group(app): old_groups = app.group.get_group_list() group = Group(name="hjhj", header="jhjh", footer="jhjjhhj") app.group.create(group) new_groups = app.group.get_group_list() assert len(old_groups) + 1 == len(new_groups) old_groups.append(group) assert sorted(old_groups, key=Gr...
random_line_split
vm.py
import sys import os import pty, shlex import signal import subprocess import socket import time import atexit import re import string import logging import random from .vif import VirtualInterface from .vnet import VirtualNet from .riotnative import RIOT from string import Template import libvirt import hashlib a...
elif self.nodeType == "riot_native": logging.getLogger("Looking up this node") self.vm_instance = RIOT(self.fullname, self.binary, self.vmgroup_name, self.nics[0].tap) return True def define(self, conn=None): if self.nodeType == "meshrouter": if not ...
global all_domains if self.nodeType == "meshrouter": if not all_domains: all_domains = {} for id in conn.listDomainsID(): dom = conn.lookupByID(id) all_domains[dom.name()] = dom for id in conn.listDefinedDomains()...
identifier_body
vm.py
import sys import os import pty, shlex import signal import subprocess import socket import time import atexit import re import string import logging import random from .vif import VirtualInterface from .vnet import VirtualNet from .riotnative import RIOT from string import Template import libvirt import hashlib a...
(): def __init__(self, name, nodeType, nics=None, binary=None, vmgroup_name=""): self.name = name self.nodeType = nodeType self.binary = binary self.nics = nics if not nics: self.nics = [] self.vmgroup_name = vmgroup_name self.vm_instance = None ...
VM
identifier_name
vm.py
import sys import os import pty, shlex import signal import subprocess import socket import time import atexit import re import string import logging import random from .vif import VirtualInterface from .vnet import VirtualNet from .riotnative import RIOT from string import Template import libvirt import hashlib a...
if self.nodeType == "meshrouter": if self.vm_instance or self.lookup(conn): self.vm_instance.undefine() def start(self): if self.vm_instance: if not self.vm_instance.isActive(): self.vm_instance.create() def stop(self): if self.vm...
# TODO: needs here anything to be done for RIOT native?
random_line_split
vm.py
import sys import os import pty, shlex import signal import subprocess import socket import time import atexit import re import string import logging import random from .vif import VirtualInterface from .vnet import VirtualNet from .riotnative import RIOT from string import Template import libvirt import hashlib a...
def define(self, conn=None): if self.nodeType == "meshrouter": if not self.lookup(conn): logging.getLogger("").info("Defining VM %s" %(self.fullname)) self.vm_instance = conn.defineXML(self.create_vm_xml()) else: logging.getLogger("").info("D...
logging.getLogger("Looking up this node") self.vm_instance = RIOT(self.fullname, self.binary, self.vmgroup_name, self.nics[0].tap) return True
conditional_block
ServerGroupDetails.tsx
import { UISref } from '@uirouter/react'; import React from 'react'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { RunningTasks } from './RunningTasks'; import type { IServerGroupDetailsProps, IServerGroupDetailsState } from './ServerGroupDetailsWrapper'; import { ServerGroupInsi...
public render() { const { Actions, app, sections } = this.props; const { loading, serverGroup } = this.state; const showEntityTags = SETTINGS.feature && SETTINGS.feature.entityTags; const hasInsightActions = serverGroup && serverGroup.insightActions && serverGroup.insightActions.length > 0; co...
{ this.destroy$.next(); this.serverGroupsRefreshUnsubscribe(); }
identifier_body
ServerGroupDetails.tsx
import { UISref } from '@uirouter/react'; import React from 'react'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { RunningTasks } from './RunningTasks'; import type { IServerGroupDetailsProps, IServerGroupDetailsState } from './ServerGroupDetailsWrapper'; import { ServerGroupInsi...
); } }
</div> )} </div>
random_line_split
ServerGroupDetails.tsx
import { UISref } from '@uirouter/react'; import React from 'react'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { RunningTasks } from './RunningTasks'; import type { IServerGroupDetailsProps, IServerGroupDetailsState } from './ServerGroupDetailsWrapper'; import { ServerGroupInsi...
} public componentWillUnmount(): void { this.destroy$.next(); this.serverGroupsRefreshUnsubscribe(); } public render() { const { Actions, app, sections } = this.props; const { loading, serverGroup } = this.state; const showEntityTags = SETTINGS.feature && SETTINGS.feature.entityTags; ...
{ this.props .detailsGetter(nextProps, this.autoClose) .pipe(takeUntil(this.destroy$)) .subscribe(this.updateServerGroup); }
conditional_block
ServerGroupDetails.tsx
import { UISref } from '@uirouter/react'; import React from 'react'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { RunningTasks } from './RunningTasks'; import type { IServerGroupDetailsProps, IServerGroupDetailsState } from './ServerGroupDetailsWrapper'; import { ServerGroupInsi...
(props: IServerGroupDetailsProps) { super(props); this.state = { loading: true, serverGroup: undefined, }; } private autoClose(): void { ReactInjector.$state.params.allowModalToStayOpen = true; ReactInjector.$state.go('^', null, { location: 'replace' }); } private updateServer...
constructor
identifier_name
animation.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/. */ //! CSS transitions and animations. use context::LayoutContext; use flow::{self, Flow}; use gfx::display_list::Op...
if should_push { new_running_animations.push(animation); } } if running_animations.is_empty() && new_running_animations.is_empty() { // Nothing to do. Return early so we don't flood the compositor with // `ChangeRunningAnimationsState` messages. return ...
{ // If the animation was already present in the list for the // node, just update its state, else push the new animation to // run. if let Some(ref mut animations) = running_animations.get_mut(node) { // TODO: This being linear is probably not optimal. ...
conditional_block
animation.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/. */ //! CSS transitions and animations. use context::LayoutContext; use flow::{self, Flow}; use gfx::display_list::Op...
(constellation_chan: &IpcSender<ConstellationMsg>, script_chan: &IpcSender<ConstellationControlMsg>, running_animations: &mut HashMap<OpaqueNode, Vec<Animation>>, expired_animations: &mut HashMap<OpaqueNode, Vec<Animation>>, ...
update_animation_state
identifier_name
animation.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/. */ //! CSS transitions and animations. use context::LayoutContext; use flow::{self, Flow}; use gfx::display_list::Op...
}
{ let mut damage = RestyleDamage::empty(); flow.mutate_fragments(&mut |fragment| { if let Some(ref animations) = animations.get(&fragment.node) { for animation in animations.iter() { let old_style = fragment.style.clone(); update_style_for_animation(&context.s...
identifier_body
animation.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/. */ //! CSS transitions and animations. use context::LayoutContext; use flow::{self, Flow}; use gfx::display_list::Op...
new_running_animations.push(animation); } } if running_animations.is_empty() && new_running_animations.is_empty() { // Nothing to do. Return early so we don't flood the compositor with // `ChangeRunningAnimationsState` messages. return } let now = timer.seco...
} if should_push {
random_line_split
mod.rs
//! GPU resource managers pub use crate::context::Texture; pub use crate::resource::effect::{Effect, ShaderAttribute, ShaderUniform}; pub use crate::resource::framebuffer_manager::{ FramebufferManager, OffscreenBuffers, RenderTarget, }; pub use crate::resource::gl_primitive::GLPrimitive; pub use crate::resource::g...
mod planar_material_manager; mod planar_mesh; mod planar_mesh_manager; mod texture_manager;
mod mesh; mod mesh_manager;
random_line_split
send_key.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2014 Andy Stewart # # Author: Andy Stewart <lazycat.manatee@gmail.com> # Maintainer: Andy Stewart <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publ...
xlib_display = get_xlib_display() mask = 0 for modifier in modifiers: if modifier == "Ctrl": mask |= Xlib.X.ControlMask elif modifier == "Alt": mask |= Xlib.X.Mod1Mask elif modifier == "Shift": mask |= Xlib.X.ShiftMask elif modifier ==...
def send_string(window, str, modifiers, press=True):
random_line_split
send_key.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2014 Andy Stewart # # Author: Andy Stewart <lazycat.manatee@gmail.com> # Maintainer: Andy Stewart <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publ...
event = event_type( root=xlib_display.screen().root, window=window, child=Xlib.X.NONE, same_screen=1, root_x=0, root_y=0, event_x=0, event_y=0, state=mask, detail=keycode, time=Xlib.X.CurrentTime, ) window.send_event(eve...
xlib_display = get_xlib_display() mask = 0 for modifier in modifiers: if modifier == "Ctrl": mask |= Xlib.X.ControlMask elif modifier == "Alt": mask |= Xlib.X.Mod1Mask elif modifier == "Shift": mask |= Xlib.X.ShiftMask elif modifier == "Su...
identifier_body
send_key.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2014 Andy Stewart # # Author: Andy Stewart <lazycat.manatee@gmail.com> # Maintainer: Andy Stewart <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publ...
(ch): keysym = Xlib.XK.string_to_keysym(ch) if keysym == 0: # Unfortunately, although this works to get the correct keysym # i.e. keysym for '#' is returned as "numbersign" # the subsequent display.keysym_to_keycode("numbersign") is 0. if ch in special_X_keysyms: spec...
get_keysym
identifier_name
send_key.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2014 Andy Stewart # # Author: Andy Stewart <lazycat.manatee@gmail.com> # Maintainer: Andy Stewart <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Publ...
return keysym def send_string(window, str, modifiers, press=True): xlib_display = get_xlib_display() mask = 0 for modifier in modifiers: if modifier == "Ctrl": mask |= Xlib.X.ControlMask elif modifier == "Alt": mask |= Xlib.X.Mod1Mask elif modifier ...
special = special_X_keysyms[ch] keysym = Xlib.XK.string_to_keysym(special)
conditional_block
time.ts
import moment from 'moment-timezone' export const getLocalTime = (datetimeString) => { return datetimeString ? moment.utc(datetimeString).tz(moment.tz.guess()) : null } export const specialFormatIfToday = (datetimeString) => { const localTime = datetimeString ? moment.utc(datetimeString).tz(moment.tz.guess()) : n...
const now = moment().utc() return now.isAfter(datetimeString) }
return datetime.format('ddd, MMM D') } } export const isOutdated = (datetimeString) => {
random_line_split
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use std::task; fn child(tx: &Sender<Box<uint>>, i: uint) { tx.send(box i); } pub fn main() { let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; for i in range(0u, n) { let tx = tx.clone(); task::spawn(proc() { child(&tx, i) }); expected += i...
random_line_split
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; for i in range(0u, n) { let tx = tx.clone(); task::spawn(proc() { child(&tx, i) }); expected += i; } let mut actual = 0u; for _ in range(0u, n) { let j = rx.recv(); ...
main
identifier_name
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let (tx, rx) = channel(); let n = 100u; let mut expected = 0u; for i in range(0u, n) { let tx = tx.clone(); task::spawn(proc() { child(&tx, i) }); expected += i; } let mut actual = 0u; for _ in range(0u, n) { let j = rx.recv(); a...
identifier_body
method-call-tracker.js
import { checkTest } from './utils'; var MethodCallTracker = function(env, methodName) { this._env = env; this._methodName = methodName; this._isExpectingNoCalls = false; this._expecteds = []; this._actuals = []; }; MethodCallTracker.prototype = { stubMethod() { if (this._originalMethod) { // Me...
, expectCall(message) { this.stubMethod(); this._expecteds.push(message || /.*/); }, expectNoCalls() { this.stubMethod(); this._isExpectingNoCalls = true; }, isExpectingNoCalls() { return this._isExpectingNoCalls; }, isExpectingCalls() { return !this._isExpectingNoCalls && this...
{ if (this._originalMethod) { this._env.setDebugFunction(this._methodName, this._originalMethod); } }
identifier_body
method-call-tracker.js
import { checkTest } from './utils'; var MethodCallTracker = function(env, methodName) { this._env = env; this._methodName = methodName; this._isExpectingNoCalls = false; this._expecteds = []; this._actuals = []; }; MethodCallTracker.prototype = { stubMethod() { if (this._originalMethod) { // Me...
if (env.runningProdBuild) { assert.ok(true, `calls to Ember.${methodName} disabled in production builds.`); return; } if (isExpectingNoCalls) { let actualMessages = []; for (i = 0; i < actuals.length; i++) { if (!actuals[i][1]) { actualMessages.push(actuals[i][0]...
{ return; }
conditional_block
method-call-tracker.js
import { checkTest } from './utils'; var MethodCallTracker = function(env, methodName) { this._env = env; this._methodName = methodName; this._isExpectingNoCalls = false; this._expecteds = []; this._actuals = []; }; MethodCallTracker.prototype = { stubMethod() { if (this._originalMethod) { // Me...
() { this.stubMethod(); this._isExpectingNoCalls = true; }, isExpectingNoCalls() { return this._isExpectingNoCalls; }, isExpectingCalls() { return !this._isExpectingNoCalls && this._expecteds.length; }, assert() { let { assert } = QUnit.config.current; let env = this._env; let...
expectNoCalls
identifier_name
method-call-tracker.js
import { checkTest } from './utils'; var MethodCallTracker = function(env, methodName) { this._env = env; this._methodName = methodName; this._isExpectingNoCalls = false; this._expecteds = []; this._actuals = []; }; MethodCallTracker.prototype = { stubMethod() { if (this._originalMethod) { // Me...
} } else { if (expected === actual[0]) { match = actual; break; } } } } if (!actual) { assert.ok(false, `Received no Ember.${methodName} calls at all, expecting: ${expected}`); } else if (match && !mat...
if (expected instanceof RegExp) { if (expected.test(actual[0])) { match = actual; break;
random_line_split
htmlfieldsetelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use crate::d...
match attr.local_name() { &local_name!("disabled") => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Fieldset was already disabled before. ...
Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation);
random_line_split
htmlfieldsetelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use crate::d...
// https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> DomRoot<ValidityState> { let window = window_from_node(self); ValidityState::new(&window, self.upcast()) } // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_getter!(Disabled,...
{ #[derive(JSTraceable, MallocSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { elem.downcast::<HTMLElement>() .map_or(false, HTMLElement::is_listed_element...
identifier_body
htmlfieldsetelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use crate::d...
; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { elem.downcast::<HTMLElement>() .map_or(false, HTMLElement::is_listed_element) } } let filter = Box::new(ElementsFilter); ...
ElementsFilter
identifier_name
htmlfieldsetelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::attr::Attr; use crate::dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use crate::d...
}, &local_name!("form") => { self.form_attribute_mutated(mutation); }, _ => {}, } } } impl FormControl for HTMLFieldSetElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_fo...
{ for field in fields { let el = field.downcast::<Element>().unwrap(); el.check_disabled_attribute(); el.check_ancestors_disabled_state_for_form_control(); } }
conditional_block
test_apdetail.py
# -*- coding: utf-8 -*- """UnitTests for airwaveapiclient.""" import os import unittest from airwaveapiclient import APDetail from airwaveapiclient.tests import test_utils class APDetailUnitTests(unittest.TestCase): """Class APDetailUnitTests. Unit test for APDetail. """ def setUp(self): ...
def test_radio_type(self): """Test radio_type.""" for radio in self.obj['radio']: if radio['radio_type'] == 'bgn': self.assertEqual(radio['radio_interface'], '2') if radio['radio_type'] == 'aN': self.assertEqual(radio['radio_interface'], '1')
def test_init(self): """Test init.""" self.assertNotEqual(self.obj, None)
random_line_split
test_apdetail.py
# -*- coding: utf-8 -*- """UnitTests for airwaveapiclient.""" import os import unittest from airwaveapiclient import APDetail from airwaveapiclient.tests import test_utils class APDetailUnitTests(unittest.TestCase): """Class APDetailUnitTests. Unit test for APDetail. """ def setUp(self): ...
(self): """Test radio_type.""" for radio in self.obj['radio']: if radio['radio_type'] == 'bgn': self.assertEqual(radio['radio_interface'], '2') if radio['radio_type'] == 'aN': self.assertEqual(radio['radio_interface'], '1')
test_radio_type
identifier_name