file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
mode_keys_test.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self):
with self.assertRaisesRegexp(ValueError, 'Multiple keys/values found'):
_ = mode_keys.ModeKeyMap(**{
mode_keys.KerasModeKeys.PREDICT: 3,
mode_keys.EstimatorModeKeys.PREDICT: 1
})
if __name__ == '__main__':
test.main()
| test_invalid_init | identifier_name |
mode_keys_test.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | self.assertEqual(
{mode_keys.KerasModeKeys.TEST, mode_keys.KerasModeKeys.PREDICT},
set(mode_map.keys()))
# Map is immutable
with self.assertRaises(TypeError):
mode_map[mode_keys.KerasModeKeys.TEST] = 1
def test_invalid_init(self):
with self.assertRaisesRegexp(ValueError, 'Mult... | mode_map = mode_keys.ModeKeyMap(**{
mode_keys.KerasModeKeys.PREDICT: 3,
mode_keys.KerasModeKeys.TEST: 1
})
# Test dictionary __getitem__
self.assertEqual(3, mode_map[mode_keys.KerasModeKeys.PREDICT])
self.assertEqual(3, mode_map[mode_keys.EstimatorModeKeys.PREDICT])
self.assertEqual... | identifier_body |
mode_keys_test.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | self.assertLen(mode_map, 2)
self.assertEqual({1, 3}, set(mode_map.values()))
self.assertEqual(
{mode_keys.KerasModeKeys.TEST, mode_keys.KerasModeKeys.PREDICT},
set(mode_map.keys()))
# Map is immutable
with self.assertRaises(TypeError):
mode_map[mode_keys.KerasModeKeys.TEST] = ... |
# Test common dictionary methods | random_line_split |
mode_keys_test.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | test.main() | conditional_block | |
compare.py | # ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# 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.o... |
assert test_iterator() == test_loader()
| parser = NeonArgparser(__doc__)
args = parser.parse_args()
train_dir = os.path.join(args.data_dir, 'macrotrain')
test_dir = os.path.join(args.data_dir, 'macrotest')
write_batches(args, train_dir, trainimgs, 0)
write_batches(args, test_dir, testimgs, 1)
train = ImageLoader(set_name='train', do_t... | identifier_body |
compare.py | # ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# 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.o... | path = os.path.join(basepath, datadir)
if not os.path.exists(path):
process(basepath)
subdirs = glob(os.path.join(path, '*'))
labelnames = sorted(map(lambda x: os.path.basename(x), subdirs))
inds = range(len(labelnames))
labeldict = {key: val for key, val in zip(labelnames, inds)}
li... | random_line_split | |
compare.py | # ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# 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.o... | (inputpath):
(X_train, y_train), (X_test, y_test), nclass = load_cifar10(inputpath,
normalize=False)
process_dataset(X_train, y_train, inputpath, trainimgs)
process_dataset(X_test, y_test, inputpath, testimgs)
def load_dataset(basepath, datad... | process | identifier_name |
compare.py | # ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# 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.o... |
print('Writing batches to %s' % macrodir)
bw = BatchWriter(out_dir=macrodir,
image_dir=os.path.join(args.data_dir, datadir),
target_size=32, macro_size=1024,
file_pattern='*.jpg', validation_pct=val_pct)
bw.run()
def run(args, train, test):
... | return | conditional_block |
camera-helper.ts | -geo/geometry/picking';
import { GraphicsRenderObject } from '../../mol-gl/render-object';
import { Scene } from '../../mol-gl/scene';
import { WebGLContext } from '../../mol-gl/webgl/context';
import { GraphicsRenderVariantsBlended } from '../../mol-gl/webgl/render-item';
import { Sphere3D } from '../../mol-math/geome... | export function isCameraAxesLoci(x: Loci): x is CameraAxesLoci {
return x.kind === 'data-loci' && x.tag === 'camera-axes';
}
function updateCamera(camera: Camera, viewport: Viewport, viewOffset: Camera.ViewOffset) {
const { near, far } = camera;
const fullLeft = -viewport.width / 2;
const fullRight = ... | }
export type CameraAxesLoci = ReturnType<typeof CameraAxesLoci> | random_line_split |
camera-helper.ts | 0.1, max: 2, step: 0.1 }, { isEssential: true }),
};
type AxesParams = typeof AxesParams
type AxesProps = PD.Values<AxesParams>
export const CameraHelperParams = {
axes: PD.MappedStatic('on', {
on: PD.Group(AxesParams),
off: PD.Group({})
}, { cycle: true, description: 'Show camera orientation a... | {
const scale = 100 * props.scale;
const mesh = createAxesMesh(scale, shape?.geometry);
mesh.setBoundingSphere(Sphere3D.create(Vec3.create(scale / 2, scale / 2, scale / 2), scale + scale / 4));
const getColor = (groupId: number) => {
switch (groupId) {
case 1: return props.colorX;
... | identifier_body | |
camera-helper.ts | geo/geometry/picking';
import { GraphicsRenderObject } from '../../mol-gl/render-object';
import { Scene } from '../../mol-gl/scene';
import { WebGLContext } from '../../mol-gl/webgl/context';
import { GraphicsRenderVariantsBlended } from '../../mol-gl/webgl/render-item';
import { Sphere3D } from '../../mol-math/geomet... |
});
}
get isEnabled() {
return this.props.axes.name === 'on';
}
getLoci(pickingId: PickingId) {
const { objectId, groupId, instanceId } = pickingId;
if (!this.renderObject || objectId !== this.renderObject.id || groupId === CameraHelperAxis.None) return EmptyLoci;
... | {
p.axes.name = props.axes.name;
if (props.axes.name === 'on') {
this.scene.clear();
const params = { ...props.axes.params, scale: props.axes.params.scale * this.webgl.pixelRatio };
this.renderObject = createAxesRenderObject(par... | conditional_block |
camera-helper.ts | -geo/geometry/picking';
import { GraphicsRenderObject } from '../../mol-gl/render-object';
import { Scene } from '../../mol-gl/scene';
import { WebGLContext } from '../../mol-gl/webgl/context';
import { GraphicsRenderVariantsBlended } from '../../mol-gl/webgl/render-item';
import { Sphere3D } from '../../mol-math/geome... | (axis: number) {
switch (axis) {
case CameraHelperAxis.X: return 'X Axis';
case CameraHelperAxis.Y: return 'Y Axis';
case CameraHelperAxis.Z: return 'Z Axis';
case CameraHelperAxis.XY: return 'XY Plane';
case CameraHelperAxis.XZ: return 'XZ Plane';
case CameraHelperAx... | getAxisLabel | identifier_name |
openscad.py | import subprocess
import os
#from tailorscad.config import ScadConfig
BASE_DIR = '/usr/bin/'
DEFAULT = BASE_DIR + 'openscad'
def build_with_openscad(state):
args = build_args_from_state(state)
out_call = ''
for arg in args:
out_call += ' ' + arg
print 'args:', out_call
try:
... | (state):
#executable = ScadConfig.open_scad if ScadConfig.open_scad else DEFAULT
executable = 'openscad'
replace = []
if state.params:
print 'state params:', state.params
# TODO: Handle string exceptions
replace = ['-D ' + '='.join((key, str(value)))
for key,... | build_args_from_state | identifier_name |
openscad.py | import subprocess
import os
#from tailorscad.config import ScadConfig
BASE_DIR = '/usr/bin/'
DEFAULT = BASE_DIR + 'openscad'
def build_with_openscad(state):
args = build_args_from_state(state)
out_call = ''
for arg in args:
out_call += ' ' + arg
print 'args:', out_call
try:
... |
# TODO: Handle different output types
output = os.path.join(state.output_directory, state.name + ".stl")
args = [executable, '-o', output]
if len(replace) >= 1:
args.extend(replace)
args.append(state.main_path)
return args
| print 'state params:', state.params
# TODO: Handle string exceptions
replace = ['-D ' + '='.join((key, str(value)))
for key, value in state.params.iteritems()]
print 'state replace:', replace | conditional_block |
openscad.py | import subprocess
import os
#from tailorscad.config import ScadConfig
BASE_DIR = '/usr/bin/'
DEFAULT = BASE_DIR + 'openscad'
def build_with_openscad(state):
args = build_args_from_state(state)
out_call = ''
for arg in args:
out_call += ' ' + arg
print 'args:', out_call
try:
... |
args = [executable, '-o', output]
if len(replace) >= 1:
args.extend(replace)
args.append(state.main_path)
return args |
# TODO: Handle different output types
output = os.path.join(state.output_directory, state.name + ".stl") | random_line_split |
openscad.py | import subprocess
import os
#from tailorscad.config import ScadConfig
BASE_DIR = '/usr/bin/'
DEFAULT = BASE_DIR + 'openscad'
def build_with_openscad(state):
|
def build_args_from_state(state):
#executable = ScadConfig.open_scad if ScadConfig.open_scad else DEFAULT
executable = 'openscad'
replace = []
if state.params:
print 'state params:', state.params
# TODO: Handle string exceptions
replace = ['-D ' + '='.join((key, str(value)))... | args = build_args_from_state(state)
out_call = ''
for arg in args:
out_call += ' ' + arg
print 'args:', out_call
try:
subprocess.check_call(args)
return True
except subprocess.CalledProcessError as (e):
print str(e)
return False | identifier_body |
webpack.config.js | var path = require("path");
var webpack = require("webpack");
module.exports = function(entries, release) {
var config = {
// entry file to start from
entry: entries,
output: {
// directory to output to | plugins: [
/*
* This makes the left side variable available in every module and assigned to the right side module
*/
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"window.$": "jquery"
})
]
};
if (release) {
... | path: path.resolve("./lib"),
// output file name
filename: "[name].js"
}, | random_line_split |
webpack.config.js | var path = require("path");
var webpack = require("webpack");
module.exports = function(entries, release) {
var config = {
// entry file to start from
entry: entries,
output: {
// directory to output to
path: path.resolve("./lib"),
// output file name
filename: "[name].js"
},
... | else{
//config.devtool = 'cheap-eval-source-map';
}
return config;
};
| {
var uglify = new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {
screw_ie8: true,
keep_fnames: true
},
compress: {
screw_ie8: true
},
comments: false
});
config.plugins.push(uglify);
} | conditional_block |
abstract.py | # Types are added to a global registry (_typecache) in order to assign
# them unique integer codes for fast matching in _dispatcher.c.
# However, we also want types to be disposable, therefore we ensure
# each type is interned as a weak reference, so that it lives only as
# long as necessary to keep a stable type code.... | def __ne__(self, other):
return not (self == other)
def __reduce__(self):
reconstructor, args, state = super(Type, self).__reduce__()
return (_type_reconstructor, (reconstructor, args, state))
def unify(self, typingctx, other):
"""
Try to unify this type with the *o... | random_line_split | |
abstract.py | # Types are added to a global registry (_typecache) in order to assign
# them unique integer codes for fast matching in _dispatcher.c.
# However, we also want types to be disposable, therefore we ensure
# each type is interned as a weak reference, so that it lives only as
# long as necessary to keep a stable type code.... |
def is_precise(self):
"""
Whether this type is precise, i.e. can be part of a successful
type inference. Default implementation returns True.
"""
return True
def augment(self, other):
"""
Augment this type with the *other*. Return the augmented type,
... | """
Similar to *can_convert_to*, but in reverse. Only needed if
the type provides conversion from other types.
"""
return None | identifier_body |
abstract.py | Types are added to a global registry (_typecache) in order to assign
# them unique integer codes for fast matching in _dispatcher.c.
# However, we also want types to be disposable, therefore we ensure
# each type is interned as a weak reference, so that it lives only as
# long as necessary to keep a stable type code.
... |
class Callable(Type):
"""
Base class for callables.
"""
@abstractmethod
def get_call_type(self, context, args, kws):
"""
Using the typing *context*, resolve the callable's signature for
the given arguments. A signature object is returned, or None.
"""
@abstr... | a = numpy_support.as_dtype(self)
b = numpy_support.as_dtype(other)
sel = np.promote_types(a, b)
return numpy_support.from_dtype(sel) | conditional_block |
abstract.py | made immortal elsewhere (for example
# in _dispatcher.c's internal caches).
_typecodes = itertools.count()
def _autoincr():
n = next(_typecodes)
# 4 billion types should be enough, right?
assert n < 2 ** 32, "Limited to 4 billion types"
return n
_typecache = {}
def _on_type_disposal(wr, _pop=_typeca... | ndim | identifier_name | |
build.rs | use crowbook_intl::{Extractor, Localizer};
use std::env;
use std::path::Path;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=lang/fr.po");
// Extract and localize src/lib
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(conca... | let dest_path = Path::new(&env::var("OUT_DIR").unwrap()).join("localize_macros.rs");
localizer.write_macro_file(dest_path).unwrap();
// Extract and localize src/bin
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/bin"))
... | .add_lang(
"fr",
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/lib/fr.po")),
)
.unwrap(); | random_line_split |
build.rs | use crowbook_intl::{Extractor, Localizer};
use std::env;
use std::path::Path;
fn main() |
// Extract and localize src/bin
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/bin"))
.unwrap();
// Uncomment to update crowbook.pot
//extractor.write_pot_file(concat!(env!("CARGO_MANIFEST_DIR"), "/lang/bin/crowbook.p... | {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=lang/fr.po");
// Extract and localize src/lib
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/lib"))
.unwrap();
// Uncomment to update ... | identifier_body |
build.rs | use crowbook_intl::{Extractor, Localizer};
use std::env;
use std::path::Path;
fn | () {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=lang/fr.po");
// Extract and localize src/lib
let mut extractor = Extractor::new();
extractor
.add_messages_from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src/lib"))
.unwrap();
// Uncomment to upda... | main | identifier_name |
recorder.js | var url = 'http://localhost:8313';
var kTickInterval = 5000;
var kEmailRequired = false;
window.onload = kRefreshState;
var stateErrorDetails = {
'not ready': 'It looks like the "iGrabber Capture" application is not ' +
'running. Launch it from Applications > iGrabber Capture. (If it ' +
'is already running,... | {
if ($('#np3')[0].checked) {
$('#p4handle, #p4email').prop('disabled', true);
$('#p4handle, #p4email').val('');
} else {
$('#p4handle, #p4email').prop('disabled', false);
}
} | identifier_body | |
recorder.js | var url = 'http://localhost:8313';
var kTickInterval = 5000;
var kEmailRequired = false;
window.onload = kRefreshState;
var stateErrorDetails = {
'not ready': 'It looks like the "iGrabber Capture" application is not ' +
'running. Launch it from Applications > iGrabber Capture. (If it ' +
'is already running,... | $('input[type=text]').each(
function (_, e) { obj[e.id] = $(e).val(); });
npl = $('#np3')[0].checked ? 3 : 4;
obj['nplayers'] = npl;
obj['level'] =
$('#50cc')[0].checked ? '50cc' :
$('#100cc')[0].checked ? '100cc' :
$('#150cc')[0].checked ? '150cc' : 'unknown';
if (!obj['p1handle'] || !obj['... | function kStart()
{
var obj, npl, msg;
obj = {}; | random_line_split |
recorder.js | var url = 'http://localhost:8313';
var kTickInterval = 5000;
var kEmailRequired = false;
window.onload = kRefreshState;
var stateErrorDetails = {
'not ready': 'It looks like the "iGrabber Capture" application is not ' +
'running. Launch it from Applications > iGrabber Capture. (If it ' +
'is already running,... | ()
{
makeRequest('post', '/stop', {});
}
function kStart()
{
var obj, npl, msg;
obj = {};
$('input[type=text]').each(
function (_, e) { obj[e.id] = $(e).val(); });
npl = $('#np3')[0].checked ? 3 : 4;
obj['nplayers'] = npl;
obj['level'] =
$('#50cc')[0].checked ? '50cc' :
$('#100cc')[0].checked ... | kStop | identifier_name |
ShareThisForm.js | /**
* @file
* This file contains most of the code for the configuration page.
*/
// Create the drupal ShareThis object for clean code and namespacing:
var drupal_st = {
// These are handlerd for updating the widget pic class.
multiW: function() {
jQuery(".st_widgetPic").addClass("st_multi");
},
classicW: fun... | removeButtonClasses: function() {
var toRemove = jQuery("#stb_sprite");
toRemove.removeClass("stbc_");
toRemove.removeClass("stbc_large");
toRemove.removeClass("stbc_hcount");
toRemove.removeClass("stbc_vcount");
toRemove.removeClass("stbc_button");
},
//Write helper functions for saving:
getWidget: fun... | random_line_split | |
ShareThisForm.js | /**
* @file
* This file contains most of the code for the configuration page.
*/
// Create the drupal ShareThis object for clean code and namespacing:
var drupal_st = {
// These are handlerd for updating the widget pic class.
multiW: function() {
jQuery(".st_widgetPic").addClass("st_multi");
},
classicW: fun... |
outputString = outputString.substring(0, outputString.length-1);
jQuery("#edit-sharethis-service-option").attr("value", outputString);
}
};
//After the page is loaded, we want to add events to dynamically created elements.
jQuery(document).ready(drupal_st.addEvents);
//After it's all done, hide the text field for... | {
outputString += "\"" + _all_services[services[i]].title + ":"
outputString += services[i] + "\","
} | conditional_block |
simple_db.py | # Copyright (c) 2016, Kevin Rodgers
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
import redis |
UUID = 'uuid'
class SimpleRedisDb(object):
def __init__(self, host, key, port=6379):
"""
:param host: database host
:param port: database port default 6397
:param key: hash set name default active_mail_filter
"""
self.host = host
self.port = port
s... | from uuid import uuid4 | random_line_split |
simple_db.py | # Copyright (c) 2016, Kevin Rodgers
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
import redis
from uuid import uuid4
UUID = 'uuid'
class SimpleRedisDb(object):
def __init__(self, host, key, port=6379):
"""
:param host: database host
:p... |
def _close_db(self):
"""
Closes database
:return:
"""
if self.redis is not None:
del self.redis
self.redis = None
def _clear_all(self):
"""
Removes all keys from hash set
:return:
"""
self._open_db()
... | self.redis = redis.Redis(connection_pool=redis.ConnectionPool(host=self.host, port=self.port, db=0)) | conditional_block |
simple_db.py | # Copyright (c) 2016, Kevin Rodgers
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
import redis
from uuid import uuid4
UUID = 'uuid'
class SimpleRedisDb(object):
def __init__(self, host, key, port=6379):
"""
:param host: database host
:p... | """
Update/replace record dictionary by UUID
:param record_key: UUID
:param record_dict: volume dictionary
:return:
"""
self._open_db()
record_dict[UUID] = record_key
self.redis.hset(self.key, record_dict[UUID], unicode(record_dict)) | identifier_body | |
simple_db.py | # Copyright (c) 2016, Kevin Rodgers
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
import redis
from uuid import uuid4
UUID = 'uuid'
class SimpleRedisDb(object):
def __init__(self, host, key, port=6379):
"""
:param host: database host
:p... | (self):
"""
Return a list of all records
:return:
list of all record dictionaries
"""
self._open_db()
all_records = []
record_keys = self.redis.hkeys(self.key)
for u in record_keys:
record_str = self.redis.hget(self.key, u)
... | get_all_records | identifier_name |
switch.py | """Support for Hydrawise cloud switches."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import (
ALLOWED_WATERING_TIME, CONF_... | (self, **kwargs):
"""Turn the device on."""
if self._sensor_type == 'manual_watering':
self.hass.data[DATA_HYDRAWISE].data.run_zone(
self._default_watering_timer, (self.data['relay']-1))
elif self._sensor_type == 'auto_watering':
self.hass.data[DATA_HYDRAW... | turn_on | identifier_name |
switch.py | """Support for Hydrawise cloud switches."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import (
ALLOWED_WATERING_TIME, CONF_... |
def turn_off(self, **kwargs):
"""Turn the device off."""
if self._sensor_type == 'manual_watering':
self.hass.data[DATA_HYDRAWISE].data.run_zone(
0, (self.data['relay']-1))
elif self._sensor_type == 'auto_watering':
self.hass.data[DATA_HYDRAWISE].data... | """A switch implementation for Hydrawise device."""
def __init__(self, default_watering_timer, *args):
"""Initialize a switch for Hydrawise device."""
super().__init__(*args)
self._default_watering_timer = default_watering_timer
@property
def is_on(self):
"""Return true if ... | identifier_body |
switch.py | """Support for Hydrawise cloud switches."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import (
ALLOWED_WATERING_TIME, CONF_... |
elif self._sensor_type == 'auto_watering':
for relay in mydata.relays:
if relay['relay'] == self.data['relay']:
if relay.get('suspended') is not None:
self._state = False
else:
self._state = True... | if not mydata.running:
self._state = False
else:
self._state = int(
mydata.running[0]['relay']) == self.data['relay'] | conditional_block |
switch.py | """Support for Hydrawise cloud switches."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import (
ALLOWED_WATERING_TIME, CONF_... | vol.All(vol.In(ALLOWED_WATERING_TIME)),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a sensor for a Hydrawise device."""
hydrawise = hass.data[DATA_HYDRAWISE].data
default_watering_timer = config.get(CONF_WATERING_TIME)
sensors = []
for sensor_type in... |
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_MONITORED_CONDITIONS, default=SWITCHES):
vol.All(cv.ensure_list, [vol.In(SWITCHES)]),
vol.Optional(CONF_WATERING_TIME, default=DEFAULT_WATERING_TIME): | random_line_split |
trimmed.spec.ts | import 'mocha';
import { trimmed } from '../../src/io';
import { expect } from '../expect';
describe ('`trimmed` tag function', () => {
/** @test {trimmed} */
it('trims the leading and trailing whitespace', () => {
expect(trimmed ` Hello world! `).to.equal('Hello world!');
});
/** @test {t... |
/** @test {trimmed} */
it('trims padded multi-line string', () => {
expect(trimmed `
| const SomeInteraction = () =>
| Interaction.where(\`${ '#actor interacts with the system' }\`, (actor: Actor) => {
| // use actor's abilities to interact with the syste... | '',
'✓ Execution successful (10ms)',
'',
].join('\n'));
}); | random_line_split |
DetectionEvents.d.ts | export declare enum DetectionEvents {
/**
* Event triggered by a audio detector indicating that its active state has changed from active to inactive or vice
* versa.
* @event
* @type {boolean} - true when service has changed to active false otherwise.
*/
DETECTOR_STATE_CHANGE = "detecto... | export declare const VAD_SCORE_PUBLISHED = DetectionEvents.VAD_SCORE_PUBLISHED;
export declare const VAD_TALK_WHILE_MUTED = DetectionEvents.VAD_TALK_WHILE_MUTED; | export declare const VAD_NOISY_DEVICE = DetectionEvents.VAD_NOISY_DEVICE;
export declare const VAD_REPORT_PUBLISHED = DetectionEvents.VAD_REPORT_PUBLISHED; | random_line_split |
specificworker.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 by YOUR NAME HERE
#
# This file is part of RoboComp
#
# RoboComp 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 o... |
#
# sm_finalize
#
@QtCore.Slot()
def sm_finalize(self):
print("Entered state finalize")
# QApplication.quit()
# =================================================================
# =================================================================
| self.compute() | identifier_body |
specificworker.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 by YOUR NAME HERE
#
# This file is part of RoboComp
#
# RoboComp 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 o... | (self):
print("Entered state initialize")
if os.getuid() != 0:
print("You need root privileges to run this component\nTry executing using 'sudo' before the call")
self.t_initialize_to_finalize.emit()
else:
_original = deca.is_decawave_scan_entry
d... | sm_initialize | identifier_name |
specificworker.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 by YOUR NAME HERE
#
# This file is part of RoboComp
#
# RoboComp 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 o... | def setParams(self, params):
# try:
# self.innermodel = InnerModel(params["InnerModelPath"])
# except:
# traceback.print_exc()
# print("Error reading config params")
return True
@QtCore.Slot()
def compute(self):
data = None
for x in range(4):
... | print('SpecificWorker destructor')
self.t_compute_to_finalize.emit()
| random_line_split |
specificworker.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 by YOUR NAME HERE
#
# This file is part of RoboComp
#
# RoboComp 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 o... |
taglist = []
if data is not None:
for key, device in data.items():
if device is not None and "location_data" in device:
position = PointUWB()
if device["location_data"] is None:
continue
if ... | try:
data = deca.get_data_multiple_devices(self.devicelist)
if data is not None:
break
except Ice.Exception as e:
traceback.print_exc()
print(e)
self.t_compute_to_finalize.emit()
break
... | conditional_block |
ChunkTemplate.ts | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
import { Hash } from 'crypto'
import { ConcatSource } from 'webpack-sources'
import { WebpackOutputOptions } from '../typings/webpack-types'
import Template = require('./Template');
import Chunk = require('./Chunk')
imp... |
chunk.rendered = true;
return new ConcatSource(source, ';');
}
updateHash(hash: Hash) {
hash.update('ChunkTemplate');
hash.update('2');
this.applyPlugins('hash', hash);
}
updateHashForChunk(hash: Hash, chunk?: Chunk) {
this.updateHash(hash);
thi... | {
source = this.applyPluginsWaterfall('render-with-entry', source, chunk);
} | conditional_block |
ChunkTemplate.ts | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
import { Hash } from 'crypto'
import { ConcatSource } from 'webpack-sources'
import { WebpackOutputOptions } from '../typings/webpack-types'
import Template = require('./Template');
import Chunk = require('./Chunk')
imp... |
updateHash(hash: Hash) {
hash.update('ChunkTemplate');
hash.update('2');
this.applyPlugins('hash', hash);
}
updateHashForChunk(hash: Hash, chunk?: Chunk) {
this.updateHash(hash);
this.applyPlugins('hash-for-chunk', hash, chunk);
}
}
export = ChunkTemplate;
| {
const moduleSources = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates);
const core = this.applyPluginsWaterfall('modules', moduleSources, chunk, moduleTemplate, dependencyTemplates);
let source = this.applyPluginsWaterfall('render', core, chunk, moduleTemplate, dependencyTem... | identifier_body |
ChunkTemplate.ts | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
import { Hash } from 'crypto'
import { ConcatSource } from 'webpack-sources'
import { WebpackOutputOptions } from '../typings/webpack-types'
import Template = require('./Template');
import Chunk = require('./Chunk')
imp... | this.updateHash(hash);
this.applyPlugins('hash-for-chunk', hash, chunk);
}
}
export = ChunkTemplate; | random_line_split | |
ChunkTemplate.ts | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
import { Hash } from 'crypto'
import { ConcatSource } from 'webpack-sources'
import { WebpackOutputOptions } from '../typings/webpack-types'
import Template = require('./Template');
import Chunk = require('./Chunk')
imp... | (hash: Hash, chunk?: Chunk) {
this.updateHash(hash);
this.applyPlugins('hash-for-chunk', hash, chunk);
}
}
export = ChunkTemplate;
| updateHashForChunk | identifier_name |
setup.py | from setuptools import setup, find_packages
import os
import allensdk
# http://bugs.python.org/issue8876#msg208792
if hasattr(os, 'link'):
del os.link
def prepend_find_packages(*roots):
|
setup(
version = allensdk.__version__,
name = 'allensdk',
author = 'David Feng',
author_email = 'davidf@alleninstitute.org',
packages = prepend_find_packages('allensdk'),
package_data={'': ['*.conf', '*.cfg', '*.md', '*.json', '*.dat', '*.env', '*.sh', 'bps', 'Makefile', 'COPYING'] },
desc... | ''' Recursively traverse nested packages under the root directories
'''
packages = []
for root in roots:
packages += [root]
packages += [root + '.' + s for s in find_packages(root)]
return packages | identifier_body |
setup.py | from setuptools import setup, find_packages
import os
import allensdk
# http://bugs.python.org/issue8876#msg208792
if hasattr(os, 'link'):
del os.link
def | (*roots):
''' Recursively traverse nested packages under the root directories
'''
packages = []
for root in roots:
packages += [root]
packages += [root + '.' + s for s in find_packages(root)]
return packages
setup(
version = allensdk.__version__,
name = 'allens... | prepend_find_packages | identifier_name |
setup.py | from setuptools import setup, find_packages
import os
import allensdk
# http://bugs.python.org/issue8876#msg208792
if hasattr(os, 'link'):
del os.link
def prepend_find_packages(*roots):
''' Recursively traverse nested packages under the root directories
'''
packages = []
for root in roots:
... |
return packages
setup(
version = allensdk.__version__,
name = 'allensdk',
author = 'David Feng',
author_email = 'davidf@alleninstitute.org',
packages = prepend_find_packages('allensdk'),
package_data={'': ['*.conf', '*.cfg', '*.md', '*.json', '*.dat', '*.env', '*.sh', 'bps', 'Make... | packages += [root]
packages += [root + '.' + s for s in find_packages(root)] | conditional_block |
setup.py | from setuptools import setup, find_packages
import os
import allensdk
# http://bugs.python.org/issue8876#msg208792
if hasattr(os, 'link'):
del os.link
def prepend_find_packages(*roots):
''' Recursively traverse nested packages under the root directories
'''
packages = [] | packages += [root]
packages += [root + '.' + s for s in find_packages(root)]
return packages
setup(
version = allensdk.__version__,
name = 'allensdk',
author = 'David Feng',
author_email = 'davidf@alleninstitute.org',
packages = prepend_find_packages('allensdk'),
pa... |
for root in roots: | random_line_split |
mod.rs | /* Copyright (C) 2022 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | pub mod pgsql; | pub mod logger;
pub mod parser; | random_line_split |
lib.rs | use std::char;
use std::collections::HashMap;
#[derive(PartialEq)]
enum Cell {
Empty,
Mine,
}
fn neighbors(x1: usize, y1: usize, x2: usize, y2: usize) -> bool {
let x1 = x1 as isize;
let x2 = x2 as isize;
let y1 = y1 as isize;
let y2 = y2 as isize;
x1 - 1 == x2 && y1 - 1 == y2 || x1 == x... | (board: &Vec<&str>) -> Vec<String> {
let mut cells: HashMap<(usize, usize), Cell> = HashMap::new();
let height = board.len();
let width = board[0].len();
for (y, row) in board.iter().enumerate() {
for (x, cell) in row.chars().enumerate() {
let c = match cell {
' ' =>... | annotate | identifier_name |
lib.rs | use std::char;
use std::collections::HashMap;
#[derive(PartialEq)]
enum Cell {
Empty,
Mine,
}
fn neighbors(x1: usize, y1: usize, x2: usize, y2: usize) -> bool {
let x1 = x1 as isize;
let x2 = x2 as isize; | x1 - 1 == x2 && y1 + 1 == y2 ||
x1 == x2 && y1 + 1 == y2 || x1 + 1 == x2 && y1 + 1 == y2 || x1 - 1 == x2 && y1 == y2 ||
x1 + 1 == x2 && y1 == y2
}
fn calc_value(x: usize, y: usize, cells: &HashMap<(usize, usize), Cell>) -> char {
let mut n = 0;
for (&(cx, cy), cell) in cells.iter() {
if nei... | let y1 = y1 as isize;
let y2 = y2 as isize;
x1 - 1 == x2 && y1 - 1 == y2 || x1 == x2 && y1 - 1 == y2 || x1 + 1 == x2 && y1 - 1 == y2 || | random_line_split |
String.js | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | ruler.innerHTML = this;
return ruler.offsetWidth;
};
/**
* Set an ellipsis on a string
*/
String.prototype.ellipsis = function(length) {
var temp = this;
var trimmed = this;
if (temp.visualLength() > length) {
trimmed += "...";
while (trimmed.visualLength() > length) {
temp = temp.substring(... | var ruler = document.getElementById('htmlarea-ruler'); | random_line_split |
String.js | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... |
}
return trimmed;
};
});
| {
temp = temp.substring(0, temp.length-1);
trimmed = temp + "...";
} | conditional_block |
webpack.config.js | /* eslint-disable */
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = (env = { dev: true }) => ({
entry: env.dev
? path.resolve(__dirname, 'examples', 'index.js')
: path.resolve(__dirname, 'lib',... | rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
]
}
}); | ignored: /node_modules/,
},
} : undefined,
module: { | random_line_split |
options.rs | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#![deny(missing_docs)]
use {std::collections::HashMap, std::collections::HashSet, std::hash::Hash, std::hash::Hasher};
/// Options that can be applied to specif... |
}
impl Eq for PathOption {}
impl Hash for PathOption {
fn hash<H: Hasher>(&self, state: &mut H) {
use PathOption::*;
state.write_u32(match self {
TrailingCommas(..) => 1,
CollapseContainersOfOne(..) => 2,
SortArrayItems(..) => 3,
PropertyNameOrder(.... | {
use PathOption::*;
match (self, other) {
(&TrailingCommas(..), &TrailingCommas(..)) => true,
(&CollapseContainersOfOne(..), &CollapseContainersOfOne(..)) => true,
(&SortArrayItems(..), &SortArrayItems(..)) => true,
(&PropertyNameOrder(..), &PropertyNameO... | identifier_body |
options.rs | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#![deny(missing_docs)]
use {std::collections::HashMap, std::collections::HashSet, std::hash::Hash, std::hash::Hasher};
/// Options that can be applied to specif... | fn eq(&self, other: &Self) -> bool {
use PathOption::*;
match (self, other) {
(&TrailingCommas(..), &TrailingCommas(..)) => true,
(&CollapseContainersOfOne(..), &CollapseContainersOfOne(..)) => true,
(&SortArrayItems(..), &SortArrayItems(..)) => true,
... | /// and placed after the sorted properties.
PropertyNameOrder(Vec<&'static str>),
}
impl PartialEq for PathOption { | random_line_split |
options.rs | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#![deny(missing_docs)]
use {std::collections::HashMap, std::collections::HashSet, std::hash::Hash, std::hash::Hasher};
/// Options that can be applied to specif... | () -> Self {
FormatOptions {
indent_by: 4,
trailing_commas: true,
collapse_containers_of_one: false,
sort_array_items: false,
options_by_path: HashMap::new(),
}
}
}
| default | identifier_name |
app01.js | /**
* Created by USER: tarso.
* On DATE: 29/08/16.
* By NAME: app01.js.
*/
/** | */
'use strict'
var bs = require("black-scholes");
var nCall;
var nPut;
var nS; // Current price of the underlying
var nK; // Strike price
var nTime; // Time to expiration in years
var nVolatility; // Volatility as a decimal
var nRisk; // Annual risk-free interest rate as a decimal
var ... | * black-scholes
*
* Source: https://www.npmjs.com/package/black-scholes | random_line_split |
factories_basic_type.ts | /**
* @module node-opcua-factory
*/
import * as _ from "underscore";
import * as util from "util";
import { assert } from "node-opcua-assert";
import { decodeLocaleId, encodeLocaleId, validateLocaleId } from "node-opcua-basic-types";
import { BinaryStream, OutputBinaryStream } from "node-opcua-binary-stream";
impo... |
const name = schema.name;
const t: BasicTypeDefinition = findSimpleType(schema.subType);
/* istanbul ignore next */
if (!t) {
// tslint:disable-next-line:no-console
console.log(util.inspect(schema, { colors: true}));
throw new Error(" cannot find subtype " + schema.subType);
... | {
// tslint:disable-next-line: no-console
console.log(schema);
throw new Error(`Basic Type ${schema.name} already registered`);
} | conditional_block |
factories_basic_type.ts | /**
* @module node-opcua-factory
*/
import * as _ from "underscore";
import * as util from "util";
import { assert } from "node-opcua-assert";
import { decodeLocaleId, encodeLocaleId, validateLocaleId } from "node-opcua-basic-types";
import { BinaryStream, OutputBinaryStream } from "node-opcua-binary-stream";
impo... |
const encodeFunc = schema.encode || t.encode;
assert(_.isFunction(encodeFunc));
const decodeFunc = schema.decode || t.decode;
assert(_.isFunction(decodeFunc));
const defaultValue = (schema.defaultValue === undefined) ? t.defaultValue : schema.defaultValue;
// assert(_.isFunction(defaultValue)... | {
const exists: boolean = hasBuiltInType(schema.name);
if (exists) {
// tslint:disable-next-line: no-console
console.log(schema);
throw new Error(`Basic Type ${schema.name} already registered`);
}
const name = schema.name;
const t: BasicTypeDefinition = findSimpleType(sche... | identifier_body |
factories_basic_type.ts | /**
* @module node-opcua-factory
*/
import * as _ from "underscore";
import * as util from "util";
import { assert } from "node-opcua-assert";
import { decodeLocaleId, encodeLocaleId, validateLocaleId } from "node-opcua-basic-types";
import { BinaryStream, OutputBinaryStream } from "node-opcua-binary-stream";
impo... | (schema: BasicTypeOptions) {
const exists: boolean = hasBuiltInType(schema.name);
if (exists) {
// tslint:disable-next-line: no-console
console.log(schema);
throw new Error(`Basic Type ${schema.name} already registered`);
}
const name = schema.name;
const t: BasicTypeDefin... | registerBasicType | identifier_name |
factories_basic_type.ts | /**
* @module node-opcua-factory
*/
import * as _ from "underscore";
import * as util from "util";
import { assert } from "node-opcua-assert";
import { decodeLocaleId, encodeLocaleId, validateLocaleId } from "node-opcua-basic-types";
import { BinaryStream, OutputBinaryStream } from "node-opcua-binary-stream";
impo... | registerBasicType({ name: "AccessRestrictionType", subType: "UInt32" });
registerBasicType({ name: "NormalizedString", subType: "String" });
registerBasicType({ name: "DecimalString", subType: "String" });
registerBasicType({ name: "DurationString", subType: "String" });
registerBasicType({ name: "TimeString", subType:... | registerBasicType({ name: "AccessLevelExType", subType: "UInt32" });
registerBasicType({ name: "EventNotifierType", subType: "Byte" }); | random_line_split |
app.js | $(function() {
$(".navbar-expand-toggle").click(function() {
$(".app-container").toggleClass("expanded");
return $(".navbar-expand-toggle").toggleClass("fa-rotate-90");
});
return $(".navbar-right-expand-toggle").click(function() {
$(".navbar-right").toggleClass("expanded");
return $(".navbar-righ... | return $(".side-menu .nav .dropdown .collapse").collapse('hide');
});
}); | });
});
$(function() {
return $(".side-menu .nav .dropdown").on('show.bs.collapse', function() { | random_line_split |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... |
fn answer1(lines: &[String]) -> usize {
let mut g = Grid::new();
for line in lines.iter() {
parse_and_run(&mut g, line.as_str());
}
g.values().filter(|i| **i).count()
}
type Grid2 = HashMap<(usize, usize), usize>;
fn on(g: &mut Grid2, i: usize, j: usize) {
let e = g.entry((i, j)).or_inse... | {
let p = Path::new("data/input.txt");
match File::open(&p) {
Err(e) => panic!("Couldn't open {}: {}", p.display(), e.description()),
Ok(f) => BufReader::new(f).lines(),
}
} | identifier_body |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... | (g: &mut Grid2, i: usize, j: usize) {
let e = g.entry((i, j)).or_insert(0);
*e = e.saturating_add(2);
}
fn pnr(g: &mut Grid2, s: &str) {
let f = if s.starts_with("turn on") {
on
} else if s.starts_with("turn off") {
off
} else {
tog
};
let (i0, j0, i1, j1) = parse_pa... | tog | identifier_name |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... |
fn toggle(g: &mut Grid, i: usize, j: usize) {
let e = g.entry((i, j)).or_insert(false);
*e = !*e;
}
fn parse_pairs(s: &str) -> (usize, usize, usize, usize) {
lazy_static! {
static ref RE: Regex = Regex::new(
"([0-9]+),([0-9]+) through ([0-9]+),([0-9]+)"
).unwrap();
}
... | random_line_split | |
main.rs | extern crate regex;
#[macro_use]
extern crate lazy_static;
use regex::Regex;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::Lines;
use std::io::prelude::*;
use std::collections::HashMap;
use std::path::Path;
type Grid = HashMap<(usize, usize), bool>;
fn turn_on(g: &mut Grid, i: usize, ... | else {
toggle
};
let (i0, j0, i1, j1) = parse_pairs(s);
for i in i0..i1 + 1 {
for j in j0..j1 + 1 {
f(g, i, j);
}
}
}
#[test]
fn _t() {
let mut g = Grid::new();
parse_and_run(&mut g, "turn on 0,0 through 999,999");
for i in 0..999 {
for j in 0..9... | {
turn_off
} | conditional_block |
courses.py |
from static_replace import replace_static_urls
from courseware.access import has_access
import branding
log = logging.getLogger(__name__)
def get_request_for_thread():
"""Walk up the stack, return the nearest first argument named "request"."""
frame = None
try:
for f in inspect.stack()[1:]:
... |
Returns d / filename if found in dir d, else raises ResourceNotFoundError.
"""
for directory in dirs:
filepath = path(directory) / filename
if filesystem.exists(filepath):
return filepath
raise ResourceNotFoundError("Could not find {0}".format(filename))
def get_course_abo... |
filesystem: an OSFS filesystem
dirs: a list of path objects
filename: a string | random_line_split |
courses.py |
from static_replace import replace_static_urls
from courseware.access import has_access
import branding
log = logging.getLogger(__name__)
def get_request_for_thread():
"""Walk up the stack, return the nearest first argument named "request"."""
frame = None
try:
for f in inspect.stack()[1:]:
... |
finally:
del frame
def get_course(course_id, depth=0):
"""
Given a course id, return the corresponding course descriptor.
If course_id is not valid, raises a ValueError. This is appropriate
for internal use.
depth: The number of levels of children for the modulestore to cache.
... | return frame.f_locals["request"] | conditional_block |
courses.py |
from static_replace import replace_static_urls
from courseware.access import has_access
import branding
log = logging.getLogger(__name__)
def get_request_for_thread():
"""Walk up the stack, return the nearest first argument named "request"."""
frame = None
try:
for f in inspect.stack()[1:]:
... |
def course_image_url(course):
"""Try to look up the image url for the course. If it's not found,
log an error and return the dead link"""
if course.static_asset_path or modulestore().get_modulestore_type(course.location.course_id) == XML_MODULESTORE_TYPE:
return '/static/' + (course.static_asset... | """
Same as get_course_with_access, except that if course_id is None,
return None without performing any access checks.
"""
if course_id is None:
return None
return get_course_with_access(user, course_id, action) | identifier_body |
courses.py |
from static_replace import replace_static_urls
from courseware.access import has_access
import branding
log = logging.getLogger(__name__)
def get_request_for_thread():
"""Walk up the stack, return the nearest first argument named "request"."""
frame = None
try:
for f in inspect.stack()[1:]:
... | (course_id, depth=0):
"""
Given a course id, return the corresponding course descriptor.
If course_id is not valid, raises a ValueError. This is appropriate
for internal use.
depth: The number of levels of children for the modulestore to cache.
None means infinite depth. Default is to fetch ... | get_course | identifier_name |
peoplegui--frame.py | """
See peoplegui--old.py: the alternative here uses nedted row frames with fixed
widdth labels with pack() to acheive the same aligned layout as grid(), but it
takes two extra lines of code as is (though adding window resize support makes
the two techniques roughly the same--see later in the book).
"""
from tk... | ():
global entries
window = Tk()
window.title('People Shelve')
form = Frame(window)
form.pack()
entries = {}
for label in ('key',) + fieldnames:
row = Frame(form)
lab = Label(row, text=label, width=6)
ent = Entry(row)
row.pack(side=TOP)
l... | makeWidgets | identifier_name |
peoplegui--frame.py | """
See peoplegui--old.py: the alternative here uses nedted row frames with fixed
widdth labels with pack() to acheive the same aligned layout as grid(), but it
takes two extra lines of code as is (though adding window resize support makes
the two techniques roughly the same--see later in the book).
"""
from tk... |
db[key] = record
db = shelve.open(shelvename)
window = makeWidgets()
window.mainloop()
db.close() # back here after quit or window close
| setattr(record, field, eval(entries[field].get())) | conditional_block |
peoplegui--frame.py | """
See peoplegui--old.py: the alternative here uses nedted row frames with fixed
widdth labels with pack() to acheive the same aligned layout as grid(), but it
takes two extra lines of code as is (though adding window resize support makes
the two techniques roughly the same--see later in the book).
"""
from tk... | db = shelve.open(shelvename)
window = makeWidgets()
window.mainloop()
db.close() # back here after quit or window close | for field in fieldnames:
setattr(record, field, eval(entries[field].get()))
db[key] = record
| random_line_split |
peoplegui--frame.py | """
See peoplegui--old.py: the alternative here uses nedted row frames with fixed
widdth labels with pack() to acheive the same aligned layout as grid(), but it
takes two extra lines of code as is (though adding window resize support makes
the two techniques roughly the same--see later in the book).
"""
from tk... |
db = shelve.open(shelvename)
window = makeWidgets()
window.mainloop()
db.close() # back here after quit or window close
| key = entries['key'].get()
if key in db:
record = db[key] # update existing record
else:
from person import Person # make/store new one for key
record = Person(name='?', age='?') # eval: strings must be quoted
for field in fieldnames:
... | identifier_body |
random_seed.rs | use chapter2::dungeon::{Dungeon};
use chapter2::genotype::{Genotype};
use chapter2::phenotype::{Seed};
use rand::{Rng, thread_rng};
#[derive(Clone, Debug)]
pub struct RandomSeed {
seed: Seed,
}
impl RandomSeed {
pub fn new(seed: &Seed) -> RandomSeed {
RandomSeed {
seed: seed.clone(),
... |
dungeon.set_tile(i, j, &tile);
}
}
dungeon.clone()
}
}
| {
dungeon.set_occupant(i, j, &occupant);
} | conditional_block |
random_seed.rs | use chapter2::dungeon::{Dungeon};
use chapter2::genotype::{Genotype};
use chapter2::phenotype::{Seed};
use rand::{Rng, thread_rng};
#[derive(Clone, Debug)]
pub struct RandomSeed {
seed: Seed,
}
impl RandomSeed { | RandomSeed {
seed: seed.clone(),
}
}
}
impl Genotype for RandomSeed {
fn generate(&self) -> Dungeon {
let mut rng = thread_rng();
let w = self.seed.width;
let h = self.seed.height;
let mut dungeon = Dungeon::new(w, h, None);
for i in 0..dungeo... | pub fn new(seed: &Seed) -> RandomSeed { | random_line_split |
random_seed.rs | use chapter2::dungeon::{Dungeon};
use chapter2::genotype::{Genotype};
use chapter2::phenotype::{Seed};
use rand::{Rng, thread_rng};
#[derive(Clone, Debug)]
pub struct RandomSeed {
seed: Seed,
}
impl RandomSeed {
pub fn new(seed: &Seed) -> RandomSeed {
RandomSeed {
seed: seed.clone(),
... | (&self) -> Dungeon {
let mut rng = thread_rng();
let w = self.seed.width;
let h = self.seed.height;
let mut dungeon = Dungeon::new(w, h, None);
for i in 0..dungeon.width as u32 {
for j in 0..dungeon.height as u32 {
let tile = self.seed.tiles.choose(&mu... | generate | identifier_name |
generic-static-methods.rs | // Copyright 2013 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 ... | } | random_line_split | |
generic-static-methods.rs | // Copyright 2013 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 ... |
}
pub fn main() {
assert_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
}
| {
let mut r = Vec::new();
for elt in x.iter() {
r.push(f(elt));
}
r
} | identifier_body |
generic-static-methods.rs | // Copyright 2013 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 ... | <U>(x: &Vec<T> , f: |&T| -> U) -> Vec<U> {
let mut r = Vec::new();
for elt in x.iter() {
r.push(f(elt));
}
r
}
}
pub fn main() {
assert_eq!(vec_utils::map_(&vec!(1,2,3), |&x| x+1), vec!(2,3,4));
}
| map_ | identifier_name |
item_allocator.py | # Copyright 2015 IBM Corporation
#
# 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 ag... |
def _read(self):
if not os.path.exists(self.state_file):
return []
with open(self.state_file) as f:
return f.readlines()
| with open(self.state_file, "w") as f:
f.writelines(lines) | identifier_body |
item_allocator.py | # Copyright 2015 IBM Corporation
#
# 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 ag... |
self.allocations[key] = self.pool.pop()
self._write_allocations()
return self.allocations[key]
def release(self, key):
if self.lookup(key):
self.pool.add(self.allocations.pop(key))
self._write_allocations()
def _write_allocations(self):
current... | self.pool.update(self.remembered.values())
self.remembered.clear()
if not self.pool:
# The number of address pairs allocated from the
# pool depends upon the prefix length specified
# in DVR_FIP_LL_CIDR
raise RuntimeError(_("Cannot ... | conditional_block |
item_allocator.py | # Copyright 2015 IBM Corporation
#
# 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 ag... | with open(self.state_file) as f:
return f.readlines() | random_line_split | |
item_allocator.py | # Copyright 2015 IBM Corporation
#
# 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 ag... | (self):
current = ["%s,%s\n" % (k, v) for k, v in self.allocations.items()]
remembered = ["%s,%s\n" % (k, v) for k, v in self.remembered.items()]
current.extend(remembered)
self._write(current)
def _write(self, lines):
with open(self.state_file, "w") as f:
f.writ... | _write_allocations | identifier_name |
wagtail_hooks.py | from django.core import urlresolvers
from django.conf.urls import include, url
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailforms import urls
from wagtail.wagtailforms.models import get_forms_for_user
... |
class FormsMenuItem(MenuItem):
def is_shown(self, request):
# show this only if the user has permission to retrieve submissions for at least one form
return get_forms_for_user(request.user).exists()
@hooks.register('register_admin_menu_item')
def register_forms_menu_item():
return FormsMenu... | return [
url(r'^forms/', include(urls, app_name='wagtailforms', namespace='wagtailforms')),
] | identifier_body |
wagtail_hooks.py | from django.core import urlresolvers
from django.conf.urls import include, url
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
| from wagtail.wagtailforms.models import get_forms_for_user
@hooks.register('register_admin_urls')
def register_admin_urls():
return [
url(r'^forms/', include(urls, app_name='wagtailforms', namespace='wagtailforms')),
]
class FormsMenuItem(MenuItem):
def is_shown(self, request):
# show th... | from wagtail.wagtailforms import urls | random_line_split |
wagtail_hooks.py | from django.core import urlresolvers
from django.conf.urls import include, url
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailforms import urls
from wagtail.wagtailforms.models import get_forms_for_user
... | (MenuItem):
def is_shown(self, request):
# show this only if the user has permission to retrieve submissions for at least one form
return get_forms_for_user(request.user).exists()
@hooks.register('register_admin_menu_item')
def register_forms_menu_item():
return FormsMenuItem(
_('Forms... | FormsMenuItem | identifier_name |
collection.d.ts | /**
* Wraps Javascript Objects
*/
export declare class StringMapWrapper {
static merge<V>(m1: {
[key: string]: V;
}, m2: {
[key: string]: V;
}): {
[key: string]: V;
};
static equals<V>(m1: {
[key: string]: V;
}, m2: {
[key: string]: V;
}): boolean;
}... | {
static findLast<T>(arr: T[], condition: (value: T) => boolean): T;
static removeAll<T>(list: T[], items: T[]): void;
static remove<T>(list: T[], el: T): boolean;
static equals(a: any[], b: any[]): boolean;
static flatten<T>(list: Array<T | T[]>): T[];
}
export declare function isListLikeIterable(... | ListWrapper | identifier_name |
collection.d.ts | /**
* Wraps Javascript Objects
*/
export declare class StringMapWrapper {
static merge<V>(m1: {
[key: string]: V;
}, m2: {
[key: string]: V;
}): {
[key: string]: V;
};
static equals<V>(m1: {
[key: string]: V;
}, m2: {
[key: string]: V;
}): boolean;
} | */
export interface Predicate<T> {
(value: T, index?: number, array?: T[]): boolean;
}
export declare class ListWrapper {
static findLast<T>(arr: T[], condition: (value: T) => boolean): T;
static removeAll<T>(list: T[], items: T[]): void;
static remove<T>(list: T[], el: T): boolean;
static equals(a... | /**
* A boolean-valued function over a value, possibly including context information
* regarding that value's position in an array. | random_line_split |
sodium.rs | extern crate sodiumoxide;
use errors::prelude::*;
use failure::{err_msg, ResultExt};
use self::sodiumoxide::crypto::secretbox;
use self::sodiumoxide::crypto::secretbox::xsalsa20poly1305;
pub const KEYBYTES: usize = xsalsa20poly1305::KEYBYTES;
pub const NONCEBYTES: usize = xsalsa20poly1305::NONCEBYTES;
pub const MACBY... | (key: &Key, nonce: &Nonce, doc: &[u8]) -> (Vec<u8>, Tag) {
let mut cipher = doc.to_vec();
let tag = secretbox::seal_detached(cipher.as_mut_slice(),
&nonce.0,
&key.0);
(cipher, Tag(tag))
}
pub fn decrypt_detached(key: &Key, nonce: &Nonce, tag... | encrypt_detached | identifier_name |
sodium.rs | extern crate sodiumoxide;
use errors::prelude::*;
use failure::{err_msg, ResultExt};
use self::sodiumoxide::crypto::secretbox;
use self::sodiumoxide::crypto::secretbox::xsalsa20poly1305;
pub const KEYBYTES: usize = xsalsa20poly1305::KEYBYTES;
pub const NONCEBYTES: usize = xsalsa20poly1305::NONCEBYTES;
pub const MACBY... |
pub fn gen_nonce() -> Nonce {
Nonce(secretbox::gen_nonce())
}
pub fn encrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Vec<u8> {
secretbox::seal(
doc,
&nonce.0,
&key.0,
)
}
pub fn decrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Result<Vec<u8>, IndyError> {
secretbox::open(
... | {
Key(secretbox::gen_key())
} | identifier_body |
sodium.rs | extern crate sodiumoxide;
use errors::prelude::*;
use failure::{err_msg, ResultExt};
use self::sodiumoxide::crypto::secretbox;
use self::sodiumoxide::crypto::secretbox::xsalsa20poly1305;
pub const KEYBYTES: usize = xsalsa20poly1305::KEYBYTES;
pub const NONCEBYTES: usize = xsalsa20poly1305::NONCEBYTES;
pub const MACBY... |
pub fn gen_nonce() -> Nonce {
Nonce(secretbox::gen_nonce())
}
pub fn encrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Vec<u8> {
secretbox::seal(
doc,
&nonce.0,
&key.0,
)
}
pub fn decrypt(key: &Key, nonce: &Nonce, doc: &[u8]) -> Result<Vec<u8>, IndyError> {
secretbox::open(
... | pub fn create_key() -> Key {
Key(secretbox::gen_key())
} | random_line_split |
mut-function-arguments.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 | // except according to those terms.
fn f(mut y: ~int) {
*y = 5;
assert!(*y == 5);
}
fn g() {
let frob: &fn(~int) = |mut q| { *q = 2; assert!(*q == 2); };
let w = ~37;
frob(w);
}
pub fn main() {
let z = ~17;
f(z);
g();
} | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
mut-function-arguments.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 ... |
pub fn main() {
let z = ~17;
f(z);
g();
}
| {
let frob: &fn(~int) = |mut q| { *q = 2; assert!(*q == 2); };
let w = ~37;
frob(w);
} | identifier_body |
mut-function-arguments.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 ... | (mut y: ~int) {
*y = 5;
assert!(*y == 5);
}
fn g() {
let frob: &fn(~int) = |mut q| { *q = 2; assert!(*q == 2); };
let w = ~37;
frob(w);
}
pub fn main() {
let z = ~17;
f(z);
g();
}
| f | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.