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 |
|---|---|---|---|---|
pib.py | # pib.py - functions for handling Serbian VAT numbers
# coding: utf-8
#
# Copyright (C) 2017 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the L... | """PIB (Poreski Identifikacioni Broj, Serbian tax identification number).
The Serbian tax identification number consists of 9 digits where the last
digit is a check digit.
>>> validate('101134702')
'101134702'
>>> validate('101134703')
Traceback (most recent call last):
...
InvalidChecksum: ...
"""
from stdnum.e... | # License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
| random_line_split |
pib.py | # pib.py - functions for handling Serbian VAT numbers
# coding: utf-8
#
# Copyright (C) 2017 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the L... |
if len(number) != 9:
raise InvalidLength()
mod_11_10.validate(number)
return number
def is_valid(number):
"""Check if the number is a valid VAT number."""
try:
return bool(validate(number))
except ValidationError:
return False
| raise InvalidFormat() | conditional_block |
pib.py | # pib.py - functions for handling Serbian VAT numbers
# coding: utf-8
#
# Copyright (C) 2017 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the L... |
def is_valid(number):
"""Check if the number is a valid VAT number."""
try:
return bool(validate(number))
except ValidationError:
return False
| """Check if the number is a valid VAT number. This checks the length,
formatting and check digit."""
number = compact(number)
if not isdigits(number):
raise InvalidFormat()
if len(number) != 9:
raise InvalidLength()
mod_11_10.validate(number)
return number | identifier_body |
batch_norm_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC, normc_initializer as \
torch_normc_initializer
from ray.rllib.models.torch.torch_modelv2 import... |
output = tf.keras.layers.Dense(
units=self.num_outputs,
kernel_initializer=normc_initializer(0.01),
activation=None,
name="fc_out")(last_layer)
value_out = tf.keras.layers.Dense(
units=1,
kernel_initializer=normc_initializer(0.01),... | label = "fc{}".format(i)
last_layer = tf.keras.layers.Dense(
units=size,
kernel_initializer=normc_initializer(1.0),
activation=tf.nn.tanh,
name=label)(last_layer)
# Add a batch norm layer
last_layer = tf.keras.layers.Bat... | conditional_block |
batch_norm_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC, normc_initializer as \
torch_normc_initializer
from ray.rllib.models.torch.torch_modelv2 import... | (self, input_dict, state, seq_lens):
out, self._value_out = self.base_model(
[input_dict["obs"], input_dict["is_training"]])
return out, []
@override(ModelV2)
def value_function(self):
return tf.reshape(self._value_out, [-1])
class TorchBatchNormModel(TorchModelV2, nn.Modu... | forward | identifier_name |
batch_norm_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC, normc_initializer as \
torch_normc_initializer
from ray.rllib.models.torch.torch_modelv2 import... | [input_dict["obs"], input_dict["is_training"]])
return out, []
@override(ModelV2)
def value_function(self):
return tf.reshape(self._value_out, [-1])
class TorchBatchNormModel(TorchModelV2, nn.Module):
"""Example of a TorchModelV2 using batch normalization."""
capture_index... |
@override(ModelV2)
def forward(self, input_dict, state, seq_lens):
out, self._value_out = self.base_model( | random_line_split |
batch_norm_model.py | import numpy as np
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.misc import SlimFC, normc_initializer as \
torch_normc_initializer
from ray.rllib.models.torch.torch_modelv2 import... |
@override(ModelV2)
def forward(self, input_dict, state, seq_lens):
# Set the correct train-mode for our hidden module (only important
# b/c we have some batch-norm layers).
self._hidden_layers.train(mode=input_dict.get("is_training", False))
self._hidden_out = self._hidden_laye... | TorchModelV2.__init__(self, obs_space, action_space, num_outputs,
model_config, name)
nn.Module.__init__(self)
layers = []
prev_layer_size = int(np.product(obs_space.shape))
self._logits = None
# Create layers 0 to second-last.
for size in [... | identifier_body |
holiday-shutdowns.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toPromise } from 'rxjs/operator/toPromise';
import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { BaseService } from './base.service';
import { HolidayShutdown } from '../sha... |
getHolidayShutdowns(): Promise<HolidayShutdown[]> {
const uri = HolidayShutdownsUri.HolidayShutdownsBase;
return this.http.get(`${uri}`)
.toPromise()
.then((response) => {
return response as HolidayShutdown[];
})
.catch(this.handleError);
}
saveHolidayShutdown(holidaySh... | { super(http); } | identifier_body |
holiday-shutdowns.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toPromise } from 'rxjs/operator/toPromise';
import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { BaseService } from './base.service';
import { HolidayShutdown } from '../sha... | (holidayShutdown: HolidayShutdown): Promise<HolidayShutdown> {
const uri = HolidayShutdownsUri.HolidayShutdownsBase;
return this.http.post(`${uri}`, this.formatDate(holidayShutdown)).toPromise().catch(this.handleError);
}
deleteHolidayShutdown(id: number): Promise<HolidayShutdown> {
const uri = Holiday... | saveHolidayShutdown | identifier_name |
holiday-shutdowns.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
| import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { BaseService } from './base.service';
import { HolidayShutdown } from '../shared/dto/holiday-shutdown';
import { HolidayShutdownsUri } from '../shared/enums';
@Injectable()
export class HolidayShutdownsService extends BaseServ... | import { toPromise } from 'rxjs/operator/toPromise';
| random_line_split |
NodeReadPlugin.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// 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
... | {
return promisifiedRead(rawArticle);
} | identifier_body | |
NodeReadPlugin.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// 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
... | // This program is distributed in the hope that it will be useful, but 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 ... | // version.
// | random_line_split |
NodeReadPlugin.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// 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
... | (rawArticle : string) : Promise <NodeReadArticle> {
return promisifiedRead(rawArticle);
}
| create | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (PythonPackage):
"""pasta is an AST-based Python refactoring library."""
homepage = "https://github.com/google/pasta"
url = "https://pypi.io/packages/source/g/google-pasta/google-pasta-0.1.8.tar.gz"
version('0.1.8', sha256='713813a9f7d6589e5defdaf21e80e4392eb124662f8bd829acd51a4f8735c0cb')
d... | PyGooglePasta | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyGooglePasta(PythonPackage):
| """pasta is an AST-based Python refactoring library."""
homepage = "https://github.com/google/pasta"
url = "https://pypi.io/packages/source/g/google-pasta/google-pasta-0.1.8.tar.gz"
version('0.1.8', sha256='713813a9f7d6589e5defdaf21e80e4392eb124662f8bd829acd51a4f8735c0cb')
depends_on('py-setupto... | identifier_body | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
# | from spack import *
class PyGooglePasta(PythonPackage):
"""pasta is an AST-based Python refactoring library."""
homepage = "https://github.com/google/pasta"
url = "https://pypi.io/packages/source/g/google-pasta/google-pasta-0.1.8.tar.gz"
version('0.1.8', sha256='713813a9f7d6589e5defdaf21e80e439... | # SPDX-License-Identifier: (Apache-2.0 OR MIT)
| random_line_split |
shape.py | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
return None
| if shape == marked_shape:
return special_type_map[special_type] | conditional_block |
shape.py | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | EVENT_NAME = ''
def __init__(self, service_name, operation_name, event_emitter,
context=None):
self._service_name = service_name
self._operation_name = operation_name
self._event_emitter = event_emitter
self._context = context
if context is None:
... | identifier_body | |
shape.py | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | self._event_emitter.emit(
'docs.%s.%s.%s.%s' % (self.EVENT_NAME,
self._service_name,
self._operation_name,
name),
section=section)
... | include=include, exclude=exclude,
is_top_level_param=is_top_level_param,
is_required=is_required)
if is_top_level_param: | random_line_split |
shape.py | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | (self, section, shape, history,
include=None, exclude=None, name=None,
is_required=False):
"""Traverses and documents a shape
Will take a self class and call its appropriate methods as a shape
is traversed.
:param ... | traverse_and_document_shape | identifier_name |
issue-38293.rs | // Copyright 2016 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 foo::f::{self}; //~ ERROR unresolved import `foo::f`
mod bar {
pub fn baz() {}
pub mod baz {}
}
use bar::baz::{self};
fn main() {
baz(); //~ ERROR expected function, found module `baz`
}
| { } | identifier_body |
issue-38293.rs | // Copyright 2016 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 foo::f::{self}; //~ ERROR unresolved import `foo::f`
mod bar {
pub fn baz() {}
pub mod baz {}
}
use bar::baz::{self};
fn main() {
baz(); //~ ERROR expected function, found module `baz`
}
| f | identifier_name |
issue-38293.rs | // Copyright 2016 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 ... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that `fn foo::bar::{self}` only imports `bar` in the type namespace.
mod foo {
pub fn f() { }
}
use foo::f::{self}; //~ ERROR unresolved import `foo::f`
mod bar {
pub fn baz() {}
pub mod baz {}
}
... | random_line_split | |
Citizen.ts | module Thralldom {
export module AI {
export class Citizen extends AIController {
private previousDistance: number;
private zeroMovementCounter: number;
private static MaxZeroMovementFrames = 15;
| (character: Character, graph: Algorithms.IGraph) {
super(character, graph);
var pos = GeometryUtils.Vector3To2(character.mesh.position);
this.previousDistance = Infinity;
this.randomizeGoal(pos);
}
public updateCallback(delta: num... | constructor | identifier_name |
Citizen.ts | module Thralldom {
export module AI {
export class Citizen extends AIController {
private previousDistance: number;
private zeroMovementCounter: number;
private static MaxZeroMovementFrames = 15;
constructor(character: Character, graph: Algorithms.IGraph) {
... | public updateCallback(delta: number, world: Thralldom.World): void {
var character = this.character;
var pos = GeometryUtils.Vector3To2(character.mesh.position);
var target = this.path[this.currentNode].first;
var distanceToTarget = pos.distan... | random_line_split | |
xsdt.rs | //! Extended System Description Table
use core::mem; | pub struct Xsdt(&'static Sdt);
impl Xsdt {
/// Cast SDT to XSDT if signature matches.
pub fn new(sdt: &'static Sdt) -> Option<Self> {
if &sdt.signature == b"XSDT" {
Some(Xsdt(sdt))
} else {
None
}
}
/// Get a iterator for the table entries.
pub fn it... |
use super::sdt::Sdt;
/// XSDT structure
#[derive(Debug)] | random_line_split |
xsdt.rs | //! Extended System Description Table
use core::mem;
use super::sdt::Sdt;
/// XSDT structure
#[derive(Debug)]
pub struct Xsdt(&'static Sdt);
impl Xsdt {
/// Cast SDT to XSDT if signature matches.
pub fn new(sdt: &'static Sdt) -> Option<Self> {
if &sdt.signature == b"XSDT" {
Some(Xsdt(sdt... |
// When there is no more elements return a None value
None
}
}
| {
// get the item
let item = unsafe { *(self.sdt.data_address() as *const u64).offset(self.index as isize) };
// increment the index
self.index += 1;
// return the found entry
return Some(item as usize);
} | conditional_block |
xsdt.rs | //! Extended System Description Table
use core::mem;
use super::sdt::Sdt;
/// XSDT structure
#[derive(Debug)]
pub struct Xsdt(&'static Sdt);
impl Xsdt {
/// Cast SDT to XSDT if signature matches.
pub fn new(sdt: &'static Sdt) -> Option<Self> {
if &sdt.signature == b"XSDT" {
Some(Xsdt(sdt... | (&self) -> XsdtIter {
XsdtIter {
sdt: self.0,
index: 0
}
}
}
/// XSDT as an array of 64-bit physical addresses that point to other DESCRIPTION_HEADERs. So we use
/// an iterator to walk through it.
pub struct XsdtIter {
sdt: &'static Sdt,
index: usize
}
impl Iterato... | iter | identifier_name |
http_challenge_cache.py | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import threading
try:
import urllib.parse as parse
except ImportError:
import urlparse as parse # type: ignore
try:
from typing import TYPE_CHECKING
excep... |
def _get_cache_key(url):
"""Use the URL's netloc as cache key except when the URL specifies the default port for its scheme. In that case
use the netloc without the port. That is to say, https://foo.bar and https://foo.bar:443 are considered equivalent.
This equivalency prevents an unnecessary challenge... | """ Gets the challenge for the cached URL.
:param url: the URL the challenge is cached for.
:rtype: HttpBearerChallenge """
if not url:
raise ValueError("URL cannot be None")
key = _get_cache_key(url)
with _lock:
return _cache.get(key) | identifier_body |
http_challenge_cache.py | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import threading
try:
import urllib.parse as parse
except ImportError:
import urlparse as parse # type: ignore
try:
from typing import TYPE_CHECKING
excep... |
url = parse.urlparse(url)
with _lock:
del _cache[url.netloc]
def set_challenge_for_url(url, challenge):
""" Caches the challenge for the specified URL.
:param url: the URL for which to cache the challenge
:param challenge: the challenge to cache """
if not url:
raise ValueEr... | raise ValueError("URL cannot be empty") | conditional_block |
http_challenge_cache.py | # ------------------------------------
# Copyright (c) Microsoft Corporation. | import threading
try:
import urllib.parse as parse
except ImportError:
import urlparse as parse # type: ignore
try:
from typing import TYPE_CHECKING
except ImportError:
TYPE_CHECKING = False
if TYPE_CHECKING:
# pylint: disable=unused-import
from typing import Dict
from .http_challenge im... | # Licensed under the MIT License.
# ------------------------------------ | random_line_split |
http_challenge_cache.py | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import threading
try:
import urllib.parse as parse
except ImportError:
import urlparse as parse # type: ignore
try:
from typing import TYPE_CHECKING
excep... | (url):
"""Use the URL's netloc as cache key except when the URL specifies the default port for its scheme. In that case
use the netloc without the port. That is to say, https://foo.bar and https://foo.bar:443 are considered equivalent.
This equivalency prevents an unnecessary challenge when using Key Vault... | _get_cache_key | identifier_name |
models.py | #!/usr/bin/env python
# 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 (the
# "License"); you ma... | (name='Browse', description='', is_saved=False, snippets=None):
from notebook.connectors.hiveserver2 import HS2Api
editor = Notebook()
_snippets = []
for snippet in snippets:
default_properties = {
'files': [],
'functions': [],
'settings': []
}
if snippet['type'] == 'hiv... | make_notebook2 | identifier_name |
models.py | #!/usr/bin/env python
# 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 (the
# "License"); you ma... |
def _update_property_value(properties, key, value):
"""
Update property dict in list of properties where prop has "key": key, set "value": value
"""
for prop in properties:
if prop['key'] == key:
prop.update({'value': value})
| from beeswax.models import HQL, IMPALA, RDBMS, SPARK
if btype == HQL:
return 'hive'
elif btype == IMPALA:
return 'impala'
elif btype == RDBMS:
data = json.loads(bdata)
return data['query']['server']
elif btype == SPARK: # We should not import
return 'spark'
else:
return 'hive' | identifier_body |
models.py | #!/usr/bin/env python
# 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 (the
# "License"); you ma... | 'description': description,
'sessions': [
{
'type': _snippet['type'],
'properties': HS2Api.get_properties(snippet['type']),
'id': None
} for _snippet in _snippets # Non unique types currently
],
'selectedSnippet': _snippets[0]['type'],
'type': 'notebook',
'... | data = {
'name': name,
'uuid': str(uuid.uuid4()), | random_line_split |
models.py | #!/usr/bin/env python
# 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 (the
# "License"); you ma... |
data.append(escaped_row)
return data
def make_notebook(name='Browse', description='', editor_type='hive', statement='', status='ready',
files=None, functions=None, settings=None, is_saved=False, database='default', snippet_properties=None):
from notebook.connectors.hiveserver2 import HS2A... | if isinstance(field, numbers.Number):
if math.isnan(field) or math.isinf(field):
escaped_field = json.dumps(field)
else:
escaped_field = field
elif field is None:
escaped_field = 'NULL'
else:
escaped_field = smart_unicode(field, errors='replace') # Prevent... | conditional_block |
fix_intern.py | # Copyright 2006 Georg Brandl.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for intern().
intern(s) -> sys.intern(s)"""
# Local imports
from .. import pytree
from .. import fixer_base
from ..fixer_util import Name, Attr, touch_import
class FixIntern(fixer_base.BaseFix):
BM_compatible... |
new = pytree.Node(syms.power,
Attr(Name(u"sys"), Name(u"intern")) +
[pytree.Node(syms.trailer,
[results["lpar"].clone(),
newarglist,
r... | after = [n.clone() for n in after] | conditional_block |
fix_intern.py | # Copyright 2006 Georg Brandl.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for intern().
intern(s) -> sys.intern(s)"""
# Local imports
from .. import pytree
from .. import fixer_base
from ..fixer_util import Name, Attr, touch_import
class FixIntern(fixer_base.BaseFix):
BM_compatible... | (self, node, results):
syms = self.syms
obj = results["obj"].clone()
if obj.type == syms.arglist:
newarglist = obj.clone()
else:
newarglist = pytree.Node(syms.arglist, [obj.clone()])
after = results["after"]
if after:
after = [... | transform | identifier_name |
fix_intern.py | # Copyright 2006 Georg Brandl.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for intern().
intern(s) -> sys.intern(s)"""
# Local imports
from .. import pytree
from .. import fixer_base
from ..fixer_util import Name, Attr, touch_import
class FixIntern(fixer_base.BaseFix):
BM_compatible... | newarglist = pytree.Node(syms.arglist, [obj.clone()])
after = results["after"]
if after:
after = [n.clone() for n in after]
new = pytree.Node(syms.power,
Attr(Name(u"sys"), Name(u"intern")) +
[pytree.Node(syms.trai... | random_line_split | |
fix_intern.py | # Copyright 2006 Georg Brandl.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for intern().
intern(s) -> sys.intern(s)"""
# Local imports
from .. import pytree
from .. import fixer_base
from ..fixer_util import Name, Attr, touch_import
class FixIntern(fixer_base.BaseFix):
BM_compatible... | syms = self.syms
obj = results["obj"].clone()
if obj.type == syms.arglist:
newarglist = obj.clone()
else:
newarglist = pytree.Node(syms.arglist, [obj.clone()])
after = results["after"]
if after:
after = [n.clone() for n in after]
... | identifier_body | |
hierarchical.js | /* @flow */
import * as React from "react";
import { nest } from "d3-collection";
import { scaleLinear } from "d3-scale";
import TooltipContent from "../tooltip-content";
const parentPath = (d, pathArray) => {
if (d.parent) {
pathArray = parentPath(d.parent, [d.key, ...pathArray]);
} else {
pathArray = ["r... | tooltipContent: (d: Object) => {
return (
<TooltipContent>
{hierarchicalTooltip(d, primaryKey, metric1)}
</TooltipContent>
);
}
};
}; | margin: { left: 100, right: 100, top: 10, bottom: 10 },
hoverAnnotation: true, | random_line_split |
hierarchical.js | /* @flow */
import * as React from "react";
import { nest } from "d3-collection";
import { scaleLinear } from "d3-scale";
import TooltipContent from "../tooltip-content";
const parentPath = (d, pathArray) => {
if (d.parent) {
pathArray = parentPath(d.parent, [d.key, ...pathArray]);
} else {
pathArray = ["r... |
const lightenScale = scaleLinear()
.domain([6, 1])
.clamp(true)
.range(["white", colorHash[colorNode.key]]);
return lightenScale(d.depth);
};
export const semioticHierarchicalChart = (
data: Array<Object>,
schema: Object,
options: Object
) => {
const {
hierarchyType = "dendrogram",
ch... | {
colorNode = colorNode.parent;
} | conditional_block |
app.js | /*
*
* Copyright (c) 2015 Daniel D. Bruce
*
* This file is part of thermopi.
*
* thermopi 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 version 3 of the License, or
* (at your option) any later ver... |
setInterval(function() {
checktemp(function(temp) {
var differential = (status == 0) ? differential_on : differential_off;
console.log("Status: " + status);
console.log("Differential: " + differential);
var setpoint = findsetpoint();
console.log("Setpoint: " + setpoint);
toggleheat(temp <= setpoint - dif... | {
status = setting ? "1" : "0";
status.to(togglelocation);
console.log("Heat status: " + status);
} | identifier_body |
app.js | /*
*
* Copyright (c) 2015 Daniel D. Bruce
*
* This file is part of thermopi.
*
* thermopi 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 version 3 of the License, or
* (at your option) any later ver... |
}
console.log("using week");
return setpoint;
}
function toggleheat(setting) {
status = setting ? "1" : "0";
status.to(togglelocation);
console.log("Heat status: " + status);
}
setInterval(function() {
checktemp(function(temp) {
var differential = (status == 0) ? differential_on : differential_off;
conso... | {
yesterday_setpoints = week.days[(now.day()+6)%7].setpoints;
setpoint = yesterday_setpoints[yesterday_setpoints.length-1].temp;
console.log("using week (yesterday's last temp)");
return setpoint;
} | conditional_block |
app.js | /*
*
* Copyright (c) 2015 Daniel D. Bruce
*
* This file is part of thermopi.
*
* thermopi 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 version 3 of the License, or
* (at your option) any later ver... | data = parseFloat(data);
data /= 1000;
data *= 9/5;
data += 32;
data /= fudgefactor;
data = data.toFixed(1);
console.log("Current temp: " + data);
callback(data);
})
}
});
}
function findsetpoint() {
setpoint = 50;
setpoint_set = false;
var hold = JSON.parse(fs.readFileSync('./... | fs.readFile(files[0], function(error, data) {
data = data.toString().substr(data.length-6,5); | random_line_split |
app.js | /*
*
* Copyright (c) 2015 Daniel D. Bruce
*
* This file is part of thermopi.
*
* thermopi 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 version 3 of the License, or
* (at your option) any later ver... | (callback) {
glob("/sys/bus/w1/devices/28-*/w1_slave", function(er, files) {
if (files.length > 0) {
fs.readFile(files[0], function(error, data) {
data = data.toString().substr(data.length-6,5);
data = parseFloat(data);
data /= 1000;
data *= 9/5;
data += 32;
data /= fudgefactor;
data =... | checktemp | identifier_name |
sr-Latn-BA.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number... | ['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'], 'KM',
'Bosansko-hercegovačka konvertibilna marka', {
'AUD': [, '$'],
'BAM': ['KM'],
'BYN': [, 'r.'],
'GEL': [, 'ლ'],
'KRW': [, '₩'],
'NZD': [, '$'],
'TWD': ['NT$'],
'USD': ['US$', '$'],
'VND': [, '₫']
},
plural
]; | '{1} {0}',
,
,
],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], | random_line_split |
sr-Latn-BA.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function | (n: number): number {
return 5;
}
export default [
'sr-Latn-BA',
[
['a', 'p'],
['prije podne', 'po podne'],
],
,
[
['n', 'p', 'u', 's', 'č', 'p', 's'], ['ned.', 'pon.', 'ut.', 'sr.', 'čet.', 'pet.', 'sub.'],
['nedjelja', 'ponedeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'],
... | plural | identifier_name |
sr-Latn-BA.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number... |
export default [
'sr-Latn-BA',
[
['a', 'p'],
['prije podne', 'po podne'],
],
,
[
['n', 'p', 'u', 's', 'č', 'p', 's'], ['ned.', 'pon.', 'ut.', 'sr.', 'čet.', 'pet.', 'sub.'],
['nedjelja', 'ponedeljak', 'utorak', 'srijeda', 'četvrtak', 'petak', 'subota'],
['ne', 'po', 'ut', 'sr', 'če', 'pe... | {
return 5;
} | identifier_body |
emulation.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use serde_json::{Map, Value};
use std::net::TcpStream;
pub... | (name: String) -> EmulationActor {
EmulationActor { name: name }
}
}
| new | identifier_name |
emulation.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 actor::{Actor, ActorMessageStatus, ActorRegistry};
use serde_json::{Map, Value};
use std::net::TcpStream;
pub... |
}
impl EmulationActor {
pub fn new(name: String) -> EmulationActor {
EmulationActor { name: name }
}
}
| {
Ok(match msg_type {
_ => ActorMessageStatus::Ignored,
})
} | identifier_body |
emulation.rs |
use actor::{Actor, ActorMessageStatus, ActorRegistry};
use serde_json::{Map, Value};
use std::net::TcpStream;
pub struct EmulationActor {
pub name: String,
}
impl Actor for EmulationActor {
fn name(&self) -> String {
self.name.clone()
}
fn handle_message(
&self,
_registry: &A... | /* 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/. */ | random_line_split | |
AndroidNotification.js | var Notification = require('./Notification');
var AndroidNotification = Notification.extend({ | 'body': {
'ticker': '',
'title': '',
'text': '',
// 'icon': '',
// 'largeIcon': '',
'play_vibrate': 'true',
'play_lights': 'true',
'play_sound': 'true',
'after_open': '',
// 'url': '',
// 'activity': '',
// 'custom': ''
},
// 'extra': {
// 'foo': 'bar'
// }
},
initializ... |
// the array for payload, please see API doc for more information
_androidPayload: {
'display_type': 'notification', | random_line_split |
slope.py | #!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
import numpy as np
import sys
import scipy
from scipy import stats
data_file = sys.argv[1]
data = np.loadtxt(data_file)
slope, intercept, r_value, p_value, std_err = stats.linregress(data[499:2499,0], data[499:2499,1])
nf = open('linear_reg.dat', 'w')
... |
nf.close() | nf.write('Diffusion coeff: %10.5E m^2 s^-1$ \n' %(slope*10**(-8)/6.0)) | random_line_split |
theme.rs | use crate::color::{LinSrgba, Srgba};
use std::collections::HashMap;
/// A set of styling defaults used for coloring texturing geometric primitives that have no entry
/// within the **Draw**'s inner **ColorMap**.
#[derive(Clone, Debug)]
pub struct Theme {
/// Fill color defaults.
pub fill_color: Color,
/// ... | .get(prim)
.map(|&c| c)
.unwrap_or(self.fill_color.default)
}
/// Retrieve the linaer sRGBA fill color representation for the given primitive.
pub fn fill_lin_srgba(&self, prim: &Primitive) -> LinSrgba {
self.fill_srgba(prim).into_linear()
}
/// Retrieve... | .primitive | random_line_split |
theme.rs | use crate::color::{LinSrgba, Srgba};
use std::collections::HashMap;
/// A set of styling defaults used for coloring texturing geometric primitives that have no entry
/// within the **Draw**'s inner **ColorMap**.
#[derive(Clone, Debug)]
pub struct Theme {
/// Fill color defaults.
pub fill_color: Color,
/// ... |
/// Retrieve the linaer sRGBA stroke color representation for the given primitive.
pub fn stroke_lin_srgba(&self, prim: &Primitive) -> LinSrgba {
self.stroke_srgba(prim).into_linear()
}
}
impl Default for Theme {
fn default() -> Self {
// TODO: This should be pub const.
let de... | {
self.stroke_color
.primitive
.get(prim)
.map(|&c| c)
.unwrap_or(self.stroke_color.default)
} | identifier_body |
theme.rs | use crate::color::{LinSrgba, Srgba};
use std::collections::HashMap;
/// A set of styling defaults used for coloring texturing geometric primitives that have no entry
/// within the **Draw**'s inner **ColorMap**.
#[derive(Clone, Debug)]
pub struct Theme {
/// Fill color defaults.
pub fill_color: Color,
/// ... | (&self, prim: &Primitive) -> Srgba {
self.stroke_color
.primitive
.get(prim)
.map(|&c| c)
.unwrap_or(self.stroke_color.default)
}
/// Retrieve the linaer sRGBA stroke color representation for the given primitive.
pub fn stroke_lin_srgba(&self, prim: &... | stroke_srgba | identifier_name |
ToDoCollectionView.js | define([
'utils/Config',
'utils/Debug',
'utils/String',
'backbone',
'views/PageView',
'views/ToDoView',
'text!../../templates/PageView.container.html',
'text!../../templates/PageView.controls.html'
], function(
Config,
Debug,
StringUtil,
Backbone,
PageView,
ToDoVi... | var self = this;
this.collection.bind('add', function() {
new ToDoView({
model : self.collection.at(self.collection.length-1),
parent : self
}).render();
});
this.on(Config.event.ADD_RANDOM_TASK, f... |
/**
*
*/
initialize : function() { | random_line_split |
functions_68.js | ['hglrc',['HGLRC',['../wglew_8h.html#a79abb55a8f5ce093fad0358132a376e4',1,'wglew.h']]],
['hpbufferarb',['HPBUFFERARB',['../wglew_8h.html#a90ca6f3efc25075502afda6d38df143b',1,'wglew.h']]],
['hpbufferext',['HPBUFFEREXT',['../wglew_8h.html#a9a3e24dd9ba635197a508013c122d1d1',1,'wglew.h']]]
]; | var searchData=
[
['handle',['HANDLE',['../wglew_8h.html#aa1efb7b85228601549d183556de19dfc',1,'wglew.h']]],
['hdc',['HDC',['../wglew_8h.html#a7b84f5391331438359747d138a86ffe3',1,'wglew.h']]], | random_line_split | |
open.js | /**
* Opens provided file in browser.
*
* • Tabs should be opened using the terminal via this task. Doing
* so will ensure the generated tab will auto-close when Gulp is
* closed. Opening tabs by typing/copy-pasting the project URL
* into the browser address bar will not auto-close the tab(s)
* due to se... | lse {
// Else open the file in a browser. Which is what this task was
// originally set out to do.
// Run yargs.
__flags = yargs
.option("file", {
alias: "F",
type: "string",
demandOption: true
})
.option("port", {
alias: "p",
type: "number"
}).argv;
// Get flag values.
var... | // If the editor flag is provided open the given file in the user's
// default editor.
var spawn = require("child_process").spawn;
// Check that the file exists.
if (!fe.sync(editor)) {
print.gulp.warn(
"The file",
chalk.magenta(directory),
"does not exist."
);
return done();
}
// ... | conditional_block |
open.js | /**
* Opens provided file in browser.
*
* • Tabs should be opened using the terminal via this task. Doing
* so will ensure the generated tab will auto-close when Gulp is
* closed. Opening tabs by typing/copy-pasting the project URL
* into the browser address bar will not auto-close the tab(s)
* due to se... |
// Check that the file exists.
if (!fe.sync(editor)) {
print.gulp.warn(
"The file",
chalk.magenta(directory),
"does not exist."
);
return done();
}
// Run yargs.
__flags = yargs
.option("wait", {
alias: "w",
type: "boolean"
})
.option("line", {
alias: "l",
type:... | } else if (editor) {
// If the editor flag is provided open the given file in the user's
// default editor.
var spawn = require("child_process").spawn; | random_line_split |
rx.async.min.js | /* */
"format cjs";
(function(a) {
var b = {
"boolean": !1,
"function": !0,
object: !0,
number: !1,
string: !1,
undefined: !1
},
c = b[typeof window] && window || this,
d = b[typeof exports] && exports && !exports.nodeType && exports,
e = b[typeof module] && module && !mod... | }, function(c) {
a.off(b, c);
}, d);
};
var C = o.fromEventPattern = function(a, b, c) {
return new r(function(d) {
function e(a) {
var b = a;
if (c)
try {
b = c(arguments);
} catch (e) {
return d.onError(e);
}
d.o... | c.onNext(b);
});
}).publish().refCount() : C(function(c) {
a.on(b, c); | random_line_split |
rx.async.min.js | /* */
"format cjs";
(function(a) {
var b = {
"boolean": !1,
"function": !0,
object: !0,
number: !1,
string: !1,
undefined: !1
},
c = b[typeof window] && window || this,
d = b[typeof exports] && exports && !exports.nodeType && exports,
e = b[typeof module] && module && !mod... |
});
} catch (g) {
f = !0, c(g);
}
}
var f,
g = Object.keys(a),
h = g.length,
i = new a.constructor;
if (!h)
return void v.schedule(function() {
c(null, i);
});
for (var j = 0,
k = g.len... | {
if (a)
return f = !0, c(a);
i[d] = b, --h || c(null, i);
} | conditional_block |
rx.async.min.js | /* */
"format cjs";
(function(a) {
var b = {
"boolean": !1,
"function": !0,
object: !0,
number: !1,
string: !1,
undefined: !1
},
c = b[typeof window] && window || this,
d = b[typeof exports] && exports && !exports.nodeType && exports,
e = b[typeof module] && module && !mod... | (a) {
var b = a;
if (c)
try {
b = c(arguments);
} catch (e) {
return d.onError(e);
}
d.onNext(b);
}
var f = a(e);
return t(function() {
b && b(e, f);
});
}).publish().refCount();
};
return o.startAsync ... | e | identifier_name |
rx.async.min.js | /* */
"format cjs";
(function(a) {
var b = {
"boolean": !1,
"function": !0,
object: !0,
number: !1,
string: !1,
undefined: !1
},
c = b[typeof window] && window || this,
d = b[typeof exports] && exports && !exports.nodeType && exports,
e = b[typeof module] && module && !mod... |
e.push(f), a.apply(b, e);
}).publishLast().refCount();
};
}, c.config.useNativeEvents = !1, o.fromEvent = function(a, b, d) {
return a.addListener ? C(function(c) {
a.addListener(b, c);
}, function(c) {
a.removeListener(b, c);
}, d) : c.config.useNativeEvents || "function" !... | {
if (a)
return void d.onError(a);
for (var e = arguments.length,
f = [],
g = 1; e > g; g++)
f[g - 1] = arguments[g];
if (c) {
try {
f = c.apply(b, f);
} catch (h) {
return d.onError(h);... | identifier_body |
acquire.py | """Bootstrap"""
from __future__ import absolute_import, unicode_literals
import logging
import os
import sys
from operator import eq, lt
from virtualenv.util.path import Path
from virtualenv.util.six import ensure_str
from virtualenv.util.subprocess import Popen, subprocess
from .bundle import from_bundle
from .util... |
elif version_spec.startswith("=="):
from_pos, op = 2, eq
else:
raise ValueError(version_spec)
version = Wheel.as_version_tuple(version_spec[from_pos:])
start = next((at for at, w in enumerate(wheels) if op(w.version_tuple, version)), len(wheels))
return None... | from_pos, op = 1, lt | conditional_block |
acquire.py | """Bootstrap"""
from __future__ import absolute_import, unicode_literals
import logging
import os
import sys
from operator import eq, lt
from virtualenv.util.path import Path
from virtualenv.util.six import ensure_str
from virtualenv.util.subprocess import Popen, subprocess
from .bundle import from_bundle
from .util... |
def pip_wheel_env_run(search_dirs, app_data):
for_py_version = "{}.{}".format(*sys.version_info[0:2])
env = os.environ.copy()
env.update(
{
ensure_str(k): str(v) # python 2 requires these to be string only (non-unicode)
for k, v in {"PIP_USE_WHEEL": "1", "PIP_USER": "0", ... | wheels = discover_wheels(in_folder, distribution, None, for_py_version)
start, end = 0, len(wheels)
if version_spec is not None:
if version_spec.startswith("<"):
from_pos, op = 1, lt
elif version_spec.startswith("=="):
from_pos, op = 2, eq
else:
raise ... | identifier_body |
acquire.py | """Bootstrap"""
from __future__ import absolute_import, unicode_literals
import logging
import os
import sys
from operator import eq, lt
from virtualenv.util.path import Path
from virtualenv.util.six import ensure_str
from virtualenv.util.subprocess import Popen, subprocess
from .bundle import from_bundle
from .util... | wheel = get_wheel(
distribution="pip",
version=None,
for_py_version=for_py_version,
search_dirs=search_dirs,
download=False,
app_data=app_data,
do_periodic_update=False,
)
if wheel is None:
raise RuntimeError("could not find the embedded pip")
... | {
ensure_str(k): str(v) # python 2 requires these to be string only (non-unicode)
for k, v in {"PIP_USE_WHEEL": "1", "PIP_USER": "0", "PIP_NO_INPUT": "1"}.items()
},
) | random_line_split |
acquire.py | """Bootstrap"""
from __future__ import absolute_import, unicode_literals
import logging
import os
import sys
from operator import eq, lt
from virtualenv.util.path import Path
from virtualenv.util.six import ensure_str
from virtualenv.util.subprocess import Popen, subprocess
from .bundle import from_bundle
from .util... | (distribution, version_spec, for_py_version, search_dirs, app_data, to_folder):
to_download = "{}{}".format(distribution, version_spec or "")
logging.debug("download wheel %s %s to %s", to_download, for_py_version, to_folder)
cmd = [
sys.executable,
"-m",
"pip",
"download",
... | download_wheel | identifier_name |
title.service.spec.ts | import {
inject,
TestBed
} from '@angular/core/testing';
import { Component } from '@angular/core';
import {
BaseRequestOptions,
ConnectionBackend,
Http
} from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { Title } from './title.service';
describe('Title', () => {
beforeEac... | useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
},
Title
]}));
it('should have http', inject([ Title ], (title: Title) => {
expect(!!title.... | {
provide: Http, | random_line_split |
errors.rs | // ------------------------------------------------------------------------- //
// Imports //
// ------------------------------------------------------------------------- //
// Standard libraries imports
use std::process;
use std::result::Result as StdR... |
// ------------------------------------------------------------------------- //
// Traits //
// ------------------------------------------------------------------------- //
/// A fallible unwrap
pub trait Fallible<T> {
/// Return the value from Ok... | random_line_split | |
errors.rs | // ------------------------------------------------------------------------- //
// Imports //
// ------------------------------------------------------------------------- //
// Standard libraries imports
use std::process;
use std::result::Result as StdR... | (&self) {
let mut msg = self.message.clone();
match self.error {
None => (),
Some(_) => msg.push(':'),
}
stderr(&Red.paint(msg).to_string());
match self.error.clone() {
None => (),
Some(error) => stderr(&boxify(error, Red)),
... | print | identifier_name |
_screenshot.py | # -*- coding: utf-8 -*-
import os
import robot
from keywordgroup import KeywordGroup
class _ScreenshotKeywords(KeywordGroup):
def __init__(self):
self._screenshot_index = 0
# Public
def capture_page_screenshot(self, filename=None):
"""Takes a screenshot of the current page... |
else:
filename = filename.replace('/', os.sep)
logdir = self._get_log_dir()
path = os.path.join(logdir, filename)
link = robot.utils.get_link_path(path, logdir)
return path, link
| self._screenshot_index += 1
filename = 'appium-screenshot-%d.png' % self._screenshot_index | conditional_block |
_screenshot.py | # -*- coding: utf-8 -*-
import os
import robot
from keywordgroup import KeywordGroup
class | (KeywordGroup):
def __init__(self):
self._screenshot_index = 0
# Public
def capture_page_screenshot(self, filename=None):
"""Takes a screenshot of the current page and embeds it into the log.
`filename` argument specifies the name of the file to write the
scree... | _ScreenshotKeywords | identifier_name |
_screenshot.py | # -*- coding: utf-8 -*-
import os
import robot
from keywordgroup import KeywordGroup
class _ScreenshotKeywords(KeywordGroup):
def __init__(self):
self._screenshot_index = 0
# Public
def capture_page_screenshot(self, filename=None):
|
# Private
def _get_screenshot_paths(self, filename):
if not filename:
self._screenshot_index += 1
filename = 'appium-screenshot-%d.png' % self._screenshot_index
else:
filename = filename.replace('/', os.sep)
logdir = self._get_log_dir()
... | """Takes a screenshot of the current page and embeds it into the log.
`filename` argument specifies the name of the file to write the
screenshot into. If no `filename` is given, the screenshot is saved into file
`appium-screenshot-<counter>.png` under the directory where
the Robot ... | identifier_body |
_screenshot.py | # -*- coding: utf-8 -*-
import os
import robot
from keywordgroup import KeywordGroup
class _ScreenshotKeywords(KeywordGroup):
def __init__(self):
self._screenshot_index = 0
# Public
def capture_page_screenshot(self, filename=None):
"""Takes a screenshot of the current page... | # Private
def _get_screenshot_paths(self, filename):
if not filename:
self._screenshot_index += 1
filename = 'appium-screenshot-%d.png' % self._screenshot_index
else:
filename = filename.replace('/', os.sep)
logdir = self._get_log_dir()
... | random_line_split | |
index.ts | // | // PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING
//
// This file is providing the test runner to use when running extension tests.
// By default the test runner in use is Mocha based.
//
// You can provide your own test runner if you want to override it by exporting
// a function run(testRoot: string... | random_line_split | |
manage.py | #!/usr/bin/env python
from __future__ import with_statement, division, unicode_literals
import logging
import os
import sys
import unittest
from server import app
__package__ = 'server'
DEFAULT_HOST = '0.0.0.0'
DEFAULT_PORT = 8000
def run_tests():
suite = unittest.TestLoader().discover('.'.join([__package__, ... | sys.exit(main()) | conditional_block | |
manage.py | #!/usr/bin/env python
from __future__ import with_statement, division, unicode_literals
import logging
import os
import sys
import unittest
from server import app
__package__ = 'server'
DEFAULT_HOST = '0.0.0.0'
DEFAULT_PORT = 8000
def run_tests():
suite = unittest.TestLoader().discover('.'.join([__package__, ... |
def main(args=sys.argv[1:]):
logging.basicConfig(level='WARNING', format='%(asctime)s %(levelname)s:%(module)s:%(lineno)d:%(message)s')
args = parse_args(args)
# Call the function for the corresponding subparser
kwargs = vars(args)
function = kwargs.pop('function')
function(**kwargs)
if __... | from argparse import ArgumentParser
parser = ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands')
subparser = subparsers.add_parser('start', description="Start running a simple Matchmaker Exchange API server")
subparser.add_argument("-p", "--port", default=DEFAULT_PORT,
... | identifier_body |
manage.py | #!/usr/bin/env python
from __future__ import with_statement, division, unicode_literals
import logging
import os
import sys
import unittest
from server import app
__package__ = 'server'
DEFAULT_HOST = '0.0.0.0'
DEFAULT_PORT = 8000
def run_tests(): | def parse_args(args):
from argparse import ArgumentParser
parser = ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands')
subparser = subparsers.add_parser('start', description="Start running a simple Matchmaker Exchange API server")
subparser.add_argument("-p", "--port", default=... | suite = unittest.TestLoader().discover('.'.join([__package__, 'tests']))
unittest.TextTestRunner().run(suite)
| random_line_split |
manage.py | #!/usr/bin/env python
from __future__ import with_statement, division, unicode_literals
import logging
import os
import sys
import unittest
from server import app
__package__ = 'server'
DEFAULT_HOST = '0.0.0.0'
DEFAULT_PORT = 8000
def run_tests():
suite = unittest.TestLoader().discover('.'.join([__package__, ... | (args):
from argparse import ArgumentParser
parser = ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands')
subparser = subparsers.add_parser('start', description="Start running a simple Matchmaker Exchange API server")
subparser.add_argument("-p", "--port", default=DEFAULT_PORT,
... | parse_args | identifier_name |
schema-validation.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | if (errors !== null) {
for (const error of errors) {
config.Message({
Channel: Channel.Error,
Details: error,
Plugin: "schema-validator",
Source: [{ document: fileIn.key, Position: { path: parseJsonPointer(error.path) } as any }],
Text: `Schema violati... | return CreatePerFilePlugin(async config => async (fileIn, sink) => {
const obj = fileIn.ReadObject<any>();
const errors = await new Promise<{ code: string, params: string[], message: string, path: string }[] | null>(res => validator.validate(obj, extendedSwaggerSchema, (err, valid) => res(valid ? null : err))... | random_line_split |
schema-validation.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | {
const validator = new SchemaValidator({ breakOnFirstError: false });
const extendedSwaggerSchema = require("./swagger-extensions.json");
(validator as any).setRemoteReference("http://json.schemastore.org/swagger-2.0", require("./swagger.json"));
(validator as any).setRemoteReference("https://raw.githubuserco... | identifier_body | |
schema-validation.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return await sink.Forward(fileIn.Description, fileIn);
});
} | {
for (const error of errors) {
config.Message({
Channel: Channel.Error,
Details: error,
Plugin: "schema-validator",
Source: [{ document: fileIn.key, Position: { path: parseJsonPointer(error.path) } as any }],
Text: `Schema violation: ${error.message}`
... | conditional_block |
schema-validation.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): PipelinePlugin {
const validator = new SchemaValidator({ breakOnFirstError: false });
const extendedSwaggerSchema = require("./swagger-extensions.json");
(validator as any).setRemoteReference("http://json.schemastore.org/swagger-2.0", require("./swagger.json"));
(validator as any).setRemoteReference("https... | GetPlugin_SchemaValidator | identifier_name |
bootstrap-wysihtml5.sv-SE.js | /**
* Swedish translation for bootstrap-wysihtml5
*/
(function($){
$.fn.wysihtml5.locale["sv-SE"] = {
font_styles: {
normal: "Normal Text",
h1: "Rubrik 1",
h2: "Rubrik 2",
h3: "Rubrik 3"
},
emphasis: {
bold: "Fet",
ita... | gray: "Grå",
maroon: "Kastaniebrun",
red: "Röd",
purple: "Lila",
green: "Grön",
olive: "Olivgrön",
navy: "Marinblå",
blue: "Blå",
orange: "Orange"
}
};
}(jQuery)); | },
colours: {
black: "Svart",
silver: "Silver", | 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
// https://w3c.github.io/uievents/#widl-UIEvent-detail
fn Detail(&self) -> i32 {
self.detail.get()
}
// https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent
fn InitUIEvent(
&self,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Optio... | {
self.view.get()
} | identifier_body |
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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... |
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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Option<&Window>,
detail: i32,
) {
let event = self.upcast::<Event>();
if event.dispatching() {
return;
}
event.init_event(Atom::from(type_), can_bubble, cancelable);
... | fn InitUIEvent(
&self, | 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindi... | (
&self,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
view: Option<&Window>,
detail: i32,
) {
let event = self.upcast::<Event>();
if event.dispatching() {
return;
}
event.init_event(Atom::from(type_), can_bubble, c... | InitUIEvent | identifier_name |
main.rs | // Crypto challenge Set1 / Challenge 1
// Convert hex to base64
extern crate codec;
#[cfg(not(test))]
fn main() |
#[test]
fn challenge1() {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let output = codec::to_base64( codec::from_hex(input).ok().unwrap().as_slice() );
assert_eq!(output, String::from_str("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub... | {
let args = std::os::args();
if args.len() != 2 {
println!("USAGE: challenge1 HEX_ENCODED_STRING");
} else {
let input = args[1].as_slice();
match codec::from_hex(input) {
Err(msg) => println!("Invalid hex string: {}", msg),
Ok(binary) => println!("{}", ... | identifier_body |
main.rs | // Crypto challenge Set1 / Challenge 1
// Convert hex to base64
extern crate codec;
#[cfg(not(test))]
fn main() {
let args = std::os::args();
if args.len() != 2 {
println!("USAGE: challenge1 HEX_ENCODED_STRING");
} else {
let input = args[1].as_slice();
match codec::from_hex(i... | #[test]
fn challenge1() {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let output = codec::to_base64( codec::from_hex(input).ok().unwrap().as_slice() );
assert_eq!(output, String::from_str("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3V... | }
}
}
| random_line_split |
main.rs | // Crypto challenge Set1 / Challenge 1
// Convert hex to base64
extern crate codec;
#[cfg(not(test))]
fn main() {
let args = std::os::args();
if args.len() != 2 {
println!("USAGE: challenge1 HEX_ENCODED_STRING");
} else {
let input = args[1].as_slice();
match codec::from_hex(i... | () {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let output = codec::to_base64( codec::from_hex(input).ok().unwrap().as_slice() );
assert_eq!(output, String::from_str("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"));
}
| challenge1 | identifier_name |
__manifest__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo RTL support
# Copyright (C) 2016 Mohammed Barsi.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# publ... | Adding RTL (Right to Left) Support for Odoo.
===========================================
This module provides a propper RTL support for Odoo.
""",
'depends': ['web'],
'auto_install': False,
'data': [
'views/templates.xml',
],
} | 'category': 'Usability',
'summary': 'Web RTL (Right to Left) layout',
'description':
""" | random_line_split |
zinc_compile.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import tex... | (self, target):
return target.has_sources('.java') or target.has_sources('.scala')
def select_source(self, source_file_path):
return source_file_path.endswith('.java') or source_file_path.endswith('.scala')
def __init__(self, *args, **kwargs):
super(ZincCompile, self).__init__(*args, **kwargs)
# ... | select | identifier_name |
zinc_compile.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import tex... | from pants.backend.jvm.tasks.jvm_compile.analysis_tools import AnalysisTools
from pants.backend.jvm.tasks.jvm_compile.jvm_compile import JvmCompile
from pants.backend.jvm.tasks.jvm_compile.scala.zinc_analysis import ZincAnalysis
from pants.backend.jvm.tasks.jvm_compile.scala.zinc_analysis_parser import ZincAnalysisPars... | from pants.backend.jvm.subsystems.scala_platform import ScalaPlatform
from pants.backend.jvm.subsystems.shader import Shader
from pants.backend.jvm.targets.jar_dependency import JarDependency | random_line_split |
zinc_compile.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import tex... | self.context.log.debug('Calling zinc on: {} ({})'
.format(analysis_file,
hash_file(analysis_file).upper()
if os.path.exists(analysis_file)
else 'nonexistent')) | identifier_body | |
zinc_compile.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import tex... |
except KeyError:
pass
unresolved_plugins = plugin_names - set(plugins.keys())
if unresolved_plugins:
raise TaskError('Could not find requested plugins: {}'.format(list(unresolved_plugins)))
return plugins
def extra_products(self, target):
"""Override extra_products to produc... | if name in plugins:
raise TaskError('Plugin {} defined in {} and in {}'.format(name, plugins[name], jar))
# It's important to use relative paths, as the compiler flags get embedded in the zinc
# analysis file, and we port those between systems via the artifact cache.
pl... | conditional_block |
benchmark_qt_rx2.py | #!/usr/bin/env python
#
# Copyright 2010 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 version 3, or (at your option)
... |
def rx_gain_clock(self):
return self._gain_clock
def rx_gain_clock_beta(self):
return self._gain_clock_beta
def set_rx_gain_clock(self, gain):
self._gain_clock = gain
self._gain_clock_beta = .25 * self._gain_clock * self._gain_clock
self.rxpath.packet_receiver._de... | return self._decim | identifier_body |
benchmark_qt_rx2.py | #!/usr/bin/env python
#
# Copyright 2010 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 version 3, or (at your option)
... |
(options, args) = parser.parse_args ()
if len(args) != 0:
parser.print_help(sys.stderr)
sys.exit(1)
if options.rx_freq is None:
sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
parser.print_help(sys.stderr)
sys.exit(1)
# build the graph
tb =... | mod.add_options(expert_grp) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.