file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
decorators.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Function/method decorators that provide timeout and retry logic. """ import functools import itertools import sys from devil.android import device_erro...
try: if timeout_retry.CurrentTimeoutThreadGroup(): # Don't wrap if there's already an outer timeout thread. return impl() else: desc = '%s(%s)' % (f.__name__, ', '.join(itertools.chain( (str(a) for a in args), ('%s=%s' % (k, str(v)) for k, v in kwargs.iter...
@functools.wraps(f) def impl(): return f(*args, **kwargs)
random_line_split
decorators.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Function/method decorators that provide timeout and retry logic. """ import functools import itertools import sys from devil.android import device_erro...
(f, timeout_func, retries_func, pass_values=False): """ Wraps a funcion with timeout and retry handling logic. Args: f: The function to wrap. timeout_func: A callable that returns the timeout value. retries_func: A callable that returns the retries value. pass_values: If True, passes the values ret...
_TimeoutRetryWrapper
identifier_name
decorators.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Function/method decorators that provide timeout and retry logic. """ import functools import itertools import sys from devil.android import device_erro...
else: desc = '%s(%s)' % (f.__name__, ', '.join(itertools.chain( (str(a) for a in args), ('%s=%s' % (k, str(v)) for k, v in kwargs.iteritems())))) return timeout_retry.Run(impl, timeout, retries, desc=desc) except reraiser_thread.TimeoutError as e: raise device_er...
return impl()
conditional_block
decorators.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Function/method decorators that provide timeout and retry logic. """ import functools import itertools import sys from devil.android import device_erro...
def WithTimeoutAndRetriesFromInstance( default_timeout_name=DEFAULT_TIMEOUT_ATTR, default_retries_name=DEFAULT_RETRIES_ATTR, min_default_timeout=None): """Returns a decorator that handles timeouts and retries. The provided |default_timeout_name| and |default_retries_name| are used to get the defau...
"""Returns a decorator that handles timeouts and retries. The provided |default_timeout| and |default_retries| values are used only if timeout and retries values are not provided. Args: default_timeout: The number of seconds to wait for the decorated function to return. Only used if a '...
identifier_body
lib.rs
// Copyright 2015 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 session::Session; use lint::LintId; mod builtin; /// Tell the `LintStore` about all the built-in lints (the ones /// defined in this crate and the ones defined in /// `rustc::lint::builtin`). pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { macro_rules! add_builtin { ($...
pub use rustc::middle as middle; pub use rustc::session as session; pub use rustc::util as util;
random_line_split
lib.rs
// Copyright 2015 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 ...
{ macro_rules! add_builtin { ($sess:ident, $($name:ident),*,) => ( {$( store.register_pass($sess, false, box builtin::$name); )*} ) } macro_rules! add_builtin_with_new { ($sess:ident, $($name:ident),*,) => ( {$( ...
identifier_body
lib.rs
// Copyright 2015 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 ...
(store: &mut lint::LintStore, sess: Option<&Session>) { macro_rules! add_builtin { ($sess:ident, $($name:ident),*,) => ( {$( store.register_pass($sess, false, box builtin::$name); )*} ) } macro_rules! add_builtin_with_new { ($sess:iden...
register_builtins
identifier_name
test_uri.py
from __future__ import unicode_literals from httoop import URI def test_simple_uri_comparision(uri): u1 = URI(b'http://abc.com:80/~smith/home.html') u2 = URI(b'http://ABC.com/%7Esmith/home.html') u3 = URI(b'http://ABC.com:/%7esmith/home.html') u4 = URI(b'http://ABC.com:/%7esmith/./home.html') u5 = URI(b'http://...
assert bytes(URI(b'http://username@example.com')) == b'http://username@example.com' assert bytes(URI(b'http://username:password@example.com')) == b'http://username:password@example.com'
identifier_body
test_uri.py
from __future__ import unicode_literals from httoop import URI def test_simple_uri_comparision(uri): u1 = URI(b'http://abc.com:80/~smith/home.html') u2 = URI(b'http://ABC.com/%7Esmith/home.html') u3 = URI(b'http://ABC.com:/%7esmith/home.html') u4 = URI(b'http://ABC.com:/%7esmith/./home.html') u5 = URI(b'http://...
def test_request_uri_maxlength(): pass def test_request_uri_is_star(): pass def test_request_uri_containig_fragment(): pass def test_invalid_uri_scheme(): pass def test_invalid_port(): pass def test_normalized_uri_redirects(): pass def test_uri_composing_username_and_password(): assert bytes(URI(b'ht...
assert u1 == u5
random_line_split
test_uri.py
from __future__ import unicode_literals from httoop import URI def test_simple_uri_comparision(uri): u1 = URI(b'http://abc.com:80/~smith/home.html') u2 = URI(b'http://ABC.com/%7Esmith/home.html') u3 = URI(b'http://ABC.com:/%7esmith/home.html') u4 = URI(b'http://ABC.com:/%7esmith/./home.html') u5 = URI(b'http://...
(): pass def test_request_uri_containig_fragment(): pass def test_invalid_uri_scheme(): pass def test_invalid_port(): pass def test_normalized_uri_redirects(): pass def test_uri_composing_username_and_password(): assert bytes(URI(b'http://username@example.com')) == b'http://username@example.com' assert...
test_request_uri_is_star
identifier_name
the_test.rs
use std::env; use std::process; use std::sync::Arc; fn main() { log_ndc_env_logger::init(); let mut server = httpbis::ServerBuilder::new_plain(); server .service .set_service("/", Arc::new(httpbis_h2spec_test::Ok200)); server.set_port(8888); let _server = server.build().expect("ser...
.stderr(process::Stdio::inherit()) .spawn() .expect("spawn h2spec"); let exit_status = h2spec.wait().expect("h2spec wait"); assert!(exit_status.success(), "{}", exit_status); }
.stdin(process::Stdio::null()) .stdout(process::Stdio::inherit())
random_line_split
the_test.rs
use std::env; use std::process; use std::sync::Arc; fn
() { log_ndc_env_logger::init(); let mut server = httpbis::ServerBuilder::new_plain(); server .service .set_service("/", Arc::new(httpbis_h2spec_test::Ok200)); server.set_port(8888); let _server = server.build().expect("server.build()"); let mut h2spec = process::Command::new("...
main
identifier_name
the_test.rs
use std::env; use std::process; use std::sync::Arc; fn main()
{ log_ndc_env_logger::init(); let mut server = httpbis::ServerBuilder::new_plain(); server .service .set_service("/", Arc::new(httpbis_h2spec_test::Ok200)); server.set_port(8888); let _server = server.build().expect("server.build()"); let mut h2spec = process::Command::new("h2s...
identifier_body
reactNative.ts
import { trim } from 'ramda' import exitCodes from '../lib/exit-codes' import { IgniteToolbox, IgniteRNInstallResult } from '../types' // DEPRECATED: Please specify React Native version when invoking install // Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' }) const REACT_NATIVE_VERSION...
if (opts.useNpm) { rnOptions.push('--npm') } // react-native init const cmd = trim(`npx react-native init ${name} ${rnOptions.join(' ')}`) log('initializing react native') log(cmd) const withTemplate = reactNativeTemplate ? ` with ${print.colors.cyan(reactNativeTemplate)} template` : ''...
rnOptions.push('--skip-jest') }
conditional_block
reactNative.ts
import { trim } from 'ramda' import exitCodes from '../lib/exit-codes' import { IgniteToolbox, IgniteRNInstallResult } from '../types' // DEPRECATED: Please specify React Native version when invoking install // Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' }) const REACT_NATIVE_VERSION...
)}`, ) if (parameters.options.debug) spinner.stop() // ok, let's do this // react-native init takes about 20s to execute const stdioMode = parameters.options.debug ? 'inherit' : 'ignore' try { log('initializing react native project') log(`command: ${cmd}`) await system.e...
log(cmd) const withTemplate = reactNativeTemplate ? ` with ${print.colors.cyan(reactNativeTemplate)} template` : '' const spinner = print.spin( `adding ${print.colors.cyan('React Native ' + reactNativeVersion)}${withTemplate} ${print.colors.muted( '(30 seconds-ish)',
random_line_split
reactNative.ts
import { trim } from 'ramda' import exitCodes from '../lib/exit-codes' import { IgniteToolbox, IgniteRNInstallResult } from '../types' // DEPRECATED: Please specify React Native version when invoking install // Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' }) const REACT_NATIVE_VERSION...
odule.exports = attach
{ // fist-full o features const { parameters, print, system, filesystem, strings, ignite } = toolbox const { log } = ignite /** * Installs React Native. */ async function install( opts: { name?: string; version?: string; template?: string; skipJest?: boolean; useNpm?: boolean } = {}, ): Promise<I...
identifier_body
reactNative.ts
import { trim } from 'ramda' import exitCodes from '../lib/exit-codes' import { IgniteToolbox, IgniteRNInstallResult } from '../types' // DEPRECATED: Please specify React Native version when invoking install // Example: const rnInstall = await reactNative.install({ name, version: '0.42.0' }) const REACT_NATIVE_VERSION...
( opts: { name?: string; version?: string; template?: string; skipJest?: boolean; useNpm?: boolean } = {}, ): Promise<IgniteRNInstallResult> { // grab the name & version const name = opts.name || parameters.first let reactNativeVersion = opts.version || parameters.options['react-native-version'] ...
install
identifier_name
mod.rs
mod compile_mx; pub mod cpp; pub mod paths; mod template; use crate::error::Result; use crate::generate::cpp::modeler::MxModeler; use crate::generate::paths::Paths; use crate::model::create::Create; use crate::model::creator::Creator; use crate::model::post_process::PostProcess; use crate::model::transform::Transform;...
(args: GenArgs) -> Result<()> { let xsd = read_to_string(&args.paths.xsd_3_0).unwrap(); let doc = exile::parse(xsd.as_str()).unwrap(); let new_xsd = Xsd::load(&args.paths.xsd_3_0)?; let transforms: Vec<Box<dyn Transform>> = vec![Box::new(MxModeler::new())]; let creates: Vec<Box<dyn Create>> = vec![B...
run
identifier_name
mod.rs
mod compile_mx; pub mod cpp; pub mod paths; mod template; use crate::error::Result; use crate::generate::cpp::modeler::MxModeler; use crate::generate::paths::Paths; use crate::model::create::Create; use crate::model::creator::Creator; use crate::model::post_process::PostProcess; use crate::model::transform::Transform;...
} /// Generate `mx::core` in C++ pub fn run(args: GenArgs) -> Result<()> { let xsd = read_to_string(&args.paths.xsd_3_0).unwrap(); let doc = exile::parse(xsd.as_str()).unwrap(); let new_xsd = Xsd::load(&args.paths.xsd_3_0)?; let transforms: Vec<Box<dyn Transform>> = vec![Box::new(MxModeler::new())]; ...
{ Self { paths: Paths::default(), } }
identifier_body
mod.rs
mod compile_mx; pub mod cpp; pub mod paths; mod template; use crate::error::Result; use crate::generate::cpp::modeler::MxModeler; use crate::generate::paths::Paths; use crate::model::create::Create; use crate::model::creator::Creator; use crate::model::post_process::PostProcess; use crate::model::transform::Transform;...
let creates: Vec<Box<dyn Create>> = vec![Box::new(MxModeler::new())]; let post_processors: Vec<Box<dyn PostProcess>> = vec![Box::new(MxModeler::new())]; let creator = Creator::new_with_default(Some(transforms), Some(creates), Some(post_processors)); let models = creator.create(&new_xsd)?; let cpp_wr...
random_line_split
rclxls.py
#!/usr/bin/env python2 # Extractor for Excel files. # Mso-dumper is not compatible with Python3. We use sys.executable to # start the actual extractor, so we need to use python2 too. import rclexecm import rclexec1 import xlsxmltocsv import re import sys import os import xml.sax class XLSProcessData: def __init_...
proto = rclexecm.RclExecM() filter = XLSFilter(proto) extract = rclexec1.Executor(proto, filter) rclexecm.main(proto, extract)
if __name__ == '__main__': if not rclexecm.which("xls-dump.py"): print("RECFILTERROR HELPERNOTFOUND ppt-dump.py") sys.exit(1)
random_line_split
rclxls.py
#!/usr/bin/env python2 # Extractor for Excel files. # Mso-dumper is not compatible with Python3. We use sys.executable to # start the actual extractor, so we need to use python2 too. import rclexecm import rclexec1 import xlsxmltocsv import re import sys import os import xml.sax class XLSProcessData: def __init_...
(self, line): if self.ishtml: self.out += line + "\n" return if not self.gotdata: self.out += '''<html><head>''' + \ '''<meta http-equiv="Content-Type" ''' + \ '''content="text/html;charset=UTF-8">''' + \ ...
takeLine
identifier_name
rclxls.py
#!/usr/bin/env python2 # Extractor for Excel files. # Mso-dumper is not compatible with Python3. We use sys.executable to # start the actual extractor, so we need to use python2 too. import rclexecm import rclexec1 import xlsxmltocsv import re import sys import os import xml.sax class XLSProcessData: def __init_...
if __name__ == '__main__': if not rclexecm.which("xls-dump.py"): print("RECFILTERROR HELPERNOTFOUND ppt-dump.py") sys.exit(1) proto = rclexecm.RclExecM() filter = XLSFilter(proto) extract = rclexec1.Executor(proto, filter) rclexecm.main(proto, extract)
def __init__(self, em): self.em = em self.ntry = 0 def reset(self): self.ntry = 0 pass def getCmd(self, fn): if self.ntry: return ([], None) self.ntry = 1 # Some HTML files masquerade as XLS try: data = open(fn...
identifier_body
rclxls.py
#!/usr/bin/env python2 # Extractor for Excel files. # Mso-dumper is not compatible with Python3. We use sys.executable to # start the actual extractor, so we need to use python2 too. import rclexecm import rclexec1 import xlsxmltocsv import re import sys import os import xml.sax class XLSProcessData: def __init_...
else: return ([], None) if __name__ == '__main__': if not rclexecm.which("xls-dump.py"): print("RECFILTERROR HELPERNOTFOUND ppt-dump.py") sys.exit(1) proto = rclexecm.RclExecM() filter = XLSFilter(proto) extract = rclexec1.Executor(proto, filter) rclexecm.main(p...
return ([sys.executable, cmd, "--dump-mode=canonical-xml", \ "--utf-8", "--catch"], XLSProcessData(self.em), rclexec1.Executor.opt_ignxval)
conditional_block
schema.js
import should from 'should'; import Schema from '../../src/schema';
const SIMPEL_OBJECT = { type: 'object', properties: { name: { type: 'string' } } }; describe('Schema', () => { describe('#getType', () => { it('should return string type for child', () => { const schema = new Schema(SIMPEL_OBJECT); schema.getType('name').should.equal('string'); }); })...
random_line_split
test_anonymous_epic.py
""" Functional test Anonymous Epic Storyboard is defined within the comments of the program itself """ import unittest from flask import url_for from biblib.views.http_errors import NO_PERMISSION_ERROR from biblib.tests.stubdata.stub_data import UserShop, LibraryShop from biblib.tests.base import TestCaseDatabase, M...
self.assertEqual(1, len(end_points)) self.assertEqual('/libraries/<string:library>', end_points[0]) if __name__ == '__main__': unittest.main(verbosity=2)
if len(response.json[end_point]['scopes']) == 0: end_points.append(end_point)
random_line_split
test_anonymous_epic.py
""" Functional test Anonymous Epic Storyboard is defined within the comments of the program itself """ import unittest from flask import url_for from biblib.views.http_errors import NO_PERMISSION_ERROR from biblib.tests.stubdata.stub_data import UserShop, LibraryShop from biblib.tests.base import TestCaseDatabase, M...
if __name__ == '__main__': unittest.main(verbosity=2)
""" Base class used to test the Big Share Admin Epic """ def test_anonymous_epic(self): """ Carries out the epic 'Anonymous', where a user tries to access a private library and also a public library. The user also (artificial) tries to access any other endpoints that do not ...
identifier_body
test_anonymous_epic.py
""" Functional test Anonymous Epic Storyboard is defined within the comments of the program itself """ import unittest from flask import url_for from biblib.views.http_errors import NO_PERMISSION_ERROR from biblib.tests.stubdata.stub_data import UserShop, LibraryShop from biblib.tests.base import TestCaseDatabase, M...
(self): """ Separately test the number of scopes that are scopeless. This will only fail during staging when the scopes are all set to be open. In the production system, there is only once end point that will be scopeless. """ response = self.client.get('/resources') ...
test_scopes
identifier_name
test_anonymous_epic.py
""" Functional test Anonymous Epic Storyboard is defined within the comments of the program itself """ import unittest from flask import url_for from biblib.views.http_errors import NO_PERMISSION_ERROR from biblib.tests.stubdata.stub_data import UserShop, LibraryShop from biblib.tests.base import TestCaseDatabase, M...
unittest.main(verbosity=2)
conditional_block
cdgdec.rs
// Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com> // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, ...
() { init(); let pipeline = gst::Pipeline::new(Some("cdgdec-test")); let input_path = { let mut r = PathBuf::new(); r.push(env!("CARGO_MANIFEST_DIR")); r.push("tests"); r.push("BrotherJohn"); r.set_extension("cdg"); r }; // Ensure we are in push mod...
test_cdgdec
identifier_name
cdgdec.rs
// Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com> // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, ...
child_proxy .set_child_property("real-filesrc::blocksize", &blocksize) .expect("failed to set 'blocksize' property"); } let parse = gst::ElementFactory::make("cdgparse", None).unwrap(); let dec = gst::ElementFactory::make("cdgdec", None).unwrap(); let sink = gst::Element...
.expect("failed to set 'num-buffers' property"); let blocksize: u32 = 24; // One CDG instruction
random_line_split
cdgdec.rs
// Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com> // // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, ...
#[test] fn test_cdgdec() { init(); let pipeline = gst::Pipeline::new(Some("cdgdec-test")); let input_path = { let mut r = PathBuf::new(); r.push(env!("CARGO_MANIFEST_DIR")); r.push("tests"); r.push("BrotherJohn"); r.set_extension("cdg"); r }; // E...
{ use std::sync::Once; static INIT: Once = Once::new(); INIT.call_once(|| { gst::init().unwrap(); gstcdg::plugin_register_static().expect("cdgdec tests"); }); }
identifier_body
a.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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 ap...
{ let address: Ipv4Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv4 address".to_string()))) .and_then(|s| Ipv4Addr::from_str(s).map_err(Into::into))?; Ok(address) }
identifier_body
a.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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 ap...
use std::net::Ipv4Addr; use std::str::FromStr; use crate::error::*; /// Parse the RData from a set of Tokens pub fn parse<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv4Addr> { let address: Ipv4Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken(...
//! Parser for A text form
random_line_split
a.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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 ap...
<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv4Addr> { let address: Ipv4Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv4 address".to_string()))) .and_then(|s| Ipv4Addr::from_str(s).map_err(Into::into))?; Ok(address) }
parse
identifier_name
rendering.py
import maya.cmds;mc = maya.cmds import pymel.core;pm = pymel.core from pytaya.core.general import listForNone from pytd.util.logutils import logMsg from pytd.util.sysutils import grouper def fileNodesFromObjects(oObjList): return fileNodesFromShaders(shadersFromObjects(oObjList)) def fileNodesFromShaders(oMatL...
def duplicateShadersPerObject(oMatList): oNewMatList = [] for oMat in oMatList: oShadEngList = oMat.outputs(type="shadingEngine") if not oShadEngList: continue oShadEng = oShadEngList[0] oShadEngMemberList = oShadEng.members() oMemberByGeoObjDct = {} ...
logMsg("Processing {0}".format(repr(oMat))) try: colorAttr = oMat.attr("color") except pm.MayaAttributeError: logMsg("\tNo color attribute found.") continue try: oSG = oMat.shadingGroups()[0] except IndexError: print "\tNo Sha...
conditional_block
rendering.py
import maya.cmds;mc = maya.cmds import pymel.core;pm = pymel.core from pytaya.core.general import listForNone from pytd.util.logutils import logMsg from pytd.util.sysutils import grouper def fileNodesFromObjects(oObjList): return fileNodesFromShaders(shadersFromObjects(oObjList)) def fileNodesFromShaders(oMatLi...
button=['Ok', 'Cancel'], defaultButton='Cancel', cancelButton='Cancel', dismissString='Cancel') if result == 'Cancel': return else : for oSourceXfm, oTargetXfm in tra...
# if notFoundList: # pm.sets(oSet, addElement=notFoundList) result = pm.confirmDialog(title='Transfer Uvs', message='Found {0}/{1} mismatches :'.format(len(notFoundList), len(transferList)),
random_line_split
rendering.py
import maya.cmds;mc = maya.cmds import pymel.core;pm = pymel.core from pytaya.core.general import listForNone from pytd.util.logutils import logMsg from pytd.util.sysutils import grouper def fileNodesFromObjects(oObjList): return fileNodesFromShaders(shadersFromObjects(oObjList)) def fileNodesFromShaders(oMatL...
def shadersFromObjects(objList, connectedTo=""): sAttrName = connectedTo if not objList: return [] oMatSgList = shadingGroupsFromObjects(objList) oMatList = [] for oMatSg in oMatSgList: sName = oMatSg.attr(sAttrName).name() if connectedTo else oMatSg.name() oMatList.ext...
oFileNodeList = set() for oMat in oMatList: oFileNodeList.update(oMat.listHistory(type="file")) return list(oFileNodeList)
identifier_body
rendering.py
import maya.cmds;mc = maya.cmds import pymel.core;pm = pymel.core from pytaya.core.general import listForNone from pytd.util.logutils import logMsg from pytd.util.sysutils import grouper def fileNodesFromObjects(oObjList): return fileNodesFromShaders(shadersFromObjects(oObjList)) def fileNodesFromShaders(oMatL...
(oMeshList, sNamespaceToMatch , **kwargs): bForce = kwargs.get("force", False) oShadingGroupMembersDct = {} oMatNotConformList = [] for oShape in oMeshList: # print "\nfor shape: ", oShape oMatSGList = shadingGroupsForObject(oShape) for oMatSG in oMatSGList: # print ...
conformShadingNetworkToNamespace
identifier_name
lower_caser.rs
use super::{Token, TokenFilter, TokenStream}; use crate::tokenizer::BoxTokenStream; use std::mem; impl TokenFilter for LowerCaser { fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> { BoxTokenStream::from(LowerCaserTokenStream { tail: token_stream, buff...
(&mut self) -> bool { if !self.tail.advance() { return false; } if self.token_mut().text.is_ascii() { // fast track for ascii. self.token_mut().text.make_ascii_lowercase(); } else { to_lowercase_unicode(&mut self.tail.token_mut().text, &mut...
advance
identifier_name
lower_caser.rs
use super::{Token, TokenFilter, TokenStream}; use crate::tokenizer::BoxTokenStream; use std::mem; impl TokenFilter for LowerCaser { fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> { BoxTokenStream::from(LowerCaserTokenStream { tail: token_stream, buff...
} true } fn token(&self) -> &Token { self.tail.token() } fn token_mut(&mut self) -> &mut Token { self.tail.token_mut() } } #[cfg(test)] mod tests { use crate::tokenizer::tests::assert_token; use crate::tokenizer::{LowerCaser, SimpleTokenizer, TextAnalyzer, ...
to_lowercase_unicode(&mut self.tail.token_mut().text, &mut self.buffer); mem::swap(&mut self.tail.token_mut().text, &mut self.buffer);
random_line_split
lower_caser.rs
use super::{Token, TokenFilter, TokenStream}; use crate::tokenizer::BoxTokenStream; use std::mem; impl TokenFilter for LowerCaser { fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> { BoxTokenStream::from(LowerCaserTokenStream { tail: token_stream, buff...
} #[cfg(test)] mod tests { use crate::tokenizer::tests::assert_token; use crate::tokenizer::{LowerCaser, SimpleTokenizer, TextAnalyzer, Token}; #[test] fn test_to_lower_case() { let tokens = token_stream_helper("Tree"); assert_eq!(tokens.len(), 1); assert_token(&tokens[0], 0, ...
{ self.tail.token_mut() }
identifier_body
lower_caser.rs
use super::{Token, TokenFilter, TokenStream}; use crate::tokenizer::BoxTokenStream; use std::mem; impl TokenFilter for LowerCaser { fn transform<'a>(&self, token_stream: BoxTokenStream<'a>) -> BoxTokenStream<'a> { BoxTokenStream::from(LowerCaserTokenStream { tail: token_stream, buff...
true } fn token(&self) -> &Token { self.tail.token() } fn token_mut(&mut self) -> &mut Token { self.tail.token_mut() } } #[cfg(test)] mod tests { use crate::tokenizer::tests::assert_token; use crate::tokenizer::{LowerCaser, SimpleTokenizer, TextAnalyzer, Token}; ...
{ to_lowercase_unicode(&mut self.tail.token_mut().text, &mut self.buffer); mem::swap(&mut self.tail.token_mut().text, &mut self.buffer); }
conditional_block
findbestmatch.py
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or with...
# return the names - and make sure there are no duplicates or empty values cleaned_names = set(names) - set([None, ""]) return cleaned_names #==================================================================== class UniqueDict(dict): """A dictionary subclass that handles making its keys ...
names.extend(non_text_names)
conditional_block
findbestmatch.py
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or with...
#==================================================================== def build_unique_dict(controls): """Build the disambiguated list of controls Separated out to a different function so that we can get the control identifiers for printing. """ name_control_map = UniqueDict() #...
"""A dictionary subclass that handles making its keys unique""" def __setitem__(self, text, item): """Set an item of the dictionary""" # this text is already in the map # so we need to make it unique if text in self: # find next unique text after text1 ...
identifier_body
findbestmatch.py
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or with...
# list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of pywinauto nor the ...
# * Redistributions of source code must retain the above copyright notice, this
random_line_split
findbestmatch.py
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or with...
(text): """Clean out non characters from the string and return it""" # remove anything after the first tab return _after_tab.sub("", text) def _cut_at_eol(text): """Clean out non characters from the string and return it""" # remove anything after the first EOL return _after_eol.sub(""...
_cut_at_tab
identifier_name
pages.js
'use strict'; var express = require('express'); var router = express.Router(); var models = require('../../models'); /* GET list pages */ router.get('/', function(req, res, next) { models.Page.findAll({ include: [models.NavigationItem] }).then(function(pages) { res.render('admin/pages/index', { titl...
res.render('admin/pages/view', {title: page.title, page:page}); }); }); /* POST create page */ router.post('/', function(req, res, next) { var data = { title: req.body.title, url: req.body.url, content: req.body.content || null, enabled: !!req.body.enabled }; models.Page.create(data).the...
{ return next(); }
conditional_block
pages.js
'use strict'; var express = require('express'); var router = express.Router(); var models = require('../../models'); /* GET list pages */ router.get('/', function(req, res, next) { models.Page.findAll({ include: [models.NavigationItem] }).then(function(pages) { res.render('admin/pages/index', { titl...
router.post('/', function(req, res, next) { var data = { title: req.body.title, url: req.body.url, content: req.body.content || null, enabled: !!req.body.enabled }; models.Page.create(data).then(function(page) { req.flash('success', 'The page has been created!'); res.redirect('/admin/page...
/* POST create page */
random_line_split
example_tasks.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
# under the License. """ Example Airflow DAG that creates, gets, lists, updates, purges, pauses, resumes and deletes Queues and creates, gets, lists, runs and deletes Tasks in the Google Cloud Tasks service in the Google Cloud. """ import os from datetime import datetime, timedelta from google.api_core.retry import R...
# "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
random_line_split
simple_executor.rs
use crate::task::Task; use alloc::collections::VecDeque; use core::task::{RawWaker, RawWakerVTable, Waker}; pub struct SimpleExecutor { task_queue: VecDeque<Task>,
task_queue: VecDeque::new(), } } pub fn spawn(&mut self, task: Task) { self.task_queue.push_back(task) } } fn dummy_raw_waker() -> RawWaker { fn no_op(_: *const ()) {} fn clone(_: *const ()) -> RawWaker { dummy_raw_waker() } let vtable = &RawWakerVTable::new(clone, no_op, no_o...
} impl SimpleExecutor { pub fn new() -> SimpleExecutor { SimpleExecutor {
random_line_split
simple_executor.rs
use crate::task::Task; use alloc::collections::VecDeque; use core::task::{RawWaker, RawWakerVTable, Waker}; pub struct SimpleExecutor { task_queue: VecDeque<Task>, } impl SimpleExecutor { pub fn new() -> SimpleExecutor { SimpleExecutor { task_queue: VecDeque::new(), } } pu...
() -> RawWaker { fn no_op(_: *const ()) {} fn clone(_: *const ()) -> RawWaker { dummy_raw_waker() } let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op); RawWaker::new(0 as *const (), vtable) } fn dummy_waker() -> Waker { unsafe { Waker::from_raw(dummy_raw_waker()) } }
dummy_raw_waker
identifier_name
simple_executor.rs
use crate::task::Task; use alloc::collections::VecDeque; use core::task::{RawWaker, RawWakerVTable, Waker}; pub struct SimpleExecutor { task_queue: VecDeque<Task>, } impl SimpleExecutor { pub fn new() -> SimpleExecutor
pub fn spawn(&mut self, task: Task) { self.task_queue.push_back(task) } } fn dummy_raw_waker() -> RawWaker { fn no_op(_: *const ()) {} fn clone(_: *const ()) -> RawWaker { dummy_raw_waker() } let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op); RawWaker::new(0 as *const (), vtable) } ...
{ SimpleExecutor { task_queue: VecDeque::new(), } }
identifier_body
index.d.ts
// Type definitions for Angular xEditable (angular.xeditable module) 0.2 // Project: https://vitalets.github.io/angular-xeditable/ // Definitions by: Joao Monteiro <https://github.com/jpmnteiro> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as angular from "angu...
}
} }
random_line_split
utils.py
from django.core.cache import cache from django.conf import settings from django.template.loader import render_to_string from tendenci.apps.navs.cache import NAV_PRE_KEY def cache_nav(nav, show_title=False): """ Caches a nav's rendered html code """ keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(n...
""" Clear nav cache """ keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(nav.id)] key = '.'.join(keys) cache.delete(key)
identifier_body
utils.py
from django.core.cache import cache from django.conf import settings from django.template.loader import render_to_string from tendenci.apps.navs.cache import NAV_PRE_KEY def
(nav, show_title=False): """ Caches a nav's rendered html code """ keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(nav.id)] key = '.'.join(keys) value = render_to_string("navs/render_nav.html", {'nav':nav, "show_title": show_title}) cache.set(key, value, 432000) #5 days return value d...
cache_nav
identifier_name
utils.py
from django.core.cache import cache from django.conf import settings from django.template.loader import render_to_string from tendenci.apps.navs.cache import NAV_PRE_KEY def cache_nav(nav, show_title=False): """ Caches a nav's rendered html code """ keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(n...
cache.delete(key)
random_line_split
test_base.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (...
parameters["file_resources-next_form_id"] = str(len(resources or [])) for i, resources_pair in enumerate(resources or []): type, path = resources_pair parameters["file_resources-%d-type" % i] = str(type) parameters["file_resources-%d-path" % i] = str(path) parameters["file_resources-%d-_exists" % i...
key, value = settings_pair parameters["settings-%d-key" % i] = str(key) parameters["settings-%d-value" % i] = str(value) parameters["settings-%d-_exists" % i] = 'True'
conditional_block
test_base.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (...
def wait_for_query_to_finish(client, response, max=60.0): # Take a async API execute_query() response in input start = time.time() sleep_time = 0.05 if is_finished(response): # aka Has error at submission return response content = json.loads(response.content) watch_url = content['watch_url'] r...
HIVE_CONF = cluster.hadoop_conf_dir finish = ( beeswax.conf.HIVE_SERVER_HOST.set_for_testing(get_localhost_name()), beeswax.conf.HIVE_SERVER_PORT.set_for_testing(HIVE_SERVER_TEST_PORT), beeswax.conf.HIVE_SERVER_BIN.set_for_testing(get_run_root('ext/hive/hive') + '/bin/hiveserver2'), beeswax.conf.H...
identifier_body
test_base.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (...
parameters["functions-next_form_id"] = str(len(udfs or [])) for i, udf_pair in enumerate(udfs or []): name, klass = udf_pair parameters["functions-%d-name" % i] = name parameters["functions-%d-class_name" % i] = klass parameters["functions-%d-_exists" % i] = 'True' parameters["settings-next_form_...
if name: parameters['saveform-name'] = name if desc: parameters['saveform-desc'] = desc
random_line_split
test_base.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (...
(cls): """ Install the common test tables (only once) """ global _INITIALIZED if _INITIALIZED: return make_query(cls.client, 'CREATE DATABASE IF NOT EXISTS %(db)s' % {'db': cls.db_name}, wait=True) make_query(cls.client, 'CREATE DATABASE IF NOT EXISTS %(db)s_other' % {'db': cls.db_nam...
init_beeswax_db
identifier_name
input.type.spec.ts
import { FormlyFieldConfig } from '@ngx-formly/core'; import { createFieldComponent, ɵCustomEvent } from '@ngx-formly/core/testing'; import { FormlyMatInputModule } from '@ngx-formly/material/input'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; const renderComponent = (field: FormlyFiel...
describe('ui-material: Input Type', () => { it('should render input type', () => { const { query } = renderComponent({ key: 'name', type: 'input', }); expect(query('formly-wrapper-mat-form-field')).not.toBeNull(); const { attributes } = query('input[type="text"]'); expect(attributes)...
random_line_split
xhr_impl.js
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(funct...
MessageBasedXHRImpl.prototype.start = function () { var broker = this._brokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL); broker.registerMethod("get", [serializer_1.PRIMITIVE], bind_1.bind(this._xhr.get, this._xhr), serializer_1.PRIMITIVE); }; MessageBasedXHRImpl = __decorate([...
{ this._brokerFactory = _brokerFactory; this._xhr = _xhr; }
identifier_body
xhr_impl.js
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(funct...
(_brokerFactory, _xhr) { this._brokerFactory = _brokerFactory; this._xhr = _xhr; } MessageBasedXHRImpl.prototype.start = function () { var broker = this._brokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL); broker.registerMethod("get", [serializer_1.PRIMITIVE], bind_1....
MessageBasedXHRImpl
identifier_name
xhr_impl.js
'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(funct...
exports.MessageBasedXHRImpl = MessageBasedXHRImpl; //# sourceMappingURL=xhr_impl.js.map
__metadata('design:paramtypes', [service_message_broker_1.ServiceMessageBrokerFactory, xhr_1.XHR]) ], MessageBasedXHRImpl); return MessageBasedXHRImpl; })();
random_line_split
lib.rs
// Copyright 2015 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 krate = match parse_input(input, &parse_session) { Ok(krate) => krate, Err(diagnostic) => { if let Some(mut diagnostic) = diagnostic { diagnostic.emit(); } summary.add_parsing_error(); return Ok((summary, FileMap::new(), FormatRepo...
let main_file = match input { Input::File(ref file) => file.clone(), Input::Text(..) => PathBuf::from("stdin"), };
random_line_split
lib.rs
// Copyright 2015 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 ...
(&self) -> bool { self.warning_count() > 0 } } impl fmt::Display for FormatReport { // Prints all the formatting errors. fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { for (file, errors) in &self.file_error_map { for error in errors { try!(wr...
has_warnings
identifier_name
lib.rs
// Copyright 2015 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 ...
} impl Spanned for ast::Ty { fn span(&self) -> Span { self.span } } impl Spanned for ast::Arg { fn span(&self) -> Span { if items::is_named_arg(self) { mk_sp(self.pat.span.lo, self.ty.span.hi) } else { self.ty.span } } } #[derive(Copy, Clone, D...
{ self.span }
identifier_body
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. use app_units::Au; use byteorder::{BigEndian, ByteOrder}; use c...
fn template(&self) -> Arc<FontTemplateData> { self.font_data.clone() } fn family_name(&self) -> Option<String> { Some(self.ctfont.family_name()) } fn face_name(&self) -> Option<String> { Some(self.ctfont.face_name()) } fn style(&self) -> FontStyle { use s...
{ let size = match pt_size { Some(s) => s.to_f64_px(), None => 0.0, }; match template.ctfont(size) { Some(ref ctfont) => { let mut handle = FontHandle { font_data: template.clone(), ctfont: ctfont.clone_w...
identifier_body
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. use app_units::Au; use byteorder::{BigEndian, ByteOrder}; use c...
// see also: https://bugreports.qt-project.org/browse/QTBUG-13364 underline_offset: au_from_pt(self.ctfont.underline_position() as f64), strikeout_size: Au(0), // FIXME(Issue #942) strikeout_offset: Au(0), // FIXME(Issue #942) leading: au_from_pt(leading), ...
// see also: https://bugs.webkit.org/show_bug.cgi?id=16768
random_line_split
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. use app_units::Au; use byteorder::{BigEndian, ByteOrder}; use c...
(pt: f64) -> Au { Au::from_f64_px(pt_to_px(pt)) } impl FontTable { pub fn wrap(data: CFData) -> FontTable { FontTable { data: data } } } impl FontTableMethods for FontTable { fn buffer(&self) -> &[u8] { self.data.bytes() } } #[derive(Debug)] pub struct FontHandle { font_data: ...
au_from_pt
identifier_name
PostActionButton.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from 'react-bootstrap/lib/Button'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import { post } from '../../api'; class PostActionButton extends Component { static propTypes = { bsStyle: PropTypes.string.isRequ...
onClick = () => { this.setState({ isWorking: true }); const { body, action, onSuccess, onError } = this.props; post(action, body).then(() => { this.setState({ isWorking: false }); onSuccess(); }, (err) => { console.error(err); onError(err); }); }; render() { co...
{ super(props); this.state = { isWorking: false }; }
identifier_body
PostActionButton.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from 'react-bootstrap/lib/Button'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import { post } from '../../api'; class PostActionButton extends Component { static propTypes = { bsStyle: PropTypes.string.isRequ...
() { const { isWorking } = this.state; const { hideContentOnAction, bsStyle, children } = this.props; const renderChildren = !isWorking || (isWorking && !hideContentOnAction); return ( <Button onClick={this.onClick} bsStyle={bsStyle}> {isWorking && <Glyphicon glyph="refresh" classNa...
render
identifier_name
PostActionButton.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from 'react-bootstrap/lib/Button'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import { post } from '../../api'; class PostActionButton extends Component { static propTypes = { bsStyle: PropTypes.string.isRequ...
this.setState({ isWorking: true }); const { body, action, onSuccess, onError } = this.props; post(action, body).then(() => { this.setState({ isWorking: false }); onSuccess(); }, (err) => { console.error(err); onError(err); }); }; render() { const { isWorking } = th...
super(props); this.state = { isWorking: false }; } onClick = () => {
random_line_split
chrome_driver_extension.ts
import {bind, Binding} from 'angular2/src/core/di'; import {ListWrapper, StringMapWrapper, StringMap} from 'angular2/src/core/facade/collection'; import { Json, isPresent, isBlank, RegExpWrapper, StringWrapper, BaseException, NumberWrapper } from 'angular2/src/core/facade/lang'; import {WebDriverExtensio...
gc() { return this._driver.executeScript('window.gc()'); } timeBegin(name: string): Promise<any> { return this._driver.executeScript(`console.time('${name}');`); } timeEnd(name: string, restartName: string = null): Promise<any> { var script = `console.timeEnd('${name}');`; if (isPresent(restartN...
{ if (isBlank(userAgent)) { return -1; } var v = StringWrapper.split(userAgent, /Chrom(e|ium)\//g)[2]; if (isBlank(v)) { return -1; } v = StringWrapper.split(v, /\./g)[0]; if (isBlank(v)) { return -1; } return NumberWrapper.parseInt(v, 10); }
identifier_body
chrome_driver_extension.ts
import {bind, Binding} from 'angular2/src/core/di'; import {ListWrapper, StringMapWrapper, StringMap} from 'angular2/src/core/facade/collection'; import { Json, isPresent, isBlank, RegExpWrapper, StringWrapper, BaseException, NumberWrapper } from 'angular2/src/core/facade/lang'; import {WebDriverExtensio...
else if (this._isEvent(categories, name, ['v8'], 'majorGC') && StringWrapper.equals(ph, 'B')) { majorGCPids[pid] = true; } return null; // nothing useful in this event } private _processAsPostChrome44Event(event, categories) { var name = event['name']; var args = event['args'...
{ var normArgs = { 'usedHeapSize': isPresent(args['usedHeapSizeAfter']) ? args['usedHeapSizeAfter'] : args['usedHeapSizeBefore'] }; if (StringWrapper.equals(ph, 'E')) { normArgs['majorGc'] = isPresent(majorGCPids[pid]) && m...
conditional_block
chrome_driver_extension.ts
import {bind, Binding} from 'angular2/src/core/di'; import {ListWrapper, StringMapWrapper, StringMap} from 'angular2/src/core/facade/collection'; import { Json, isPresent, isBlank, RegExpWrapper, StringWrapper, BaseException, NumberWrapper } from 'angular2/src/core/facade/lang'; import {WebDriverExtensio...
} var v = StringWrapper.split(userAgent, /Chrom(e|ium)\//g)[2]; if (isBlank(v)) { return -1; } v = StringWrapper.split(v, /\./g)[0]; if (isBlank(v)) { return -1; } return NumberWrapper.parseInt(v, 10); } gc() { return this._driver.executeScript('window.gc()'); } timeB...
} private _parseChromeVersion(userAgent: string): number { if (isBlank(userAgent)) { return -1;
random_line_split
chrome_driver_extension.ts
import {bind, Binding} from 'angular2/src/core/di'; import {ListWrapper, StringMapWrapper, StringMap} from 'angular2/src/core/facade/collection'; import { Json, isPresent, isBlank, RegExpWrapper, StringWrapper, BaseException, NumberWrapper } from 'angular2/src/core/facade/lang'; import {WebDriverExtensio...
(capabilities: StringMap<string, any>): boolean { return this._majorChromeVersion != -1 && StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'chrome'); } } function normalizeEvent(chromeEvent: StringMap<string, any>, data: StringMap<string, any>): StringMap<string, any> { var ph = ...
supports
identifier_name
lineNumbers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
let lineIndex = lineNumber - startLineNumber; if (lineIndex < 0 || lineIndex >= this._renderResult.length) { return ''; } return this._renderResult[lineIndex]; } } // theming registerThemingParticipant((theme, collector) => { const lineNumbers = theme.getColor(editorLineNumbers); if (lineNumbers) { c...
{ return ''; }
conditional_block
lineNumbers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} let modelLineNumber = modelPosition.lineNumber; if (this._renderCustomLineNumbers) { return this._renderCustomLineNumbers(modelLineNumber); } if (this._renderLineNumbers === RenderLineNumbersType.Relative) { let diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber); if (diff...
const modelPosition = this._context.model.coordinatesConverter.convertViewPositionToModelPosition(new Position(viewLineNumber, 1)); if (modelPosition.column !== 1) { return '';
random_line_split
lineNumbers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean { return true; } public onLinesDeleted(e: viewEvents.ViewLinesDeletedEvent): boolean { return true; } public onLinesInserted(e: viewEvents.ViewLinesInsertedEvent): boolean { return true; } public onScrollChanged(e: viewEvents.ViewScrollCh...
{ return true; }
identifier_body
lineNumbers.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
extends DynamicViewOverlay { public static readonly CLASS_NAME = 'line-numbers'; private _context: ViewContext; private _lineHeight: number; private _renderLineNumbers: RenderLineNumbersType; private _renderCustomLineNumbers: ((lineNumber: number) => string) | null; private _lineNumbersLeft: number; private ...
LineNumbersOverlay
identifier_name
__init__.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as
# WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 5...
# published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but
random_line_split
main.rs
// Copyright 2017 Google Inc. 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 applicable...
break; } } } } fn main() { let (mut worker, tx, rx) = Worker::create(1024); /* let module = Box::new(modules::ConstCtrl::new(440.0f32.log2())); worker.handle_node(Node::create(module, 1, [], [])); let module = Box::new(modules::Sin::new(44_100.0)); worke...
self.cur_note = if on { Some(midi_num) } else { None } } i += 3; } else {
random_line_split
main.rs
// Copyright 2017 Google Inc. 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 applicable...
(&self, msg: Message) { self.tx.send(msg); } fn set_ctrl_const(&mut self, value: u8, lo: f32, hi: f32, ix: usize, ts: u64) { let value = lo + value as f32 * (1.0/127.0) * (hi - lo); let param = SetParam { ix: ix, param_ix: 0, val: value, t...
send
identifier_name
main.rs
// Copyright 2017 Google Inc. 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 applicable...
else if data[i] == 0x90 || data[i] == 0x80 { let midi_num = data[i + 1]; let velocity = data[i + 2]; let on = data[i] == 0x90 && velocity > 0; if on || self.cur_note == Some(midi_num) { self.send_note(vec![5, 7], midi_num as f32, veloc...
{ let controller = data[i + 1]; let value = data[i + 2]; match controller { 1 => self.set_ctrl_const(value, 0.0, 22_000f32.log2(), 3, ts), 2 => self.set_ctrl_const(value, 0.0, 0.995, 4, ts), 3 => self.set_ctrl_co...
conditional_block
banner_generator.py
from osgeo import gdal, osr, ogr import numpy as np import scipy.misc import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("banner-generator") def create_raster_from_band( red, green, blue, output_file): logger.debug("Create big raster in output_file : %s"%output_file) red_ds = gd...
dst_ds = gdal.GetDriverByName('GTiff').Create(output_file, ny, nx, 3, gdal.GDT_UInt16) dst_ds.SetGeoTransform(red_ds.GetGeoTransform()) dst_ds.SetProjection(red_ds.GetProjection()) def write_band(band, index_band): logger.debug("Write band : %s"%index_band) band_ds = gdal.Open(band...
nx = red_ds.GetRasterBand(1).XSize ny = red_ds.GetRasterBand(1).YSize
random_line_split
banner_generator.py
from osgeo import gdal, osr, ogr import numpy as np import scipy.misc import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("banner-generator") def create_raster_from_band( red, green, blue, output_file): logger.debug("Create big raster in output_file : %s"%output_file) red_ds = gd...
def extract_banner(img_path, x, y, size_x, size_y, out_path): logger.debug("Extract banner") y_min = int(y-size_y/2) y_max = y_min+size_y x_min = int(x-size_x/2) x_max = x_min+size_x logger.debug("Extract data from table") logger.debug("Min x : %s"%x_min) logger.debug("Max x : %s"...
logger.debug("Compute x and y from lon lat") logger.debug("Longitude : %s"%lon) logger.debug("Latitude : %s"%lat) sref = osr.SpatialReference() sref.ImportFromEPSG(4326) # create a geometry from coordinates point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(lon, lat) raster_ds = gdal...
identifier_body
banner_generator.py
from osgeo import gdal, osr, ogr import numpy as np import scipy.misc import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("banner-generator") def create_raster_from_band( red, green, blue, output_file): logger.debug("Create big raster in output_file : %s"%output_file) red_ds = gd...
if green_clip[0] > green_clip[1] : logger.error("Maximum clip value should be higther than the Minimum clip value") return False def clip_array(band_index, clip): array = np.array(raster_ds.GetRasterBand(band_index).ReadAsArray()) array = np.clip(array, clip[0], clip[1]) ...
logger.error("Maximum clip value should be higther than the Minimum clip value") return False
conditional_block
banner_generator.py
from osgeo import gdal, osr, ogr import numpy as np import scipy.misc import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("banner-generator") def create_raster_from_band( red, green, blue, output_file): logger.debug("Create big raster in output_file : %s"%output_file) red_ds = gd...
(band_index, clip): array = np.array(raster_ds.GetRasterBand(band_index).ReadAsArray()) array = np.clip(array, clip[0], clip[1]) array = array - clip[0] array = (np.float32(array)*bytes_max)/(clip[1]-clip[0]) array = array.astype(int) return array logger.debug("P...
clip_array
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { NgModule } from '@angular/core'; import 'hammerjs'; import { AppRoutingModule } from './routing/app-routing.module'; import { AppComponent } from './app.component'; import { LayoutModule } from './layout/la...
{ }
AppModule
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { NgModule } from '@angular/core'; import 'hammerjs'; import { AppRoutingModule } from './routing/app-routing.module'; import { AppComponent } from './app.component'; import { LayoutModule } from './layout/la...
HttpModule, InMemoryWebApiModule.forRoot(GlobalData, { delay: 1000 }), LayoutModule, UserModule, AppRoutingModule // *** This MUST always be the last import. Or child routes won't work. *** ], bootstrap: [ AppComponent ] }) export class AppModule { }
BrowserModule,
random_line_split
aiplatform_generated_aiplatform_v1beta1_vizier_service_suggest_trials_sync.py
# -*- coding: utf-8 -*- # Copyright 2020 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...
def sample_suggest_trials(): # Create a client client = aiplatform_v1beta1.VizierServiceClient() # Initialize request argument(s) request = aiplatform_v1beta1.SuggestTrialsRequest( parent="parent_value", suggestion_count=1744, client_id="client_id_value", ) # Make the ...
# [START aiplatform_generated_aiplatform_v1beta1_VizierService_SuggestTrials_sync] from google.cloud import aiplatform_v1beta1
random_line_split
aiplatform_generated_aiplatform_v1beta1_vizier_service_suggest_trials_sync.py
# -*- coding: utf-8 -*- # Copyright 2020 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_generated_aiplatform_v1beta1_VizierService_SuggestTrials_sync]
client = aiplatform_v1beta1.VizierServiceClient() # Initialize request argument(s) request = aiplatform_v1beta1.SuggestTrialsRequest( parent="parent_value", suggestion_count=1744, client_id="client_id_value", ) # Make the request operation = client.suggest_trials(request=re...
identifier_body
aiplatform_generated_aiplatform_v1beta1_vizier_service_suggest_trials_sync.py
# -*- coding: utf-8 -*- # Copyright 2020 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_v1beta1.VizierServiceClient() # Initialize request argument(s) request = aiplatform_v1beta1.SuggestTrialsRequest( parent="parent_value", suggestion_count=1744, client_id="client_id_value", ) # Make the request operation = cl...
sample_suggest_trials
identifier_name
movedex.rs
extern crate csv; use super::enums; use super::moves::Technique; use enum_primitive::FromPrimitive; use std::collections::HashMap; /// Manages the list of moves that are available. Contains a bool that is true whenever all /// available moves are inside the entries to make an easier search possible. /// By now the ...
/// Returns the entry field of a movedex. pub fn get_entries(&self) -> Vec<Technique> { self.entries.clone() } /// Returns true if the movedex contains all possible moves, and false if not. fn is_complete(&self) -> bool { self.complete } /// Creates a complete Movedex fro...
{ let mut new_dex = Vec::new(); let mut move_db = csv::Reader::from_file("./src/db/tables/pokemon_moves.csv").unwrap(); for record in move_db.decode() { let (poke_id, version, move_id, _, move_level, _): (usize, u8, ...
identifier_body
movedex.rs
extern crate csv; use super::enums; use super::moves::Technique; use enum_primitive::FromPrimitive; use std::collections::HashMap; /// Manages the list of moves that are available. Contains a bool that is true whenever all /// available moves are inside the entries to make an easier search possible. /// By now the ...
} Movedex { entries: moves, complete: true, } } }
{ if !(id == last_id) { moves[last_id - 1].set_flags(flags); last_id = id; flags = Vec::new(); } flags.push(enums::MoveFlags::from_i32(identifier).unwrap()); }
conditional_block
movedex.rs
extern crate csv; use super::enums; use super::moves::Technique; use enum_primitive::FromPrimitive; use std::collections::HashMap; /// Manages the list of moves that are available. Contains a bool that is true whenever all /// available moves are inside the entries to make an easier search possible. /// By now the ...
{ entries: Vec<Technique>, complete: bool, } // TODO: last 4 attacks are missing in move_meta.csv, therefore are not implemented right now. // DB must be extended and if statements adjusted accordingly impl Movedex { /// Takes an ID and a movedex and returns an option with the move that can be find with ...
Movedex
identifier_name
movedex.rs
extern crate csv; use super::enums; use super::moves::Technique; use enum_primitive::FromPrimitive; use std::collections::HashMap; /// Manages the list of moves that are available. Contains a bool that is true whenever all /// available moves are inside the entries to make an easier search possible. /// By now the ...
} /// Returns a list of all learnable moves by level for a specific pokemon with a specific /// level. pub fn for_token(&self, level: u16, id: usize) -> Movedex { let mut new_dex = Vec::new(); let mut move_db = csv::Reader::from_file("./src/db/tables/pokemon_moves.csv").unwrap(); ...
None
random_line_split
url.validator.ts
import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms'; export function urlValidator(control: AbstractControl): ValidationErrors
{ if (Validators.required(control) != null) { return null; } const v: string = control.value; /* tslint:disable */ return /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(...
identifier_body