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 |
|---|---|---|---|---|
generate_blink_resource_map.py | # Copyright 2015 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.
from string import Template
import optparse
import os
import sys
try:
grit_module_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..'... |
resourceIds.append(resId)
hex_values = ['0x{0:02x}'.format(ord(char)) for char in data]
f = lambda A, n=12: [A[i:i+n] for i in range(0, len(A), n)]
hex_values_string = ',\n '.join(', '.join(x) for x in f(hex_values))
cpp_definition = \
'const char kResource%s[%d] = {\n %s \n};' % \
... | continue | conditional_block |
generate_blink_resource_map.py | # Copyright 2015 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.
from string import Template
import optparse
import os
import sys
try:
grit_module_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..'... |
#include "$header_file_name"
#include "base/macros.h"
namespace html_viewer {
$definitions
BlinkResourceMap::BlinkResourceMap()
{
$map_initializer
}
const char* BlinkResourceMap::GetResource(int id, int* length)
{
ResourceMap::iterator it = resources_.find(id);
if (it == resources_.end()) {
*length = 0;... | random_line_split | |
generate_blink_resource_map.py | # Copyright 2015 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.
from string import Template
import optparse
import os
import sys
try:
grit_module_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..'... |
header_template = \
"""// Copyright 2015 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.
#ifndef MOJO_SERVICES_HTML_VIEWER_BLINK_RESOURCE_MAP_H_
#define MOJO_SERVICES_HTML_VIEWER_BLINK_RESOURCE_MAP_H_
#include <map>
... | return all(ord(c) < 128 for c in s) | identifier_body |
row-detail-template.directive.ngfactory.ts | /**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
import * as import0 from '../../../../src/components/row-detail/row-detail-template.directive';
import * as import1 from '@angular/core/s... | ():void {
}
ngDoCheck(view:import1.AppView<any>,el:any,throwOnChange:boolean):boolean {
var changed:any = this._changed;
this._changed = false;
return changed;
}
checkHost(view:import1.AppView<any>,componentView:import1.AppView<any>,el:any,throwOnChange:boolean):void {
}
handleEvent(eventName:st... | ngOnDestroy | identifier_name |
row-detail-template.directive.ngfactory.ts | /**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
import * as import0 from '../../../../src/components/row-detail/row-detail-template.directive';
import * as import1 from '@angular/core/s... |
checkHost(view:import1.AppView<any>,componentView:import1.AppView<any>,el:any,throwOnChange:boolean):void {
}
handleEvent(eventName:string,$event:any):boolean {
var result:boolean = true;
return result;
}
subscribe(view:import1.AppView<any>,_eventHandler:any):void {
this._eventHandler = _eventHan... | {
var changed:any = this._changed;
this._changed = false;
return changed;
} | identifier_body |
row-detail-template.directive.ngfactory.ts | /**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
import * as import0 from '../../../../src/components/row-detail/row-detail-template.directive';
import * as import1 from '@angular/core/s... | }
ngDoCheck(view:import1.AppView<any>,el:any,throwOnChange:boolean):boolean {
var changed:any = this._changed;
this._changed = false;
return changed;
}
checkHost(view:import1.AppView<any>,componentView:import1.AppView<any>,el:any,throwOnChange:boolean):void {
}
handleEvent(eventName:string,$even... | ngOnDetach(view:import1.AppView<any>,componentView:import1.AppView<any>,el:any):void {
}
ngOnDestroy():void { | random_line_split |
hear_words.py | #!/usr/bin/env python
import glob
import copy
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32, String
import rospkg
class | :
def __init__(self):
self.speech_subscriber = rospy.Subscriber("/speech_recognition", String, self.publish_emotion)
self.emotion_publisher = rospy.Publisher("/emotion", String, queue_size=10)
# self.timer = rospy.Timer(rospy.Duration(self.velocity), self.timer_cb)
def publish_emotion(... | Hear_orders | identifier_name |
hear_words.py | #!/usr/bin/env python
import glob
import copy
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32, String | class Hear_orders:
def __init__(self):
self.speech_subscriber = rospy.Subscriber("/speech_recognition", String, self.publish_emotion)
self.emotion_publisher = rospy.Publisher("/emotion", String, queue_size=10)
# self.timer = rospy.Timer(rospy.Duration(self.velocity), self.timer_cb)
def... | import rospkg
| random_line_split |
hear_words.py | #!/usr/bin/env python
import glob
import copy
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32, String
import rospkg
class Hear_orders:
|
def main():
rospy.init_node('hearing_node', anonymous=True)
rate = rospy.Rate(30)
rospack = rospkg.RosPack()
# path = rospack.get_path('baxter_face_animation') + "/data/"
Hear_orders()
while not rospy.is_shutdown():
rate.sleep()
if __name__ == "__main__... | def __init__(self):
self.speech_subscriber = rospy.Subscriber("/speech_recognition", String, self.publish_emotion)
self.emotion_publisher = rospy.Publisher("/emotion", String, queue_size=10)
# self.timer = rospy.Timer(rospy.Duration(self.velocity), self.timer_cb)
def publish_emotion(self, ... | identifier_body |
hear_words.py | #!/usr/bin/env python
import glob
import copy
import cv2
import cv_bridge
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Int32, Float32, String
import rospkg
class Hear_orders:
def __init__(self):
self.speech_subscriber = rospy.Subscriber("/speech_recognition", String, self.publi... |
if __name__ == "__main__":
main()
| rate.sleep() | conditional_block |
stripe.d.ts | export interface StripeCardTokenParams {
/**
* Card number
*/
number: string;
/**
* Expiry month
*/
expMonth: number;
/**
* Expiry year
*/
expYear: number;
/**
* CVC / CVV
*/
cvc?: string;
/**
* Cardholder name
*/
... | */
address_state?: string;
/**
* Country
*/
address_country?: string;
/**
* Postal code / ZIP Code
*/
postal_code?: string;
/**
* 3-letter ISO code for currency
*/
currency?: string;
}
/**
* @name Stripe
* @description
* A plugin that a... | */
address_city?: string;
/**
* State / Province
| random_line_split |
stripe.d.ts | export interface StripeCardTokenParams {
/**
* Card number
*/
number: string;
/**
* Expiry month
*/
expMonth: number;
/**
* Expiry year
*/
expYear: number;
/**
* CVC / CVV
*/
cvc?: string;
/**
* Cardholder name
*/
... | {
/**
* Set publishable key
* @param publishableKey {string} Publishable key
* @return {Promise<void>}
*/
static setPublishableKey(publishableKey: string): Promise<void>;
/**
* Create Credit Card Token
* @param params {StripeCardTokenParams} Credit card information
... | Stripe | identifier_name |
lib.py | # #
# Copyright 2018-2020 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (... | (self):
"""Prepare for running test."""
super(EasyBuildLibTest, self).setUp()
# make sure BuildOptions instance is re-created
if BuildOptions in BuildOptions._instances:
del BuildOptions._instances[BuildOptions]
self.tmpdir = tempfile.mkdtemp()
def tearDown(sel... | setUp | identifier_name |
lib.py | # #
# Copyright 2018-2020 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (... |
def test_modules_tool(self):
"""Test use of modules_tool function in the context of using EasyBuild framework as a library."""
error_pattern = "Undefined build option: .*"
error_pattern += " Make sure you have set up the EasyBuild configuration using set_up_configuration\(\)"
self.... | self.assertTrue(os.path.exists(test_dir)) | random_line_split |
lib.py | # #
# Copyright 2018-2020 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (... |
self.assertFalse(BuildOptions in BuildOptions._instances)
set_up_configuration(silent=True)
self.assertTrue(BuildOptions in BuildOptions._instances)
def test_run_cmd(self):
"""Test use of run_cmd function in the context of using EasyBuild framework as a library."""
error_... | del BuildOptions._instances[BuildOptions] | conditional_block |
lib.py | # #
# Copyright 2018-2020 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (... |
def test_run_cmd(self):
"""Test use of run_cmd function in the context of using EasyBuild framework as a library."""
error_pattern = "Undefined build option: .*"
error_pattern += " Make sure you have set up the EasyBuild configuration using set_up_configuration\(\)"
self.assertErr... | """Utility function to set up EasyBuild configuration."""
# wipe BuildOption singleton instance, so it gets re-created when set_up_configuration is called
if BuildOptions in BuildOptions._instances:
del BuildOptions._instances[BuildOptions]
self.assertFalse(BuildOptions in BuildOpt... | identifier_body |
sectionalize_pass.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 doc = test::mk_doc(
~"#[doc = \"\
# Header\n\
Body\"]\
mod a {
}");
assert!(str::contains(
doc.cratemod().mods()[0].item.sections[0].body,
~"Body"));
}
#[test]
fn should_not_create_sections_from_indented_headers() {
let doc = test::mk_doc... | should_create_section_bodies | identifier_name |
sectionalize_pass.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 ... | }");
assert!(doc.cratemod().impls()[0].methods[0].sections.len() == 1u);
}
#[cfg(test)]
pub mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use sectionalize_pass::run;
pub fn mk_doc(source: ~str) -> doc::Doc {
do astsrv::from_str(copy source) |srv| {
let do... | { } | identifier_body |
sectionalize_pass.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 ... | new_desc = match copy new_desc {
Some(desc) => {
Some(desc + ~"\n" + *line)
}
None => {
Some(copy *line)
}
};
}
}
}
}
}
if ... | body: section.body + ~"\n" + *line,
.. section
});
}
None => { | random_line_split |
config.py | from collections import namedtuple
Resolution = namedtuple('Resolution', ['x', 'y'])
class Resolutions(object):
|
class Color(object):
gray = (0.15, 0.15, 0.13, 1.0)
black = (0.0, 0.0, 0.0, 1.0)
white = (1.0, 1.0, 1.0, 1.0)
red = (1.0, 0.2, 0.0, 1.0)
orange = (1.0, 0.4, 0.0, 1.0)
yellow = (1.0, 0.9, 0.0, 1.0)
light_green = (0.4, 1.0, 0.0, 1.0)
gre... | resolutions = [
(1920, 1200),
(1920, 1080),
(1680, 1050),
(1440, 900),
(1360, 768),
(1280, 800),
(1024, 640)
]
@classmethod
def parse(self, x, y):
if (x,y) not in self.resolutions:
resolutions = ', '.join(['%sx%s' % (a... | identifier_body |
config.py | from collections import namedtuple
Resolution = namedtuple('Resolution', ['x', 'y'])
class | (object):
resolutions = [
(1920, 1200),
(1920, 1080),
(1680, 1050),
(1440, 900),
(1360, 768),
(1280, 800),
(1024, 640)
]
@classmethod
def parse(self, x, y):
if (x,y) not in self.resolutions:
resolutions = ', '.joi... | Resolutions | identifier_name |
config.py | from collections import namedtuple
Resolution = namedtuple('Resolution', ['x', 'y'])
class Resolutions(object):
resolutions = [
| (1680, 1050),
(1440, 900),
(1360, 768),
(1280, 800),
(1024, 640)
]
@classmethod
def parse(self, x, y):
if (x,y) not in self.resolutions:
resolutions = ', '.join(['%sx%s' % (a, b) for a,b in self.resolutions])
raise Exception... | (1920, 1200),
(1920, 1080),
| random_line_split |
config.py | from collections import namedtuple
Resolution = namedtuple('Resolution', ['x', 'y'])
class Resolutions(object):
resolutions = [
(1920, 1200),
(1920, 1080),
(1680, 1050),
(1440, 900),
(1360, 768),
(1280, 800),
(1024, 640)
]
@classmethod
... |
return Resolution(x, y)
class Color(object):
gray = (0.15, 0.15, 0.13, 1.0)
black = (0.0, 0.0, 0.0, 1.0)
white = (1.0, 1.0, 1.0, 1.0)
red = (1.0, 0.2, 0.0, 1.0)
orange = (1.0, 0.4, 0.0, 1.0)
yellow = (1.0, 0.9, 0.0, 1.0)
light_gree... | resolutions = ', '.join(['%sx%s' % (a, b) for a,b in self.resolutions])
raise Exception('Resolution %s x %s not supported. Available resolutions: %s' % (x,y, resolutions) ) | conditional_block |
full.py | # Copyright 2013 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.
DEPS = [
'git',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'r... | (api):
yield api.test('basic')
yield api.test('basic_ref') + api.properties(revision='refs/foo/bar')
yield api.test('basic_branch') + api.properties(revision='refs/heads/testing')
yield api.test('basic_hash') + api.properties(
revision='abcdef0123456789abcdef0123456789abcdef01')
yield api.test('basic_fi... | GenTests | identifier_name |
full.py | # Copyright 2013 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.
DEPS = [
'git',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'r... |
# Bundle the repository.
api.git.bundle_create(
api.path['start_dir'].join('all.bundle'))
def GenTests(api):
yield api.test('basic')
yield api.test('basic_ref') + api.properties(revision='refs/foo/bar')
yield api.test('basic_branch') + api.properties(revision='refs/heads/testing')
yield api.test... | step_result = api.git.cat_file_at_commit(api.properties['cat_file'],
api.properties['revision'],
stdout=api.raw_io.output())
if 'TestOutput' in step_result.stdout:
pass # Success! | conditional_block |
full.py | # Copyright 2013 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.
DEPS = [
'git',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'r... | url,
ref=api.properties.get('revision'),
recursive=True,
submodule_update_force=submodule_update_force,
set_got_revision=api.properties.get('set_got_revision'),
curl_trace_file=curl_trace_file,
remote_name=api.properties.get('remote_name'),
display_fetch_size=api.properti... | random_line_split | |
full.py | # Copyright 2013 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.
DEPS = [
'git',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'r... |
def GenTests(api):
yield api.test('basic')
yield api.test('basic_ref') + api.properties(revision='refs/foo/bar')
yield api.test('basic_branch') + api.properties(revision='refs/heads/testing')
yield api.test('basic_hash') + api.properties(
revision='abcdef0123456789abcdef0123456789abcdef01')
yield api... | url = 'https://chromium.googlesource.com/chromium/src.git'
# git.checkout can optionally dump GIT_CURL_VERBOSE traces to a log file,
# useful for debugging git access issues that are reproducible only on bots.
curl_trace_file = None
if api.properties.get('use_curl_trace'):
curl_trace_file = api.path['start... | identifier_body |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use std::path::Path;
use ops::{self, ExecEngine, ProcessEngine, Compilation};
use util::{self, CargoResult, CargoTestError, ProcessError};
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
}
#[allow(depreca... | (options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<Vec<ProcessError>> {
let mut errors = Vec::new();
let config = options.compile_opts.config;
let libs = compilation.to_doc_test.iter().map(|package| {
(package, ... | run_doc_tests | identifier_name |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use std::path::Path;
use ops::{self, ExecEngine, ProcessEngine, Compilation};
use util::{self, CargoResult, CargoTestError, ProcessError};
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
}
#[allow(depreca... |
for feat in compilation.features.iter() {
p.arg("--cfg").arg(&format!("feature=\"{}\"", feat));
}
for (_, libs) in compilation.libraries.iter() {
for &(ref target, ref lib) in libs.iter() {
// Note that we can *only* doctest rlib... | {
p.arg("--test-args").arg(&test_args.connect(" "));
} | conditional_block |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use std::path::Path;
use ops::{self, ExecEngine, ProcessEngine, Compilation};
use util::{self, CargoResult, CargoTestError, ProcessError};
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
}
#[allow(depreca... |
/// Run the unit and integration tests of a project.
fn run_unit_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<Vec<ProcessError>> {
let config = options.compile_opts.config;
let cwd = options.compile_opts.conf... | {
let mut compilation = try!(ops::compile(manifest_path,
&options.compile_opts));
compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1).cmp(&(b.0.package_id(), &b.1))
});
Ok(compilation)
} | identifier_body |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use std::path::Path;
use ops::{self, ExecEngine, ProcessEngine, Compilation};
use util::{self, CargoResult, CargoTestError, ProcessError};
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast: bool,
}
#[allow(depreca... | arg.push(rust_dep);
p.arg("-L").arg(arg);
}
for native_dep in compilation.native_dirs.values() {
p.arg("-L").arg(native_dep);
}
if test_args.len() > 0 {
p.arg("--test-args").arg(&test_args.connect(" "));
... | let mut arg = OsString::from("dependency="); | random_line_split |
main.rs | // #![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
#[macro_use]
extern crate clap;
use clap::{Arg, App};
use std::io::{self, Write};
use futures::{Future, Stream};
use tokio_core::reactor::Core;
fn | () {
let matches = App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(Arg::with_name("URL")
.help("The URL to reach")
.required(true)
.index(1))
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosit... | main | identifier_name |
main.rs | // #![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
#[macro_use]
extern crate clap;
use clap::{Arg, App};
use std::io::{self, Write};
use futures::{Future, Stream};
use tokio_core::reactor::Core;
fn main() {
let matches = App::new(crate_name!())
.version... |
let mut core = Core::new().unwrap();
let handle = core.handle();
let client = hyper::Client::configure()
.connector(hyper_tls::HttpsConnector::new(4, &handle).unwrap())
.build(&handle);
let work = client.get(url).and_then(|res| {
if matches.occurrences_of("v") > 0 {
// TODO: 1.1 is hard coded for now
... | {
println!("This example only works with 'http' URLs.");
return;
} | conditional_block |
main.rs | // #![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
#[macro_use]
extern crate clap;
use clap::{Arg, App};
use std::io::{self, Write};
use futures::{Future, Stream};
use tokio_core::reactor::Core;
fn main() | {
let matches = App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(Arg::with_name("URL")
.help("The URL to reach")
.required(true)
.index(1))
.arg(Arg::with_name("v")
.short("v")
.multiple(true)
.help("Sets the level of verbosity")... | identifier_body | |
main.rs | // #![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
#[macro_use]
extern crate clap;
use clap::{Arg, App};
use std::io::{self, Write};
use futures::{Future, Stream};
use tokio_core::reactor::Core;
fn main() {
let matches = App::new(crate_name!())
.version... | if matches.occurrences_of("v") > 0 {
println!("\n\nDone.");
}
});
core.run(work).unwrap();
} | }).map(|_| { | random_line_split |
loopback.rs | //! Serial loopback via USART1
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
use blue_pill::serial::Event;
use blue_pill::time::Hertz;... |
// IDLE LOOP
fn idle(_prio: P0, _thr: T0) -> ! {
// Sleep
loop {
rtfm::wfi();
}
}
// TASKS
tasks!(stm32f103xx, {
loopback: Task {
interrupt: USART1,
priority: P1,
enabled: true,
},
});
fn loopback(_task: USART1, ref prio: P1, ref thr: T1) {
let usart1 = USART1... | {
let afio = &AFIO.access(prio, thr);
let gpioa = &GPIOA.access(prio, thr);
let rcc = &RCC.access(prio, thr);
let usart1 = USART1.access(prio, thr);
let serial = Serial(&*usart1);
serial.init(BAUD_RATE.invert(), afio, None, gpioa, rcc);
serial.listen(Event::Rxne);
} | identifier_body |
loopback.rs | //! Serial loopback via USART1
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0" | #[macro_use]
extern crate cortex_m_rtfm as rtfm;
use blue_pill::serial::Event;
use blue_pill::time::Hertz;
use blue_pill::{Serial, stm32f103xx};
use hal::prelude::*;
use rtfm::{P0, P1, T0, T1, TMax};
use stm32f103xx::interrupt::USART1;
// CONFIGURATION
pub const BAUD_RATE: Hertz = Hertz(115_200);
// RESOURCES
periph... | random_line_split | |
loopback.rs | //! Serial loopback via USART1
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
extern crate cortex_m_rtfm as rtfm;
use blue_pill::serial::Event;
use blue_pill::time::Hertz;... | (ref prio: P0, thr: &TMax) {
let afio = &AFIO.access(prio, thr);
let gpioa = &GPIOA.access(prio, thr);
let rcc = &RCC.access(prio, thr);
let usart1 = USART1.access(prio, thr);
let serial = Serial(&*usart1);
serial.init(BAUD_RATE.invert(), afio, None, gpioa, rcc);
serial.listen(Event::Rxne)... | init | identifier_name |
replace-supers.js | /* */
"format global";
"use strict";
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { re... | (node, parent) {
if (!isSuper(node, parent)) return false;
if (t.isMemberExpression(parent, { computed: false })) return false;
if (t.isCallExpression(parent, { callee: node })) return false;
return true;
}
function isSuper(node, parent) {
return t.isIdentifier(node, { name: "super" }) && t.isReferenced(node... | isIllegalBareSuper | identifier_name |
replace-supers.js | /* */
"format global";
"use strict";
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { re... |
var getThisReference = topLevel ?
// top level so `this` is the instance
t.thisExpression :
// not in the top level so we need to create a reference
self.getThisReference.bind(self);
var callback = self.specHandle;
if (self.isLoose) callback = self.looseHandle;
return callback.call(se... | {
// break on object methods
return this.skip();
} | conditional_block |
replace-supers.js | /* */
"format global";
"use strict";
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { re... |
var visitor = {
enter: function enter(node, parent, scope, state) {
var topLevel = state.topLevel;
var self = state.self;
if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
// we need to call traverseLevel again so we're context aware
self.traverseLevel(node, false);
retu... | {
return t.isIdentifier(node, { name: "super" }) && t.isReferenced(node, parent);
} | identifier_body |
replace-supers.js | /* */
"format global";
"use strict";
var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { re... | // super(...arguments);
return t.callExpression(t.memberExpression(superProperty, t.identifier("apply")), [thisReference, args[0].argument]);
} else {
return t.callExpression(t.memberExpression(superProperty, t.identifier("call")), [thisReference].concat(_toConsumableArray(args)));
}... | random_line_split | |
PersonCreate.js | import React from 'react'
import PropTypes from 'prop-types'
import Colors from '../constants/Colors'
import Styles from '../styles/PersonCreate'
import HeaderTitle from '../components/HeaderTitle'
import PersonCreateView from '../components/PersonCreateView'
import { bindActionCreators } from 'redux'
import { connect... | renderTitle: () => (
<HeaderTitle title={'Crear'} />
),
},
}
createPerson = (person) => {
this.props.createPerson(person)
}
cleanPersonCreateResponse = () => {
this.props.cleanPersonCreateResponse()
}
render() {
return (
<PersonCreateView
styles={Styles}
... | title: 'Nuevo',
backgroundColor: Colors.white,
borderBottomWidth: 1, | random_line_split |
PersonCreate.js | import React from 'react'
import PropTypes from 'prop-types'
import Colors from '../constants/Colors'
import Styles from '../styles/PersonCreate'
import HeaderTitle from '../components/HeaderTitle'
import PersonCreateView from '../components/PersonCreateView'
import { bindActionCreators } from 'redux'
import { connect... |
}
function mapStateToProps (state) {
return {
creatingPerson: state.personCreate.creatingPerson,
errorCreatingPerson: state.personCreate.errorCreatingPerson,
successCreatingPerson: state.personCreate.successCreatingPerson,
}
}
function mapDispatchToProps (dispatch) {
const actions = bindActionCreat... | {
return (
<PersonCreateView
styles={Styles}
creatingPerson={this.props.creatingPerson}
errorCreatingPerson={this.props.errorCreatingPerson}
successCreatingPerson={this.props.successCreatingPerson}
createPerson={this.createPerson}
cleanPersonCreateResponse={this... | identifier_body |
PersonCreate.js | import React from 'react'
import PropTypes from 'prop-types'
import Colors from '../constants/Colors'
import Styles from '../styles/PersonCreate'
import HeaderTitle from '../components/HeaderTitle'
import PersonCreateView from '../components/PersonCreateView'
import { bindActionCreators } from 'redux'
import { connect... | (state) {
return {
creatingPerson: state.personCreate.creatingPerson,
errorCreatingPerson: state.personCreate.errorCreatingPerson,
successCreatingPerson: state.personCreate.successCreatingPerson,
}
}
function mapDispatchToProps (dispatch) {
const actions = bindActionCreators(allActions, dispatch)
... | mapStateToProps | identifier_name |
cpuspeed.py | """
Support for displaying the current CPU speed.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.cpuspeed/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CO... | (hass, config, add_devices, discovery_info=None):
"""Set up the CPU speed sensor."""
name = config.get(CONF_NAME)
add_devices([CpuSpeedSensor(name)])
class CpuSpeedSensor(Entity):
"""Representation of a CPU sensor."""
def __init__(self, name):
"""Initialize the sensor."""
self._n... | setup_platform | identifier_name |
cpuspeed.py | """
Support for displaying the current CPU speed.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.cpuspeed/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CO... | """Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_meas... | self.update()
@property
def name(self): | random_line_split |
cpuspeed.py | """
Support for displaying the current CPU speed.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.cpuspeed/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CO... |
@property
def icon(self):
"""Return the icon to use in the frontend, if any."""
return ICON
def update(self):
"""Get the latest data and updates the state."""
from cpuinfo import cpuinfo
self.info = cpuinfo.get_cpu_info()
self._state = round(float(self.inf... | return {
ATTR_ARCH: self.info['arch'],
ATTR_BRAND: self.info['brand'],
ATTR_HZ: round(self.info['hz_advertised_raw'][0]/10**9, 2)
} | conditional_block |
cpuspeed.py | """
Support for displaying the current CPU speed.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.cpuspeed/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CO... |
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def device_state_attributes(self):
"""Return the state attributes."""
if self.info is not None:
return {
ATT... | """Return the state of the sensor."""
return self._state | identifier_body |
heartbeat_monitor.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017
#
# Author(s):
#
# Lars Ørum Rasmussen <ras@dmi.dk>
# Janne Kotro <janne.kotro@fmi.fi>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either... |
def stop(self):
self._finished.set()
#
# Context interface.
#
def __enter__(self):
return self.start()
def __exit__(self, *exc):
return self.stop()
#
# Running in the thread.
#
def run(self):
LOGGER.debug("Starting heartbeat monitor with alarm... | f self._alarm_scale:
threading.Thread.start(self)
return self
| identifier_body |
heartbeat_monitor.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017
#
# Author(s):
#
# Lars Ørum Rasmussen <ras@dmi.dk>
# Janne Kotro <janne.kotro@fmi.fi>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either... | self):
if self._alarm_event:
LOGGER.debug("Missing heartbeat alarm!")
self._alarm_event.set()
| set_alarm( | identifier_name |
heartbeat_monitor.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017
#
# Author(s):
#
# Lars Ørum Rasmussen <ras@dmi.dk>
# Janne Kotro <janne.kotro@fmi.fi>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either... | return self.start()
def __exit__(self, *exc):
return self.stop()
#
# Running in the thread.
#
def run(self):
LOGGER.debug("Starting heartbeat monitor with alarm scale %.2f", self._alarm_scale)
while not self._finished.is_set():
self._resetted = True
... | # Context interface.
#
def __enter__(self): | random_line_split |
heartbeat_monitor.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017
#
# Author(s):
#
# Lars Ørum Rasmussen <ras@dmi.dk>
# Janne Kotro <janne.kotro@fmi.fi>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either... | OGGER.debug("Missing heartbeat alarm!")
self._alarm_event.set()
| conditional_block | |
uievent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... | (window: &Window) -> Root<UIEvent> {
reflect_dom_object(box UIEvent::new_inherited(),
GlobalRef::Window(window),
UIEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: DOMString,
can_bubble: EventBubbles,
... | new_uninitialized | identifier_name |
uievent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... | let cancelable = if init.parent.cancelable {
EventCancelable::Cancelable
} else {
EventCancelable::NotCancelable
};
let event = UIEvent::new(global.as_window(), type_,
bubbles, cancelable,
init.view... | random_line_split | |
uievent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... |
event.init_event(Atom::from(&*type_), can_bubble, cancelable);
self.view.set(view);
self.detail.set(detail);
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
return;
} | conditional_block |
uievent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::UIEventBin... |
pub fn new(window: &Window,
type_: DOMString,
can_bubble: EventBubbles,
cancelable: EventCancelable,
view: Option<&Window>,
detail: i32) -> Root<UIEvent> {
let ev = UIEvent::new_uninitialized(window);
ev.InitUIEvent(type_, ... | {
reflect_dom_object(box UIEvent::new_inherited(),
GlobalRef::Window(window),
UIEventBinding::Wrap)
} | identifier_body |
adjGraph.py | #
# adjGraph
#
# Created by Brad Miller on 2005-02-24.
# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.
#
import sys
import os
import unittest
class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
def addVertex(self,key):
... | (self):
return self.color
def getConnections(self):
return self.connectedTo.keys()
def getWeight(self,nbr):
return self.connectedTo[nbr]
def __str__(self):
return str(self.id) + ":color " + self.color + ":disc " + str(self.disc) + ":fin " + str(... | getColor | identifier_name |
adjGraph.py | #
# adjGraph
#
# Created by Brad Miller on 2005-02-24.
# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.
#
import sys
import os
import unittest
class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
def addVertex(self,key):
... | def getDistance(self):
return self.dist
def getColor(self):
return self.color
def getConnections(self):
return self.connectedTo.keys()
def getWeight(self,nbr):
return self.connectedTo[nbr]
def __str__(self):
return str(s... |
def getPred(self):
return self.pred
| random_line_split |
adjGraph.py | #
# adjGraph
#
# Created by Brad Miller on 2005-02-24.
# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.
#
import sys
import os
import unittest
class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
def addVertex(self,key):
... |
if __name__ == '__main__':
unittest.main()
| print(i, k) | conditional_block |
adjGraph.py | #
# adjGraph
#
# Created by Brad Miller on 2005-02-24.
# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.
#
import sys
import os
import unittest
class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
def addVertex(self,key):
... |
def getId(self):
return self.id
class adjGraphTests(unittest.TestCase):
def setUp(self):
self.tGraph = Graph()
def testMakeGraph(self):
gFile = open("test.dat")
for line in gFile:
fVertex, tVertex = line.split('|')
fVertex = int(fVertex... | return str(self.id) + ":color " + self.color + ":disc " + str(self.disc) + ":fin " + str(self.fin) + ":dist " + str(self.dist) + ":pred \n\t[" + str(self.pred)+ "]\n" | identifier_body |
ip_dns_suffix.py | from a10sdk.common.A10BaseClass import A10BaseClass
class Suffix(A10BaseClass):
"""Class Description::
DNS suffix.
Class suffix supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param domain_name: {"description": "DNS suf... | (self, **kwargs):
self.ERROR_MSG = ""
self.required=[]
self.b_key = "suffix"
self.a10_url="/axapi/v3/ip/dns/suffix"
self.DeviceProxy = ""
self.domain_name = ""
self.uuid = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
| __init__ | identifier_name |
ip_dns_suffix.py | from a10sdk.common.A10BaseClass import A10BaseClass
|
"""Class Description::
DNS suffix.
Class suffix supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param domain_name: {"description": "DNS suffix", "format": "string", "minLength": 1, "optional": true, "maxLength": 32, "type... | class Suffix(A10BaseClass): | random_line_split |
ip_dns_suffix.py | from a10sdk.common.A10BaseClass import A10BaseClass
class Suffix(A10BaseClass):
"""Class Description::
DNS suffix.
Class suffix supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param domain_name: {"description": "DNS suf... | setattr(self,keys, value) | conditional_block | |
ip_dns_suffix.py | from a10sdk.common.A10BaseClass import A10BaseClass
class Suffix(A10BaseClass):
"""Class Description::
DNS suffix.
Class suffix supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param domain_name: {"description": "DNS suf... | self.ERROR_MSG = ""
self.required=[]
self.b_key = "suffix"
self.a10_url="/axapi/v3/ip/dns/suffix"
self.DeviceProxy = ""
self.domain_name = ""
self.uuid = ""
for keys, value in kwargs.items():
setattr(self,keys, value) | identifier_body | |
touch_surface.js | 'use strict';
var ContextHistory = require('./context_history');
var ContextTouch = require('./context_touch');
/**
* @param {!angular.Scope} $rootScope
* @param {!Window} $window
* @param {!Document} $document
* @param {!angular.Attributes} options
* @param {!TouchSurface.TouchChangedHandler} startHandler
* @... | *
* @param {boolean=} opt_offTheRecord
*/
TouchSurface.prototype.clear = function(opt_offTheRecord) {
if (opt_offTheRecord) {
ContextHistory.erase(this.context_);
} else {
this.contextHistory.undoAll(this.context_);
}
};
/** Unrenders the most previously added update */
TouchSurface.prototype.undo = ... |
/**
* Erases all currently rendered animations on the surface. | random_line_split |
touch_surface.js | 'use strict';
var ContextHistory = require('./context_history');
var ContextTouch = require('./context_touch');
/**
* @param {!angular.Scope} $rootScope
* @param {!Window} $window
* @param {!Document} $document
* @param {!angular.Attributes} options
* @param {!TouchSurface.TouchChangedHandler} startHandler
* @... |
this.resizeSurfaceToContainer_(surface, event.target);
this.redraw(); // put everything back where it was
};
/**
* @param {!CanvasRenderingContext2D} surface
* @param {!Window} container
* @private
*/
TouchSurface.prototype.resizeSurfaceToContainer_ = function(
surface, container) {
surface.canvas.wi... | {
// strange: this happens when opening dev console
// (eg: `event` is: 1987.7080000005662)
return;
} | conditional_block |
gradient.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/.
// external
use crate::qt;
// self
use super::prelude::*;
pub fn | (
g: &usvg::LinearGradient,
opacity: usvg::Opacity,
bbox: Rect,
brush: &mut qt::Brush,
) {
let mut grad = qt::LinearGradient::new(g.x1, g.y1, g.x2, g.y2);
prepare_base(&g.base, opacity, &mut grad);
brush.set_linear_gradient(grad);
apply_ts(&g.base, bbox, brush);
}
pub fn prepare_radial... | prepare_linear | identifier_name |
gradient.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/.
// external
use crate::qt;
// self
use super::prelude::*;
pub fn prepare_linear(
g: &usvg::LinearGradient,
... | {
// We don't use `QGradient::setCoordinateMode` because it works incorrectly.
//
// See QTBUG-67995
if g.units == usvg::Units::ObjectBoundingBox {
let mut ts = usvg::Transform::from_bbox(bbox);
ts.append(&g.transform);
brush.set_transform(ts.to_native());
} else {
b... | identifier_body | |
gradient.rs | use crate::qt;
// self
use super::prelude::*;
pub fn prepare_linear(
g: &usvg::LinearGradient,
opacity: usvg::Opacity,
bbox: Rect,
brush: &mut qt::Brush,
) {
let mut grad = qt::LinearGradient::new(g.x1, g.y1, g.x2, g.y2);
prepare_base(&g.base, opacity, &mut grad);
brush.set_linear_gradie... | // 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/.
// external | random_line_split | |
modify-date.ts | import {DateTime} from "luxon";
export function | (modifier: string): DateTime {
let result = null;
let regExp = /^([-|\+])([0-9]+?)(\s*)([a-z]*)/g;
let matches: RegExpExecArray = regExp.exec(modifier);
if (matches) {
result = DateTime.local();
let sign = matches[1];
let count: number = parseInt(matches[2]);
let unit ... | modifyDate | identifier_name |
modify-date.ts | import {DateTime} from "luxon";
export function modifyDate(modifier: string): DateTime {
let result = null;
let regExp = /^([-|\+])([0-9]+?)(\s*)([a-z]*)/g;
let matches: RegExpExecArray = regExp.exec(modifier);
if (matches) {
result = DateTime.local();
let sign = matches[1];
... |
return result;
} | }
else {
result = DateTime.invalid(`Failed to parse relative date "${modifier}".`);
} | random_line_split |
modify-date.ts | import {DateTime} from "luxon";
export function modifyDate(modifier: string): DateTime | {
let result = null;
let regExp = /^([-|\+])([0-9]+?)(\s*)([a-z]*)/g;
let matches: RegExpExecArray = regExp.exec(modifier);
if (matches) {
result = DateTime.local();
let sign = matches[1];
let count: number = parseInt(matches[2]);
let unit = matches[4];
switch... | identifier_body | |
ToolbarPersistTest.ts | import { UiFinder, Waiter } from '@ephox/agar';
import { describe, it } from '@ephox/bedrock-client';
import { TinyHooks, TinyUiActions } from '@ephox/mcagar';
import { Focus, Insert, Remove, SugarBody, SugarElement } from '@ephox/sugar';
import Editor from 'tinymce/core/api/Editor';
import Theme from 'tinymce/themes/... | unfocusEditor();
await Waiter.pWait(200); // Need to wait since nothing should happen.
await TinyUiActions.pWaitForPopup(editor, '.tox-tinymce-inline');
editor.ui.hide();
await UiFinder.pWaitForHidden('Wait for editor to be hidden', SugarBody.body(), '.tox-tinymce-inline');
editor.focus();
... |
it('TINY-4847: With toolbar_persist focus & unfocus should not affect toolbar visibility', async () => {
const editor = hook.editor();
await TinyUiActions.pWaitForPopup(editor, '.tox-tinymce-inline'); | random_line_split |
remoteobj.py | #!/usr/bin/env python
# remoteobj v0.4, best yet!
# TODO: This will get wrecked by recursive sets/lists/dicts; need a more picklish method.
# TODO: Dict/sets/lists should get unpacked to wrappers that are local for read-only access,
# but update the remote for write access. Note that __eq__ will be an interesting... |
def handle_hash(self, obj):
return self.pack(hash(self.unpack(obj)))
def repr(self, proxy):
return self.request(('repr', object.__getattribute__(proxy, '_proxyinfo').packed()))
def handle_repr(self, obj):
return self.pack(repr(self.unpack(obj)))
def delete(self, proxy):
info = object.__getatt... | return self.request(('hash', object.__getattribute__(proxy, '_proxyinfo').packed())) | identifier_body |
remoteobj.py | #!/usr/bin/env python
# remoteobj v0.4, best yet!
# TODO: This will get wrecked by recursive sets/lists/dicts; need a more picklish method.
# TODO: Dict/sets/lists should get unpacked to wrappers that are local for read-only access,
# but update the remote for write access. Note that __eq__ will be an interesting... |
def callattr(self, proxy, attr, args, kwargs):
return self.request(('callattr', object.__getattribute__(proxy, '_proxyinfo').packed(), attr, self.pack(args or None), self.pack(kwargs or None)))
def handle_callattr(self, obj, attr, args, kwargs):
return self.pack(getattr(self.unpack(obj), attr)(*(self.unpac... | def call(self, proxy, args, kwargs):
return self.request(('call', object.__getattribute__(proxy, '_proxyinfo').packed(), self.pack(args or None), self.pack(kwargs or None)))
def handle_call(self, obj, args, kwargs):
return self.pack(self.unpack(obj)(*(self.unpack(args) or ()), **(self.unpack(kwargs) or {}))... | random_line_split |
remoteobj.py | #!/usr/bin/env python
# remoteobj v0.4, best yet!
# TODO: This will get wrecked by recursive sets/lists/dicts; need a more picklish method.
# TODO: Dict/sets/lists should get unpacked to wrappers that are local for read-only access,
# but update the remote for write access. Note that __eq__ will be an interesting... | (self):
info = object.__getattribute__(self, '_proxyinfo')
if info.proxyhash is None:
info.proxyhash = object.__getattribute__(self, '_proxyconn').hash(self)
return info.proxyhash
def __repr__(self):
return object.__getattribute__(self, '_proxyconn').repr(self)
# Special methods don't always ... | __hash__ | identifier_name |
remoteobj.py | #!/usr/bin/env python
# remoteobj v0.4, best yet!
# TODO: This will get wrecked by recursive sets/lists/dicts; need a more picklish method.
# TODO: Dict/sets/lists should get unpacked to wrappers that are local for read-only access,
# but update the remote for write access. Note that __eq__ will be an interesting... |
return info.proxyhash
def __repr__(self):
return object.__getattribute__(self, '_proxyconn').repr(self)
# Special methods don't always go through __getattribute__, so redirect them all there.
for special in ('__str__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__rcmp__', '_... | info.proxyhash = object.__getattribute__(self, '_proxyconn').hash(self) | conditional_block |
index.d.ts | // Type definitions for Fuse.js 2.5.0
// Project: https://github.com/krisk/Fuse
// Definitions by: Greg Smith <https://github.com/smrq/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare class Fuse<T> {
constructor(list: T[], options?: Fuse.Options<T>);
search(pattern: string): T[];
}
decla... | distance?: number;
threshold?: number;
maxPatternLength?: number;
includeScore?: boolean;
getFn?: (obj: T, path: string) => string;
}
}
export = Fuse;
export as namespace Fuse; | tokenize?: boolean;
tokenSeparator? : RegExp;
matchAllTokens?: boolean;
location?: number; | random_line_split |
index.d.ts | // Type definitions for Fuse.js 2.5.0
// Project: https://github.com/krisk/Fuse
// Definitions by: Greg Smith <https://github.com/smrq/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare class | <T> {
constructor(list: T[], options?: Fuse.Options<T>);
search(pattern: string): T[];
}
declare namespace Fuse {
interface SearchFnConstructor {
new (pattern: string, options?: SearchOptions): SearchFn;
}
interface SearchFn {
search(text: string): SearchResult;
}
interface SearchResult {
readonly isMat... | Fuse | identifier_name |
copyable.js | /**
@module ember
@submodule ember-runtime
*/
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import { required } from "ember-metal/mixin";
import { Freezable } from "ember-runtime/mixins/freezable";
import { Mixin } from 'ember-metal/mixin';
import { fmt } from "ember-... | else {
throw new EmberError(fmt("%@ does not support freezing", [this]));
}
}
});
| {
return get(this, 'isFrozen') ? this : this.copy().freeze();
} | conditional_block |
copyable.js | /**
@module ember
@submodule ember-runtime
*/
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import { required } from "ember-metal/mixin";
import { Freezable } from "ember-runtime/mixins/freezable";
import { Mixin } from 'ember-metal/mixin';
import { fmt } from "ember-... | /**
Override to return a copy of the receiver. Default implementation raises
an exception.
@method copy
@param {Boolean} deep if `true`, a deep copy of the object should be made
@return {Object} copy of receiver
*/
copy: required(Function),
/**
If the object implements `Ember.Freezable... | @namespace Ember
@since Ember 0.9
*/
export default Mixin.create({ | random_line_split |
serialindicator.tsx | /// <reference path="../../built/pxtsim.d.ts" />
import * as React from "react";
import * as sui from "./sui";
import * as data from "./data";
export interface SerialIndicatorProps {
isSim: boolean,
onClick: () => any
}
export interface SerialIndicatorState {
active?: boolean
}
export class SerialIndica... | (props: any) {
super(props)
this.state = { active: false }
}
componentDidMount() {
window.addEventListener("message", this.setActive.bind(this))
}
componentWillUnmount() {
window.addEventListener("message", this.setActive.bind(this))
}
setActive(ev: MessageEven... | constructor | identifier_name |
serialindicator.tsx | /// <reference path="../../built/pxtsim.d.ts" />
import * as React from "react";
import * as sui from "./sui";
import * as data from "./data";
export interface SerialIndicatorProps {
isSim: boolean,
onClick: () => any
}
export interface SerialIndicatorState {
active?: boolean
}
export class SerialIndica... |
componentWillUnmount() {
window.addEventListener("message", this.setActive.bind(this))
}
setActive(ev: MessageEvent) {
let msg = ev.data
if (!this.state.active && (msg.type === "serial" || msg.type === "bulkserial")) {
const sim = !!msg.sim
if (sim === this... | {
window.addEventListener("message", this.setActive.bind(this))
} | identifier_body |
serialindicator.tsx | /// <reference path="../../built/pxtsim.d.ts" /> | import * as data from "./data";
export interface SerialIndicatorProps {
isSim: boolean,
onClick: () => any
}
export interface SerialIndicatorState {
active?: boolean
}
export class SerialIndicator extends data.Component<SerialIndicatorProps, SerialIndicatorState> {
constructor(props: any) {
... |
import * as React from "react";
import * as sui from "./sui"; | random_line_split |
serialindicator.tsx | /// <reference path="../../built/pxtsim.d.ts" />
import * as React from "react";
import * as sui from "./sui";
import * as data from "./data";
export interface SerialIndicatorProps {
isSim: boolean,
onClick: () => any
}
export interface SerialIndicatorState {
active?: boolean
}
export class SerialIndica... |
}
clear() {
this.setState({ active: false })
}
renderCore() {
if (!this.state.active) return <div />;
return (
<div role="button" title={lf("Open console")} className="ui label circular" tabIndex={0} onClick={this.props.onClick} onKeyDown={sui.fireClickOnEnter}>
... | {
const sim = !!msg.sim
if (sim === this.props.isSim) {
this.setState({ active: true })
}
} | conditional_block |
check_mq_channel.py | #!/usr/bin/python
import getopt
import sys
import pymqi, CMQC, CMQCFC
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
def usage():
print """Usage: rbh_check_mq_channel_status -H <HostName> -g <QMGRName> -p <PortNumber> -a <ChannelName for connection> -t <ChannelName for test>"""
def | ():
usage()
print """
Checks MQ channel status
-H, --host Host name
-g, --qmgr Queue Manager Name
-p, --port-number port number (default 1414)
-a, --channel-name-conn channel name for connection
-t, --channel-name channel name for test
example:
rbh_check_mq_... | show_help | identifier_name |
check_mq_channel.py | #!/usr/bin/python
import getopt
import sys
import pymqi, CMQC, CMQCFC
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
def usage():
print """Usage: rbh_check_mq_channel_status -H <HostName> -g <QMGRName> -p <PortNumber> -a <ChannelName for connection> -t <ChannelName for test>"""
def show_hel... |
if __name__ == "__main__":
main()
| try:
opts, args = getopt.getopt(sys.argv[1:], "hH:g:p:a:t:", ["help", "host","qmgr=","port=","channel-name=","channel-name-conn="])
except getopt.GetoptError, err:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
hostName=None
qmgrName... | identifier_body |
check_mq_channel.py | #!/usr/bin/python
import getopt
import sys
import pymqi, CMQC, CMQCFC
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
def usage():
print """Usage: rbh_check_mq_channel_status -H <HostName> -g <QMGRName> -p <PortNumber> -a <ChannelName for connection> -t <ChannelName for test>"""
def show_hel... |
else:
assert False, "unhandled option"
if not (hostName and portNumber and channelNameTest and qmgrName and channelNameConn):
usage()
exit_with_state(STATE_UNKNOWN)
# if len(channelNameConn) > MQ_CHANNEL_NAME_LENGTH:
# print "UNKNOWN - Channel name are too long."
c... | channelNameTest = a | conditional_block |
check_mq_channel.py | #!/usr/bin/python
import getopt
import sys
import pymqi, CMQC, CMQCFC
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
def usage():
print """Usage: rbh_check_mq_channel_status -H <HostName> -g <QMGRName> -p <PortNumber> -a <ChannelName for connection> -t <ChannelName for test>"""
def show_hel... | exit_with_state(STATE_OK)
if __name__ == "__main__":
main() | else:
print("OK - Channel %s is defined, but status is not available. This may indicate that the channel has not been used." % (channelNameTest)) | random_line_split |
dev.py | from .base import *
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = True
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'dev',
'USER': 'de... | (request):
return True
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK": show_toolbar,
}
ALLOWED_HOSTS = '*'
| show_toolbar | identifier_name |
dev.py | from .base import *
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = True
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'dev',
'USER': 'de... |
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK": show_toolbar,
}
ALLOWED_HOSTS = '*' | random_line_split | |
dev.py | from .base import *
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = True
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'dev',
'USER': 'de... |
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK": show_toolbar,
}
ALLOWED_HOSTS = '*'
| return True | identifier_body |
lint-for-crate.rs | // force-host
#![feature(rustc_private)]
#![feature(box_syntax)]
extern crate rustc_driver;
extern crate rustc_hir;
#[macro_use]
extern crate rustc_lint;
#[macro_use]
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_ast;
use rustc_driver::plugin::Registry;
use rustc_lint::{LateContext, LateLin... | (reg: &mut Registry) {
reg.lint_store.register_lints(&[&CRATE_NOT_OKAY]);
reg.lint_store.register_late_pass(|| box Pass);
}
| __rustc_plugin_registrar | identifier_name |
lint-for-crate.rs | // force-host
#![feature(rustc_private)]
#![feature(box_syntax)]
extern crate rustc_driver;
extern crate rustc_hir; | extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_ast;
use rustc_driver::plugin::Registry;
use rustc_lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
use rustc_span::symbol::Symbol;
use rustc_ast::attr;
declare_lint! {
CRATE_NOT_OKAY,
Warn,
"crate not marked with ... | #[macro_use]
extern crate rustc_lint;
#[macro_use] | random_line_split |
lint-for-crate.rs | // force-host
#![feature(rustc_private)]
#![feature(box_syntax)]
extern crate rustc_driver;
extern crate rustc_hir;
#[macro_use]
extern crate rustc_lint;
#[macro_use]
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_ast;
use rustc_driver::plugin::Registry;
use rustc_lint::{LateContext, LateLin... |
}
}
#[no_mangle]
fn __rustc_plugin_registrar(reg: &mut Registry) {
reg.lint_store.register_lints(&[&CRATE_NOT_OKAY]);
reg.lint_store.register_late_pass(|| box Pass);
}
| {
cx.lint(CRATE_NOT_OKAY, |lint| {
lint.build("crate is not marked with #![crate_okay]")
.set_span(krate.module().inner)
.emit()
});
} | conditional_block |
lint-for-crate.rs | // force-host
#![feature(rustc_private)]
#![feature(box_syntax)]
extern crate rustc_driver;
extern crate rustc_hir;
#[macro_use]
extern crate rustc_lint;
#[macro_use]
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_ast;
use rustc_driver::plugin::Registry;
use rustc_lint::{LateContext, LateLin... | {
reg.lint_store.register_lints(&[&CRATE_NOT_OKAY]);
reg.lint_store.register_late_pass(|| box Pass);
} | identifier_body | |
app.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... |
def build_wsgi_app(argv=None):
service.prepare_service(sys.argv)
return load_app()
| return setup_app() | identifier_body |
app.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... |
elif os.path.exists(cfg_path):
cfg_file = cfg_path
if not cfg_file:
raise cfg.ConfigFilesNotFoundError([CONF.api.api_paste_config])
LOG.info("Full WSGI config used: %s", cfg_file)
return deploy.loadapp("config:" + cfg_file)
def app_factory(global_config, **local_conf):
return set... | cfg_file = CONF.find_file(cfg_path) | conditional_block |
app.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... | import pecan
from magnum.api import config as api_config
from magnum.api import middleware
from magnum.common import config as common_config
from magnum.common import service
import magnum.conf
CONF = magnum.conf.CONF
LOG = log.getLogger(__name__)
def get_pecan_config():
# Set up the pecan configuration
fi... | from oslo_log import log
from paste import deploy | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.